Find TextView which was created programmatically?

风格不统一 提交于 2019-12-08 07:29:09

问题


How can I find those TextView's another function on same class? I will use setText(), serBackgroundColor() .. after create.

This code parts are on CreateDesign() and this func calling onCreate():

public class MainActivity extends AppCompatActivity {

private LinearLayout linearLayout;
private TextView textView;

public void CreateDesign(){

   linearLayout = (LinearLayout) findById(R.id.linearLayout);

   for(int i = 1; i <= 5; i++){
        textView = new TextView(this);
        textView.setId(i);
        textView.setText(i + ". TextView");

        linearLayout.addView(textView);
    }
}

回答1:


Well you don't necessarily need to use id here I show you two ways: 1-

TextView textView = (TextView) linearLayout.findViewById(i);

i is what you set before 1 to 5

2-

TextView textView = (TextView) linearLayout.getChildAt(i);

i here is the number of set item means 0 is the first textView to added using addView() method




回答2:


Either you create a member variable of this TextView which you can then use inside this class or you can use findViewById() on your LinearLayout.




回答3:


Use the normal findViewById() method. You're giving the TextViews unique IDs from 1 to 5, so you can find those TextViews by supplying 1-5 to findViewById().

However, you probably shouldn't be doing it this way, and you shouldn't have a global textView variable (it'll only hold a reference to the last-created TextView).

Instead, try using an ArrayList and adding all of your TextViews to it. Then you won't need to give them IDs that don't follow the standards.

public class MainActivity extends AppCompatActivity {

    private LinearLayout linearLayout;
    private ArrayList<TextView> textViews = new ArrayList<>();

    public void CreateDesign(){

        linearLayout = (LinearLayout) findById(R.id.linearLayout);

        for(int i = 1; i <= 5; i++) {
            TextView textView = new TextView(this);
            textView.setText(i + ". TextView");

            linearLayout.addView(textView);
            textViews.add(textView); //add it to the ArrayList
        }
    }
}



来源:https://stackoverflow.com/questions/54607294/find-textview-which-was-created-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!