我正在使用以下LazyAdapter。我需要在点击事件中获得点击的位置。我在第20行得到了以下建议。有什么建议吗?
不能引用内部类中的非final变量位置 用不同的方法定义
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private List<String> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
ArrayList<String> text= new ArrayList<String>();
public LazyAdapter(MainActivity a, List<String> parsed_string) {
// TODO Auto-generated constructor stub
activity = a;
data = parsed_string;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
public TextView text;
public ImageView image;
public Button click;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.item, null);
holder = new ViewHolder();
holder.text = (TextView) vi.findViewById(R.id.text);
;
holder.image = (ImageView) vi.findViewById(R.id.image);
holder.click = (Button) vi.findViewById(R.id.btn_click);
holder.click.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(activity, "clicked the button in the row",
Toast.LENGTH_LONG).show();
holder.click.setText(text.get(position)); // line 20
}
});
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
holder.text.setText("item " + position);
holder.image.setTag(data.get(position));
imageLoader.DisplayImage(data.get(position), activity, holder.image);
return vi;
}
}
答案 0 :(得分:6)
像这样声明getView
:
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
//...
}
从anonymous inner class
您只能访问final
个本地变量。
这是因为内部类的代码可能在初始化完成的类的方法之后调用,并且它的局部变量是垃圾收集的。声明变量final
使变量成为常量,并将其作为值发送到内部类,而不是作为引用。
答案 1 :(得分:0)
使用具有构造函数的属性位置实现自己的OnClickListener类 - &gt; MyOwnClickListener(position)并实现onClick的逻辑。
class MyOwnClickListener implements OnClickListener {
int position;
public MyOwnClickListener(int position) {
this.position = position;
}
@Override
public void onClick(View v) {
....
并在getView方法中设置监听器:
holder.click.setOnClickListener(new MyOwnClickListener(position) {