在android中动态创建不同数量的textViews?

如何textView在运行时根据变化创建不同数量的sinteger而不显式实例化每个s的名称textView?textView创建的每个都需要有一个参考,因为我需要onClickListeners稍后应用到每个。


下面的代码工作得很好,但是我没有提到每个textViewfor onClickListeners:


    private void buildUI(){

    int variable_int = 3; //this variable changes at run-time, set to 3 for this example


for(int i = 1; i <= variable_int; i++){


            TextView textView = (TextView) findViewById(this);


            textView.setVisibility(View.VISIBLE);

            textView.setText("my textview");


            linLayout.addView(textView);


        }

}

我想到了一个解决方案,但java.lang.NumberFormatException在尝试转换R.id.box#为intfor时会产生异常findViewById():


protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_profile);


    //Create textViews in onCreate(). They are invisible by default

    TextView box1 = (TextView) findViewById(R.id.box1);

    TextView box2 = (TextView) findViewById(R.id.box2);

    TextView box3 = (TextView) findViewById(R.id.box3);

    TextView box4 = (TextView) findViewById(R.id.box4);

    TextView box5 = (TextView) findViewById(R.id.box5);


    buildUI();

 }


private void buildUI(){

int variable_int = 3; //this variable changes at run-time, set to 3 for this example


for(int i = 1; i <= variable_int; i++){


            String x = "R.id.box"+i;

            int xx = Integer.parseInt(x); //java.lang.NumberFormatException !


            TextView textView = (TextView) findViewById(xx);


            textView.setVisibility(View.VISIBLE);

            textView.setText("my textview");


            linLayout.addView(textView);


        }

}


qq_遁去的一_1
浏览 233回答 2
2回答

白猪掌柜的

您也许可以拥有一个TextViews数组,然后稍后对其进行循环。private TextView[] generatedViews;private void generateViews(int size) {&nbsp; &nbsp; this.generatedViews = new TextView[size];&nbsp; &nbsp; for (int i = 0; i < size; ++i) {&nbsp; &nbsp; &nbsp; &nbsp; TextView tv = new TextView(this);&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; generatedViews[i] = tv;&nbsp; &nbsp; }}private void assignListeners() {&nbsp; &nbsp; for (TextView tv : generatedViews) {&nbsp; &nbsp; &nbsp; &nbsp; tv.setOnClickListener(...);&nbsp; &nbsp; }}

呼如林

你也可以在创建 TextView 的同时创建一个事件for(int i = 1; i <= variable_int; i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; TextView textView = (TextView) findViewById(this);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; textView.setVisibility(View.VISIBLE);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; textView.setText("my textview");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;**textView.setOnClickListener(....);**&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; linLayout.addView(textView);&nbsp; &nbsp; &nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java