Android 在TextView中循环并设置文本
我正好有20个TextView,它们的id是按顺序排列的,即:Android 在TextView中循环并设置文本,android,textview,Android,Textview,我正好有20个TextView,它们的id是按顺序排列的,即: R.id.textView1, R.id.textView2, R.id.textView3 ... 我有一个for循环: for (int i = 1; i < 21; i++) { TextView textView = (TextView) findViewById(R.id.textView ...);// textView.setText("..."); 有没有办法使用此for循环获取TextV
R.id.textView1, R.id.textView2, R.id.textView3 ...
我有一个for循环:
for (int i = 1; i < 21; i++) {
TextView textView = (TextView) findViewById(R.id.textView ...);//
textView.setText("...");
有没有办法使用此for循环获取TextView并设置其文本?如果您将TextView设置为id R.id.textView1。。R.id.textView21,您可以使用getIdentifier从其名称检索TextViews id
for (int i = 1; i < 21; i++) {
String name = "textView"+i
int id = getResources().getIdentifier(name, "id", getPackageName());
if (id != 0) {
TextView textView = (TextView) findViewById(id);
}
}
更有效的方法是创建一个整数数组并对其进行迭代:
int[] textViewIDs = new int[] {R.id.textView1, R.id.textView2, R.id.textView3, ... };
for(int i=0; i < textViewIDs.length; i++) {
TextView tv = (TextView ) findViewById(textViewIDs[i]);
tv.setText("...");
}
这个线程非常稳定,但我面临着同样的需求:迭代我的布局结构,并在每个TextView上执行一些操作。在以多种方式将其谷歌化之后,我最终决定编写自己的实现。你可以在这里找到它:
/* Iterates through the given Layout, looking for TextView
---------------------------------
Author : Philippe Bartolini (PhB-fr @ GitHub)
Yes another iterator ;) I think it is very adaptable
*/
public void MyIterator(View thisView){
ViewGroup thisViewGroup = null;
boolean isTextView = false;
int childrenCount = 0;
try {
thisViewGroup = (ViewGroup) thisView;
childrenCount = thisViewGroup.getChildCount();
}
catch (Exception e){
}
if(childrenCount == 0){
try {
isTextView = ((TextView) thisView).getText() != null; // You can adapt it to your own neeeds.
}
catch (Exception e){
}
if(isTextView){
// do something
}
}
else {
for(int i = 0; i < childrenCount; i++){
MyIterator(thisViewGroup.getChildAt(i));
}
}
}