How do you use setId in android?

I set up this loop and it works fine, but I would like to be able to change each textView individually, so I need to set up textView.setId (whathveryouputinhere); Can someone explain to me how to set the id and what you put in parentheses? Thank!

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++;

        }
+3
source share
2 answers

I am setting up this loop and it works fine, but I would like to be able to modify each textView separately

OK

so I need to configure textView.setId (anyway);

No, no, there are better ways to achieve what you are trying to do.

One example might be something like this:

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 . , , , . TextView , . , , findViewById(), , .

0

View ,

. .

. - , setTag , .

0

All Articles