我想在onClick方法上放置ArrayList。 但它告诉我,我应该将arraylist改为final(我会把东西放在那里,所以不能)。 我该怎么把arraylist放进去呢?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView txt1;
Button btn1;
ArrayList <String> shop= new ArrayList <String>();
impshop(shop);
txt1 =(TextView)findViewById(R.id.tv1);
btn1 =(Button)findViewById(R.id.button1);
btn1.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Random ran = new Random();
int choose = ran.nextInt(shop.size());
txt1.setText(shop.get(choose));
}});
}
我可以点击(查看v,ArrayList商店)吗?
答案 0 :(得分:1)
除了将final
添加到ArrayList
之外,您还可以在onCreate
方法之外定义它。这样做不需要您定义final
修饰符。
虽然请确保不使用ArrayList
来存储属于Activity的上下文的元素或可能链接到应用程序的其他上下文的元素,否则可能会导致在大内存泄漏。
答案 1 :(得分:0)
在
之前添加final
ArrayList <String> shop= new ArrayList <String>();
所以它看起来像:
final ArrayList <String> shop= new ArrayList <String>();
答案 2 :(得分:0)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView txt1;
Button btn1;
final ArrayList <String> shop= new ArrayList <String>();
impshop(shop);
txt1 =(TextView)findViewById(R.id.tv1);
btn1 =(Button)findViewById(R.id.button1);
btn1.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Random ran = new Random();
int choose = ran.nextInt(shop.size());
txt1.setText(shop.get(choose));
}});
}
或将ArrayList声明为字段