如何从同一片段中的自定义适配器获取值

时间:2016-07-20 11:01:29

标签: java android

我是Android的新手。我有一个片段(Menu)和一个自定义适配器(MenuListCustomAdapter)。在该片段中有一个listview和一个textview。每个列表视图包含两个按钮(add& sub)和textview。我的疑问是,我在自定义适配器中为(add& sub)按钮写了onclicklistener,点击那些按钮我要在片段(菜单)中更改textview。

菜单片段:

adapter = new MenuListCustomAdapter(itemList, this.getActivity(),"http://xyz/images/fish.png");
    menuList.setAdapter(adapter);

CustomAdapter:

 holder.plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int quantity = Integer.parseInt(holder.qty.getText().toString());
                if(list.size()>0){

                        String value = list.get(position).Quantity.toString();
                        Log.d("plus Position on Click", String.valueOf(position));
                        int count = Integer.parseInt(value)+1;
                        list.get(position).Quantity = String.valueOf(count);
                        holder.qty.setText(String.valueOf(count));
                        Log.d("plus value", String.valueOf(count));

                    if(count>0){
                        list.get(position).selFlag = true;

                    }else {
                        list.get(position).selFlag = false;
                    }

                }
            }
        });

请有人帮助我!

1 个答案:

答案 0 :(得分:0)

您应该使用界面来处理List的点击事件。

在适配器中

 // Define listener member variable
private static OnItemClickListener listener;
// Define the listener interface
public interface OnItemClickListener {
    void onItemClick(View itemView, int position);
}
// Define the method that allows the parent activity or fragment to define the listener
public void setOnItemClickListener(OnItemClickListener listener) {
    this.listener = listener;
}

在适配器ViewHolder中:

plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (listener != null)
                    listener.onItemClick(v, k);
            }
        });

在你的片段中:

adapter.setOnItemClickListener(new MenuListCustomAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {

              //you can check which view was clicked
               if(view.getId() == R.id.viewID){

                 //do your stuff here
               }
      }
    });