android studio需求:使用public void onItemClickListener(View view, int position)方法对position进行判断,当position=0时,fragment跳转到fragment1,当position=1时,fragment跳转到fragment2
时间: 2024-03-26 11:38:19 浏览: 77
可以按照以下步骤实现你的需求:
1. 在你的项目中创建两个Fragment,分别为Fragment1和Fragment2。
2. 在你的RecyclerView的Adapter中实现onItemClickListener方法。代码如下:
```java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> mData;
private OnItemClickListener mClickListener;
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mClickListener = listener;
}
// ...其他代码
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView textView;
ViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (mClickListener != null) {
mClickListener.onItemClick(v, getAdapterPosition());
}
}
}
}
```
3. 在你的Activity或Fragment中获取RecyclerView的引用,设置Adapter和OnItemClickListener。代码如下:
```java
public class MyFragment extends Fragment {
private RecyclerView mRecyclerView;
private MyAdapter mAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my, container, false);
mRecyclerView = view.findViewById(R.id.recycler_view);
mAdapter = new MyAdapter(getData());
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
if (position == 0) {
// 跳转到Fragment1
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, new Fragment1());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
} else if (position == 1) {
// 跳转到Fragment2
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, new Fragment2());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
});
return view;
}
// ...其他代码
}
```
这样,当点击RecyclerView中的第一个条目时,就会跳转到Fragment1;点击第二个条目时,就会跳转到Fragment2。
阅读全文