Android 活动将数据发送到片段,但接收到的片段为空
有一个包含按钮和LinerLayout的活动,LinerLayout是片段的容器。Fragment的布局仅包含一个TextView。我想从activity向fragment发送一个字符串,但收到的片段为null。为什么? 活动的xml格式:Android 活动将数据发送到片段,但接收到的片段为空,android,android-fragments,android-activity,Android,Android Fragments,Android Activity,有一个包含按钮和LinerLayout的活动,LinerLayout是片段的容器。Fragment的布局仅包含一个TextView。我想从activity向fragment发送一个字符串,但收到的片段为null。为什么? 活动的xml格式: <Button android:id="@+id/load" android:layout_width="match_parent" android:layout_height="80dp"
<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" />
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();
}
});
}
}
片段的Java代码:
<TextView
android:id="@+id/fragment_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
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;
}
}
试试这个,希望对你有帮助
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;
}
}
您现在要做的是获取一个名为text的捆绑包,您真正想要的是在捆绑包中获取一个字符串:
Bundle arg = getArguments();
String txt = arg.getString("text");
非常感谢。这是一个很大的帮助。我只是尝试将getBundle()更改为get(),也可以。使用getString(),这样您就可以将其作为字符串获取,并在textView.setText(text);)中进行设置。如果答案对你有帮助,请接受,谢谢。