3

我设置了这个循环,它工作正常,但我希望能够单独更改每个 textView,所以我需要设置 textView.setId(whateveryouputinhere); 有人可以向我解释如何设置 id 以及括号内的内容吗?谢谢!

while (counter < 5) {
            view = LayoutInflater.from(getBaseContext()).inflate(R.layout.newplayerlayout, null);
            parent.addView(view); 
            TextView textView = (TextView) view.findViewById(R.id.textView2);
            textView.setText("Player "+counter);
            textView.setId(counter);
            counter++;

        }
4

2 回答 2

0

根据View文件,

标识符在此视图的层次结构中不必是唯一的。标识符应该是一个正数。

在这种情况下,可能会有一些具有等效 ID 的视图。如果您想在层次结构中搜索某些视图,setTag使用某些关键对象调用可能会很方便。

于 2012-05-25T02:04:50.067 回答
0

我设置了这个循环,它工作正常,但我希望能够单独更改每个 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(),这种方法相当昂贵,您应该尽量避免过度调用它。

于 2012-05-25T02:22:56.187 回答