我设置了这个循环,它工作正常,但我希望能够单独更改每个 textView
行
所以我需要设置 textView.setId(whateveryouputinhere);
不,你没有,有更好的方法来实现你想要做的事情。
一个例子可能是这样的:
LayoutInflator mInflator; //You are creating 5 of these with your code, you don't need to.
mInflator = LayoutInflater.from(this); //Your activity is a context. So you pass it in, instead
//calling getBaseContext(). Which you should try avoid generally.
TextView[] mTxts = new TextView[5](this);
while (counter < 5) {
mTxts[counter] = (TextView)mInflator.inflate(R.layout.newplayerlayout, null);
parent.addView(view);
//TextView textView = (TextView) view.findViewById(R.id.textView2);
//You don't need this any more.
mTxts[counter].setText("Player "+counter);
//textView.setId(counter);
//don't need this either.
counter++;
}
//Now that your array is loaded you can set the text like this:
mTxts[0].setText("plums");
mTxts[2].setText("grapes");
请注意,我没有编译它,但它应该很接近。如果您在“this”上收到错误,请将它们更改为“YourActivity.this”,并使用您的活动类的名称。
有一些好处,通过保留 LayoutInflater 参考,您可以节省创建 4 个以上的参考。膨胀视图对象后,无需再通过 Id 找到它,您已经得到它。如果你愿意,你可以将它作为 TextView 直接从充气机中投射出来。通过将它们保存在一个数组中,您可以随时引用它们中的每一个,而不必再次调用 findViewById(),这种方法相当昂贵,您应该尽量避免过度调用它。