如何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);
}
}
白猪掌柜的
呼如林
相关分类