我正在使用RecyclerView(和GridLayout)将动态按钮放在网格中。 为每个动态按钮设置不同的onClickListener的最佳方法是什么,因为它是使用RecyclerView创建并放置在Gridlayout中的?
我的按钮是根据用户操作随机创建的,方法是将drawable传递给我的RecyclerView方法" createButton"下面。每次只有一个drawable传递给我的gridLayout,每次都必须创建一个新的onClickListener。最好的方法是什么?
private GridLayoutManager lLayout;
RecyclerViewAdapter rcAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<ItemObject> myList = new ArrayList<>();
rcAdapter = new RecyclerViewAdapter(getActivity(),myList);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home_fragment, container, false);
lLayout = new GridLayoutManager(getActivity(), 3,
GridLayoutManager.HORIZONTAL, false);
RecyclerView rView = (RecyclerView)view.findViewById(R.id.recycler_view);
rView.setHasFixedSize(true);
rView.setLayoutManager(lLayout);
rView.setAdapter(rcAdapter);
return view;
}
public void createButton (Drawable d, String appName){
rcAdapter.addItem(new ItemObject(appName, d));
}
答案 0 :(得分:1)
每次您只需要一个知道ItemObject
的点击监听器时,我认为您不需要新的点击监听器。为此,我将为您提供这种模式的常用方法:
在您的代码的某个地方,您有一个RecyclerView.ViewHolder
,您应该在OnClickListener
期间为该视图持有者实施ItemObject
并将OnBind
的引用传递给持有者,就像以下内容:
class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ItemObject itemObject;
public MyHolder(View itemView) {
super(itemView);
itemView.findViewById(your button Id).setOnClickListener(this); // make this holder receives the clicks
}
@Override
public void onClick(View view) {
// here you add logic that depending on the data from itemObject
}
}
然后在onBind期间,您必须正确设置ItemObject
@Override
public void onBindViewHolder (MyHolder holder, int position) {
ItemObject itemObject = list.get(position);
holder.itemObject = itemObject;
// the rest of your bind code....
}