按钮单击片段中ListView上的侦听器

时间:2015-03-01 19:24:46

标签: android listview android-fragments onclicklistener

所以我试图用onClickListener添加一个Button功能,但我似乎无法让它工作。
我的按钮在列表项的XML中声明,我的列表在片段中实现。
我做了一些研究,找到了一些答案,我尝试过的每个解决方案都失败了,或者太复杂了。我有点开始为我的无知感到抱歉。

因此我的问题是如何在这些条件下为我的Button获取onClickListener。有什么东西会使监听器的效果无法在列表中起作用吗?

2 个答案:

答案 0 :(得分:2)

在你的adpater类中按id找到按钮然后在同一个类中写入button.setOnClickListner。它会起作用

如果你想在你的frament类中进行单击,你必须在适配器类中编写接口并通过该接口扩展你的片段然后使用接口方法点击

如果您需要单击带索引/位置的片段类,则使用belo示例代码

//Inside adpater class
public interface OnEditLocationListener {
        public void onDeleteClick(int position);

    }

    private OnEditLocationListener listener;

    public void setOnEditLocationListener(OnEditLocationListener listener) {
        this.listener = listener;
    }

    //Inside getView method
    holder.imv_delete.setTag(position);
        holder.imv_delete.setOnClickListener(null);
        holder.imv_delete.setOnClickListener(new OnClickListener() {

            @Override
            public void onDeleteClick(View view) {
                if (listener != null) {
                    listener.onDeleteClick(position);
                }
            }
        });



//In Activity
        yourclass extends yourchoice implements adapter.OnEditLocationListener

        //inside onCreate/onCreateview

        adapter.setOnClickListener(getActivity/this);

        //Button click
    @Override
    public void onDeleteClick(int pos) {
        Toast.makeText(getActivity(), "clicked @ " + pos, Toast.LENGTH_SHORT).show();


    }

答案 1 :(得分:0)

您好)首先,您必须创建自定义适配器。例如:

public class EatListAdapter extends BaseAdapter {

    private ArrayList<EatTime> eatTimes;
    private Activity activity;

    public EatListAdapter(Activity activity, ArrayList<EatTime> items) {
        this.eatTimes = items;
        this.activity = activity;
    }

    @Override
    public int getCount() {
        return eatTimes.size();
    }

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

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        View v;
        LayoutInflater inflater = (LayoutInflater) activity.getApplicationContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        v = inflater.inflate(R.layout.list_item, null);

        Button delete = (Button) v.findViewById(R.id.button_delete);
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            //your ON CLICK CODE

        });

        return v;
    }
}

比设置适配器

ListView eatingList = (ListView) findViewById(R.id.eatingList);
adapter = new EatListAdapter(this, eatArrayList);
eatingList.setAdapter(adapter);