Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

android - How do I iterate through the id properties of R.java class?

I've 16 textViews and need to set something like this done:

for (int i=1; i<6; i++)
{
    int $RidInt = R.id.s; 
    tv[i] = (TextView)findViewById($RidInt);
    tv[i].setTypeface(face);
    tv[i].setClickable(true);
    tv[i].setOnClickListener(clickListener);
}

my R.java file is :

public final class R {
    public static final class attr {
    }
    public static final class drawable {
        public static final int icon=0x7f020000;
    }
    public static final class id {
        public static final int s1=0x7f050000;
        public static final int s10=0x7f050009;
        public static final int s11=0x7f05000a;
        public static final int s12=0x7f05000b;
        public static final int s13=0x7f05000c;
        public static final int s14=0x7f05000d;
        public static final int s15=0x7f05000e;
        public static final int s16=0x7f05000f;
        public static final int s2=0x7f050001;
        public static final int s3=0x7f050002;
        public static final int s4=0x7f050003;
        public static final int s5=0x7f050004;
        public static final int s6=0x7f050005;
        public static final int s7=0x7f050006;
        public static final int s8=0x7f050007;
        public static final int s9=0x7f050008;
    }
    public static final class layout {
        public static final int main=0x7f030000;
        public static final int toast=0x7f030001;
    }
    public static final class string {
        public static final int app_name=0x7f040000;
        public static final int s2=0x7f040001;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Something like that?

import java.lang.reflect.Field;
/* ... */

for (int i = 1; i < 16; i++) {
    int id = R.id.class.getField("s" + i).getInt(0);
    tv[i] = (TextView)findViewById(id);
    tv[i].setTypeface(face);
    tv[i].setClickable(true);
    tv[i].setOnClickListener(clickListener);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...