我代码里已经有public class了,还能写内部类吗,怎么调用呢
时间: 2024-02-23 20:01:28 浏览: 77
如果你的代码已经有了public class,那么你可以把ViewHolderListener接口定义为SimpleAdapter类的内部类,这样就可以避免定义多个public class的问题。你可以在SimpleAdapter类中添加如下代码:
```java
public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.ViewHolder> {
private List<String> mData;
private ViewHolderListener mListener;
public SimpleAdapter(List<String> data, ViewHolderListener listener) {
mData = data;
mListener = listener;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_simple, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
String item = mData.get(position);
holder.bindData(item);
}
@Override
public int getItemCount() {
return mData.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView mTextView;
public ViewHolder(View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.text_view);
itemView.setOnClickListener(this);
}
public void bindData(String item) {
mTextView.setText(item);
}
@Override
public void onClick(View view) {
if (mListener != null) {
mListener.onItemClick(getAdapterPosition());
}
}
}
public interface ViewHolderListener {
void onItemClick(int position);
}
}
```
在这个代码中,ViewHolderListener接口被定义为SimpleAdapter类的内部接口。ViewHolder类也被定义为SimpleAdapter类的内部类。这样做可以避免定义多个public class的问题。在Activity或Fragment中,你可以像下面这样实现ViewHolderListener接口:
```java
SimpleAdapter.ViewHolderListener itemClickListener = new SimpleAdapter.ViewHolderListener() {
@Override
public void onItemClick(int position) {
// 处理点击事件
}
};
recyclerView.setAdapter(new SimpleAdapter(getExamples(), itemClickListener));
```
在这个示例代码中,我们实现了ViewHolderListener接口,并创建了一个itemClickListener对象,将其传递给SimpleAdapter的构造函数中。在onItemClick方法中,我们可以处理RecyclerView的点击事件。
阅读全文