使用'这个'在Android事件处理程序中。有没有更好的办法?

时间:2015-03-02 16:33:35

标签: android listview

是的,总会有更好的方法。但是有更好的方法吗? :)

所以这段代码有效。它是ListActivty的自定义适配器,其想法是每行都有一个按钮,当按下该按钮时,该行的项目将被删除,列表将刷新。

private class ThirdActivityAdapter extends ArrayAdapter<String> {
    private Context ctx;
    private List<String> items;
    public ThirdActivityAdapter(Context ctx, List<String> items) {
        super(ctx, R.layout.third_activity_list_row, items);
        this.ctx = ctx;
        this.items = items;
    }

    public List<String> getItems() {
        return items;
    }

    @Override
    public View getView(int position, View convertView, final ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View row = inflater.inflate(R.layout.third_activity_list_row, parent, false);
        TextView txt = (TextView)row.findViewById(R.id.third_activity_list_row_text);
        Button btn  = (Button)row.findViewById(R.id.third_activity_list_row_btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View view = (View)v.getParent();
                ListView listView = (ListView)view.getParent();
                ThirdActivityAdapter.this.items.remove(listView.getPositionForView(view));
                ThirdActivityAdapter.this.notifyDataSetChanged();
            }
        });
        txt.setText(items.get(position));
        return row;
    }

在点击监听器中,我使用ThirdActivityAdapter.this来获取适配器中的项目。有一个更好的方法吗?我可以看到外部源如何工作,但我想在继续之前看看是否有更好的设计。

谢谢!

1 个答案:

答案 0 :(得分:0)

如果我正确理解你的问题,更好的方法。它涉及使用View.setTag(键,值)。它允许您将键值对分配给特定视图,稍后使用View.getTag(key)访问它。

这就是我要做的事情:

@Override
public View getView(int position, View convertView, final ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    View row = inflater.inflate(R.layout.third_activity_list_row, parent, false);
    TextView txt = (TextView)row.findViewById(R.id.third_activity_list_row_text);
    Button btn  = (Button)row.findViewById(R.id.third_activity_list_row_btn);
    btn.setTag(R.id.button_position, position); // Save position to View
    btn.setOnClickListener(mYourClickListener);
    txt.setText(items.get(position));
    return row;
}
View.OnClickListener mYourClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int position = v.getTag(R.id.view_position); // Obtain position
        removeItem(position);
    }
}
// Avoids this syntax because its clear to whom this method belongs.
private void remoteItem(int position) {
    items.remove(position);
    notifyDataSetChanged();
}

另外,请考虑使用ViewHolder模式以避免重复引用findViewById()