活动将数据发送到片段,但收到的片段为空

时间:2017-03-20 12:45:37

标签: android android-fragments android-activity

有一个包含Button和LinerLayout的活动,它是Fragment的容器。 Fragment的布局仅包含TextView。我想从活动中发送一个字符串到片段,但收到的片段是null。为什么呢?

xml of Activity:

    <Button
        android:id="@+id/load"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:text="load" />

    <!--the container of fragment-->
    <LinearLayout
        android:id="@+id/container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" />

xml of Fragment:

    <TextView
        android:id="@+id/fragment_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

活动的Java代码:

public class DynamicFragmentActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic_fragment);

        findViewById(R.id.load).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //create fragment and set data
                MyFragment myFragment = new MyFragment();
                Bundle bundle = new Bundle();
                bundle.putString("text", "demo");
                myFragment.setArguments(bundle);

                //commit
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.add(R.id.container, myFragment);
                fragmentTransaction.commit();

            }
        });
    }
}

Fragment的Java代码:

public class MyFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.myfragment, container, false);
        TextView textView = (TextView) view.findViewById(R.id.fragment_text);

        //receive data
        String text = getArguments().getBundle("text")+"";
        textView.setText(text);

        return view;
    }
}

2 个答案:

答案 0 :(得分:0)

试试这个,希望它有帮助...........

public class MyFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.myfragment, container, false);
    TextView textView = (TextView) view.findViewById(R.id.fragment_text);

    //change getBundle() to getString() 
    String text = getArguments().getString("text")+"";
    textView.setText(text);

    return view;
}
}

答案 1 :(得分:0)

你现在正在做的是获得一个名为text的Bundle,你真正想要的是在bundle中获取一个字符串:

Bundle arg = getArguments();
String txt = arg.getString("text");