这是我的密码。 我已经在我的RecycerView适配器中创建了一个接口,一切工作正常。 我不明白为什么碎片不会更新位置。
这是我的activity中的代码片段,我在其中设置了RecyclerView。
adapter.setOnSectionClickListener(new SectionAdapter.SectionClickListener() {
@Override
public void onItemClick(int position) {
//Here I want to send the position of the clicked item to my DescriptionFragment.
Bundle bundle = new Bundle();
bundle.putInt(DescriptionFragment.SECTION_ID, position);
DescriptionFragment frag = new DescriptionFragment();
frag.setArguments(bundle);
// NB. My code works perfectly fine when I try to send the position to an activity
// through an intent in here. the problem arises whenever I try to send it to a fragment.
}
});
这是来自DescriptionFragment的代码片段,即从我的activity接收位置的片段。 问题是每当我运行它时,它都会在我的两个回收视图项中显示“The first Unit”toast消息,这意味着位置0和位置1中都显示了“The first Unit”toast消息。
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
int id = getArguments().getInt(SECTION_ID);
if(id == 0){
Toast toast = Toast.makeText(getActivity(), "the first unit", Toast.LENGTH_LONG);
toast.show();
}
if(id == 1){
Toast toast = Toast.makeText(getActivity(), "the second unit", Toast.LENGTH_LONG);
toast.show();
}
}
不要使用片段的默认构造函数发送任何数据。 创建一个静态方法来获取Fragment的实例,并从该方法传递数据。 代码如下-
public class FirstFragment extends Fragment {
private int selectedPosition;
public FirstFragment() {
// Required empty public constructor
}
public static FirstFragment newInstance(int position) {
Bundle args = new Bundle();
args.putInt("POSITION", position);
FirstFragment fragment = new FirstFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getArguments()!=null){
selectedPosition = getArguments().getInt("POSITION");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first, container, false);
}
...............
}
片段创建将如下-
FirstFragment.newInstance(position);
您还需要使用fragment manager来实际移动到一个片段。
getSupportFragmentManager().beginTransaction().add(FirstFragment.newInstance(position));
快乐的编码!!