我无法通过Intent
或Bundle
向我的Fragment
发送数据。我错过了其他帖子似乎没有提及的内容吗?
这是我的MainActivity.java:
public class MainActivity extends Activity implements MainFragment.Test {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Bundle b = new Bundle();
b.putInt("number", 3);
MainFragment mf = new MainFragment();
mf.setArguments(b);
}
@Override
public void testPrint(String s) {
Log.d("number", s);
}
}
MainFragment.java:
public class MainFragment extends Fragment {
Test test;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof MainActivity)
test = (Test) activity;
else
throw new ClassCastException("error");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
Button b = (Button) view.findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String num = String.valueOf(getArguments().getInt("number"));
test.testPrint(num);
}
});
return view;
}
public interface Test {
public void testPrint(String s);
}
}
activity_main2.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<fragment
android:id="@+id/fragment"
android:name="com.ygutstein.testfrags.MainFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
答案 0 :(得分:2)
您正在创建MainFragment
的新实例,而不是使用activity_main2
布局中定义的实例。
但即使你正确引用它,你仍然会抛出一个IllegalStateException
,因为你无法向xml中定义的Fragment
添加参数。请改用FrameLayout
并致电FragmentTransaction.replace
。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<FrameLayout
android:id="@+id/fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
final Bundle args = new Bundle();
args.putInt("number", 3);
final MainFragment mf = new MainFragment();
mf.setArguments(args);
getFragmentManager().beginTransaction().replace(R.id.fragment, mf).commit();