如何在自定义适配器中使用我的方法中的视图?

时间:2018-10-09 07:27:03

标签: android custom-adapter

我尝试在自定义适配器中更改textview背景颜色,并创建了一个方法,因为我想通过自己的活动实现此方法。所以我想在自定义适配器的方法中使用我的视图,就像我们在onBindViewHolder()方法中如何使用holder.txt_product ....一样。

@Override
public void onBindViewHolder(final DeMontageListAdapter.MyViewHolder holder, 
final int position) {

    holder.txt_piston_code.setText(list.get(position).getPistonCode());
}

@Override
public int getItemCount() {
    return list.size();
}

public void changeTextViewBackground(){


}

我想在我的changeTextViewBackground()方法中激活onBindViewHolder()方法之类的视图。

1 个答案:

答案 0 :(得分:0)

您需要实现并设置一个侦听器接口,以使您的视图所有者能够通过您的活动与之通信:

您的自定义适配器:

     private OnItemClickListener onItemClickListener; //ADD THIS GLOBAL FIELD

     //ADD THIS SETTER
     public void setOnItemClickListener(OnItemClickListener onItemClickListener) 
     {
         this.onItemClickListener = onItemClickListener;
     }

     @Override
     public void onBindViewHolder(final DeMontageListAdapter.MyViewHolder holder, 
     final int position) {

     holder.txt_piston_code.setText(list.get(position).getPistonCode());

     // SET YOUR LISTENER TO EACH OF YOUR ITEM VIEWS
     holder.txt_piston_code.setOnClickListener(v ->
            onItemClickListener.onClickItem(position);
     }

     // ADD THIS INTERFACE AT THE END
     interface OnItemClickListener {
        void onClickItem(int position);
     }

您的活动应实现DemontageListAdapter.OnItemClickListener并覆盖其onClickItem方法:

    public class MyActivity implements DemontageListAdapter.OnItemClickListener {

        DemontageListAdapter adapter;

        { ... }

        adapter = new DemontageListAdapter (...)
        adapter.setOnItemClickListener(this); // ADD THIS BEFORE YOU SET YOUR ADAPTER TO YOUR ACTIVITY
        recyclerView.setAdapter(adapter);

        //OVERRIDE THIS METHOD OF YOUR INTERFACE
        @Override
        public void onClickItem(int position) {
            adapter.changeTextViewBackground(position);
        }
    }