📅  最后修改于: 2023-12-03 15:36:20.815000             🧑  作者: Mango
在Android开发中,适配器(Adapter)经常被用来将数据展示在各种列表或网格中。但是,有时候开发者需要在点击列表或网格中的某一项之后执行某些操作或者打开新的活动(Activity)。要实现这个功能,可以在适配器中使用Interface回调来调用活动的方法。
下面是一个使用适配器和Interface回调来调用活动方法的示例代码:
public interface ItemClickListener {
void onItemClicked(String item);
}
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private List<String> mDataList;
private ItemClickListener mListener;
public MyAdapter(List<String> dataList, ItemClickListener listener) {
mDataList = dataList;
mListener = listener;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.mTextView.setText(mDataList.get(position));
holder.itemView.setOnClickListener(v -> {
if(mListener != null) {
mListener.onItemClicked(mDataList.get(position));
}
});
}
@Override
public int getItemCount() {
return mDataList.size();
}
static class MyViewHolder extends RecyclerView.ViewHolder {
private TextView mTextView;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.item_textview);
}
}
}
public class MainActivity extends AppCompatActivity implements ItemClickListener {
private RecyclerView mRecyclerView;
private MyAdapter mMyAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
List<String> dataList = new ArrayList<>();
for (int i = 0; i < 20; i++) {
dataList.add("Item " + i);
}
mMyAdapter = new MyAdapter(dataList, this);
mRecyclerView.setAdapter(mMyAdapter);
}
@Override
public void onItemClicked(String item) {
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra("item", item);
startActivity(intent);
}
}
在上述示例中,MyAdapter实现了接口ItemClickListener,然后通过回调方法onItemClicked将点击事件传递给了MainActivity。 MainActivity在实现接口方法onItemClicked中执行了打开新的活动(DetailActivity)的操作。
通过适配器和Interface回调,我们可以方便地将列表或者网格中的点击事件传递给活动,实现一些有趣的交互效果。