為什么我傳過去的值顯示為null?
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
? ?xmlns:tools="http://schemas.android.com/tools"
? ?android:layout_width="match_parent"
? ?android:layout_height="match_parent"
? ?android:orientation="vertical"
? ?tools:context="io.github.joahyau.studying.DynamicFragmentActivity">
? ?<Button
? ? ? ?android:id="@+id/load"
? ? ? ?android:layout_width="match_parent"
? ? ? ?android:layout_height="80dp"
? ? ? ?android:text="run" />
? ?<LinearLayout
? ? ? ?android:id="@+id/container"
? ? ? ?android:layout_width="wrap_content"
? ? ? ?android:layout_height="wrap_content"
? ? ? ?android:orientation="horizontal" />
</LinearLayout>
fragment xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
? ?android:layout_width="match_parent"
? ?android:layout_height="match_parent"
? ?android:orientation="vertical">
? ?<TextView
? ? ? ?android:id="@+id/fragment_text"
? ? ? ?android:layout_width="wrap_content"
? ? ? ?android:layout_height="wrap_content" />
</LinearLayout>
Activity的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) {
? ? ? ? ? ? ? ?MyFragment myFragment = new MyFragment();
? ? ? ? ? ? ? ?Bundle bundle = new Bundle();
? ? ? ? ? ? ? ?bundle.putString("text", "demo");
? ? ? ? ? ? ? ?myFragment.setArguments(bundle);
? ? ? ? ? ? ? ?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);
? ? ? ?String text = getArguments().getBundle("text")+"";
? ? ? ?textView.setText(text);
? ? ? ?return view;
? ?}
}
2018-03-21
怎麼解決的老哥????我也是啊TT
2017-03-20
問題解決啦,我哭。。。
2017-03-20
對照著老師的源碼一行行看過,基本就變量名不一樣而已了。。。