我已经苦恼了两天,仍然找不到解决方法,我认为我的面向对象编程基础知识很差。
现在我已经声明了大约二十个 TextView
,我想知道是否有一种方法可以将 TextView
存储到一个数组中,并使用 findViewById
找到它们?
我尝试使用一个数组,像这样:
public class MainActivity extends Activity {
private TextView name, address;
LinkedHashMap<Integer, TextView> demo = new LinkedHashMap<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int temp;
allTextview = new TextView[]{name, address};
for(int i=0; i<allTextview.length; i++){
temp = getResources().getIdentifier(allTextview[i], "id", getPackageName());
allTextview[i] = (TextView)findViewById(temp);
}
}}
这种方法会导致"name"和"allTextView[0]"指向的不是同一个对象。我还尝试了这个解决方案,但问题仍然存在。
我认为原因是"name"和"address"只是被声明了,并没有指向任何对象,我该怎么解决呢?
我想使用for循环来findViewById
,并且我可以同时使用"name"和"allTextView[0]"来对TextView
进行操作。
谢谢您的帮助,请原谅我的英语水平不太好。
name.setId(int)
- MKJParekhint[] ids = new int[]{R.id.nameTextView,R.id.addressTextView}
,然后for(int i=0;i<id.length;i++){allTextViews[i] = (TextView) findViewById(ids[i]);}
- W.K.S