无法将数据从一个片段传递到另一个片段

时间:2019-02-25 06:11:31

标签: android android-fragments

我想将数据从Teachers Fragment发送到OneTeacher Fragment。我从互联网上找到了以下代码。但是当我单击列表框的一个项目时,它的输出为“ Null”。

请足够友好地提出解决方案。 (我的问题是为什么我无法通过使用以下代码将数据从Teachers Fragment发送到一个Teacher Fragment)。

教师片段

try {
      lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

               TextView myTextView = (TextView) view.findViewById(R.id.tName);

               String teachernamefrom = myTextView.getText().toString();

               Toast.makeText(getActivity(), teachernamefrom, Toast.LENGTH_SHORT).show();
               //this toast works properly

               Bundle bundle = new Bundle();
               bundle.putString("key1",teachernamefrom);

               getFragmentManager().beginTransaction()
                        .setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
                        .replace(R.id.fragment_container, new OneTeacherFragment())
                        .addToBackStack("tag")
                        .commit();

               Fragment nextFrag = new OneTeacherFragment();
               nextFrag.setArguments(bundle);

            }
        });
    } catch (Exception e) {
        Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }

OneTeacherFragment:

        teacherName = (TextView) v.findViewById(R.id.teacher_name);
        Bundle bundle = getArguments();

        if (bundle != null){
            String key = bundle.getString("key1");
            teacherName.setText(key);
        }
        else{
            Toast.makeText(getActivity(), "Null", Toast.LENGTH_SHORT).show();
        }

2 个答案:

答案 0 :(得分:0)

更改onItemClick中的代码

您在替换OneTeacherFragment()时传递了新对象Fragment,您  应当通过nextFrag

// create OneTeacherFragment
Fragment nextFrag = new OneTeacherFragment();
// set bundle arguments
nextFrag.setArguments(bundle);

getFragmentManager().beginTransaction()
                    .setCustomAnimations(android.R.animator.fade_in, 
android.R.animator.fade_out)
                    .replace(R.id.fragment_container, nextFrag) // pass created nextFrag
                    .addToBackStack("tag")
                    .commit();

答案 1 :(得分:0)

您已经设置了参数并在该实例上进行事务,而不是当前的方法

// Create an instance of the fragment
Fragment nextFrag = new OneTeacherFragment();

// Create an instance of a bundle
Bundle bundle = new Bundle();
// Pass data to the bundle
bundle.putString("key1",teachernamefrom);
// Set the arguments
nextFrag.setArguments(bundle);

// Perform the fragment transaction with the created instance
getFragmentManager().beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.replace(R.id.fragment_container, nextFrag)
.addToBackStack("tag")
.commit();