在Fragment中使用MainActivity中的值

我的应用程序具有一个带有三个片段的bottomNavigationBar。我的MainActivity包含一个CollapsingToolbar,其中包含一个RadioGroup。现在,我在MainActivity中获得了选定的RadioButton的值,但是我需要在第一个片段中使用它的值。我怎么做?每个片段都包含自己的CollapsingToolbar还是活动之间传递数据?


慕田峪4524236
浏览 263回答 3
3回答

慕的地10843

您可以使用put来传递您想要的值 SharedPreferencesSharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);    SharedPreferences.Editor edit = prefs.edit();    edit.putString("some_key",someValue); //someValue is a var that containns the value that you want to pass    edit.commit();然后在您的片段中,访问值:SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);String value = prefs.getString("some_key","default_value");另一种效率较低的方法创建一个将包含所有静态变量的Utility类。您将能够在该类的所有实例中设置并获取这些变量的值。

繁星淼淼

您可以setArguments(Bundle)在Bundle具有已设置键值对的情况下使用片段的方法。例如,您的片段对象yourFragment,那么你必须Bundle bundle = new Bundle();bundle.putString("paramKey", "paramVal");yourFragment.setArguments(bundle);在片段的中,onCreateView(LayoutInflater, ViewGroup, Bundle)您可以使用getArguments()方法访问信息。String value = getArguments().getString("paramKey");  // value = "paramVal"// inflate, return请参阅文档,以获取有关设置包值的更多信息。

30秒到达战场

这也可以使用实现Java接口这样的在Activity类中定义一个接口。在提交片段时捕获接口实例,该片段随后将用于将数据发送到片段。&nbsp; class ExampleActivity extends Activity {&nbsp; &nbsp; &nbsp; &nbsp; //Data listener to be implemented by the fragment class&nbsp; &nbsp; &nbsp; &nbsp; public interface OnDataListerner{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public void sendData(ArrayList<String> data);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; //DataListener instance to be captured while committing fragment&nbsp; &nbsp; &nbsp; &nbsp; OnDataListener fragment;&nbsp; &nbsp; &nbsp; &nbsp; //commit your fragment and type cast it to OnDataListener&nbsp; &nbsp; &nbsp; &nbsp; private void commit Fragment(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;fragment = new ExampleFragment();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;FragmentTransaction transaction =&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;getSupportFragmentManager().beginTransaction();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;transaction.replace(R.id.fragment_container, exampleFragment);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;transaction.addToBackStack(null);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;transaction.commit();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; //used to send data through interface methods which will be defined in fragment&nbsp; &nbsp; &nbsp; &nbsp; public void sendDataToFragment(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;fragment.sendData(Your data to be send);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;}在您的Fragment类中实现此接口,一旦Acitivity在此接口上调用任何方法,它将在此Fragment中调用公共类ExampleFragment扩展Fragment实现ExampleActivity.OnDataListerner {//interface callback which is called when Activity call its method.&nbsp;public void sendData(ArrayList<String> data){&nbsp; &nbsp; &nbsp; //Here is your data which can be consumed&nbsp;}}希望这可以帮助。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java