如何使用bundle将数据从片段传递到活动



我有一个关于我的主要活动的搜索视图,我想将提交的字符串从 MainActivity 传递到 SearchFragment。

@Override
public boolean onQueryTextSubmit(String query) {
Bundle bundle = new Bundle();
bundle.putString("searchTitle", query);
SearchFragment searchFragment = new SearchFragment();
searchFragment.setArguments(bundle);
Intent mIntent = new Intent(MainActivity.this, SearchActivity.class);
startActivity(mIntent);
return true;
}

但是当我尝试获取搜索片段中的数据时,我得到 NullPointerException

public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
strText = getArguments().getString("searchTitle");
return inflater.inflate(R.layout.fragment_movies, container, false);
}

我该如何解决这个问题?

请尝试这个。

在您的主活动中。

@Override
public boolean onQueryTextSubmit(String query) {
Bundle bundle = new Bundle();
bundle.putString("searchTitle", query);
SearchFragment searchFragment = new SearchFragment();
searchFragment.setArguments(bundle);
Intent mIntent = new Intent(MainActivity.this, SearchActivity.class);
// Add this line.
mIntent.putExtra("key", "value");
startActivity(mIntent);
return true;
}

在您的搜索活动中。

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView([layout_name])
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
// Put data respected to your data type.
bundle.putString("key", getIntent().getStringExtra("key"));
fragment.setArguments(bundle);
// Add new fragment
getSupportFragmentManager()
.beginTransaction()
.add([container_id], fragment)
.addToBackStack(null)
.commit()
}

在你的片段中。

@Override
public onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String value = getArguments().getString("key");
}

如果你想通过捆绑包传递数据,至少你应该把这个捆绑包放在你的意图中。

mIntent.putExtras(bundle)

比你可以通过这个得到它

getActivity().getIntent().getExtras().getString("searchTitle")

最新更新