0

我想将 ArrayList 放在 onClick 方法上。但它告诉我我应该将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 商店)吗?

4

3 回答 3

1

除了添加final到 your之外ArrayList,您还可以在onCreate方法之外定义它。这样做不需要您定义final修饰符。

尽管确保不要使用ArrayList来存储属于 Activity上下文的元素或可能链接到应用程序其他上下文的元素,但不这样做可能会导致大量内存泄漏。

于 2013-11-05T15:44:53.097 回答
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 声明为字段

于 2013-11-05T15:45:59.247 回答
0

final之前添加

ArrayList <String> shop= new ArrayList <String>();

所以它看起来像:

final ArrayList <String> shop= new ArrayList <String>();
于 2013-11-05T15:43:02.690 回答