开发者

public void method in for loop; can't recieve loop variable

Here's my for loop. Problem: I need to get a listener on an array of buttons and get the button depending on array number appending some text to a textview array with the same number.

Problem is, I can't get int i to the public void method. If I declare it my main class, the application just gets failed. When I'm changing the i value to some real integer, it works. so I figured out that the problem is - onClick method is receiving a null instead of i.

 for(int i=0; i<n;i++){
     btninput.get(i).setOnClickListener(new OnClickListener() {

         @Override
         public 开发者_运维技巧void onClick(View v) {
             converswindow.get(i).append(Html.fromHtml("<b>Вы:</b> "+msginput.get(i).getText()+"<br />"));
             msginput.get(i).setText("");
         }
     });
 }


I'm not sure if this would work or not, but try:

for(int i=0; i<n; i++) {
    final int j = i;
    btninput.get(i).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            converswindow.get(j).append(Html.fromHtml("<b>Вы:</b> "+msginput.get(i).getText()+"<br />"));
            msginput.get(j).setText("");
        }
    });
}

If that doesn't work, you can use Android's View tag mechanism to add data to the button. Read about View.setTag(...) and View.getTag(...) for more information there.


anonymous classes can't access local vars in their methods you need to make them instance vars of the objects (here I did it with ind)

for(int i=0; i<n;i++){
        btninput.get(i).setOnClickListener(new OnClickListener() {
             int ind=i;//here keep a copy of the local var

            @Override
            public void onClick(View v) {
              converswindow.get(ind).append(Html.fromHtml("<b>Вы:</b> "+msginput.get(ind).getText()+"<br />"));
              msginput.get(ind).setText("");
            }
       });
}


try using

public void onClick(View v) {
              converswindow.get(btninput.indexOf(v)).append(Html.fromHtml("<b>Вы:</b> "+msginput.get(btninput.indexOf(v).getText()+"<br />"));
              msginput.get(btninput.indexOf(v)).setText("");


Or you could create a custom OnClickListener and give it a constructor that receives an int:

public class CustomListener implements OnClickListener {
    int i;

    CustomListener(int i) {
        this.i = i;
    }

    @Override
    public void onClick(View v) {
        converswindow.get(j).append(Html.fromHtml("<b>Вы:</b>"+msginput.get(i).getText()+"<br />"));
        msginput.get(j).setText("");
    }

}

Then you could call it like this:

btninput.get(i).setOnClickListener(new CustomListener(i));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜