从匿名内部类访问非最终变量

时间:2014-08-18 10:58:46

标签: java android

public class FoodTypeAdapter extends BaseAdapter {
private Context context;

public FoodTypeAdapter(Context context) {
    this.context = context;
}

public View getView(final int position, View convertView, ViewGroup parent) {
    final ViewHolder holder = null;
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.food_type_grid,
                new LinearLayout(context));
        holder = new ViewHolder();          
        holder.btnAdd = (Button) convertView.findViewById(R.id.btnItemAdd);
        holder.etQty = (EditText) convertView.findViewById(R.id.etfItemQty);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    holder.btnAdd.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            String quantity = holder.etQty.getText().toString();
            System.out.println(quantity);
        }
    });
    return convertView;
}

public int getCount() {
    return mylist.size();
}

public Object getItem(int position) {
    return null;
}

public long getItemId(int position) {
    return 0;
}

static class ViewHolder {       
    Button btnAdd;
    EditText etQty;
}
}

在此代码中,未将holder设为final Object我无法从OnClickListener访问它。

如果我将其设为final Object,我就无法holder启动holder = new ViewHolder();

现在我该怎么办?任何帮助都会非常值得赞赏。

谢谢, 古纳

2 个答案:

答案 0 :(得分:3)

你也可以简单地调整holder的初始化,这会降低你的代码复杂性:

final ViewHolder holder;

if (convertView == null) {
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = inflater.inflate(R.layout.food_type_grid,
            new LinearLayout(context));
    holder = new ViewHolder();
    holder.btnAdd = (Button) convertView.findViewById(R.id.btnItemAdd);
    holder.etQty = (EditText) convertView.findViewById(R.id.etfItemQty);
    convertView.setTag(holder);
} else {
    holder = (ViewHolder) convertView.getTag();
}

答案 1 :(得分:2)

您可以通过在匿名类之前添加临时final变量来解决此问题,并改为使用该变量:

final ViewHolder finalHolder = holder;    // <- added

holder.btnAdd.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        String quantity = finalHolder.etQty.getText().toString();
        //                ^^^^^^^^^^^
        System.out.println(quantity);
    }
});

或者,您可以将holder设为成员变量。