为了账号安全,请及时绑定邮箱和手机立即绑定

在Fragment中使用MainActivity中的值

在Fragment中使用MainActivity中的值

慕田峪4524236 2021-04-01 09:14:23
我的应用程序具有一个带有三个片段的bottomNavigationBar。我的MainActivity包含一个CollapsingToolbar,其中包含一个RadioGroup。现在,我在MainActivity中获得了选定的RadioButton的值,但是我需要在第一个片段中使用它的值。我怎么做?每个片段都包含自己的CollapsingToolbar还是活动之间传递数据?
查看完整描述

3 回答

?
慕的地10843

TA贡献1785条经验 获得超8个赞

您可以使用put来传递您想要的值 SharedPreferences


SharedPreferences 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类。您将能够在该类的所有实例中设置并获取这些变量的值。


查看完整回答
反对 回复 2021-05-12
?
繁星淼淼

TA贡献1775条经验 获得超11个赞

您可以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

请参阅文档,以获取有关设置包值的更多信息。


查看完整回答
反对 回复 2021-05-12
?
30秒到达战场

TA贡献1828条经验 获得超6个赞

这也可以使用实现Java接口这样的


在Activity类中定义一个接口。在提交片段时捕获接口实例,该片段随后将用于将数据发送到片段


  class ExampleActivity extends Activity {


        //Data listener to be implemented by the fragment class

        public interface OnDataListerner{

            public void sendData(ArrayList<String> data);

        }


        //DataListener instance to be captured while committing fragment

        OnDataListener fragment;


        //commit your fragment and type cast it to OnDataListener

        private void commit Fragment(){

           fragment = new ExampleFragment();

           FragmentTransaction transaction = 

           getSupportFragmentManager().beginTransaction();

           transaction.replace(R.id.fragment_container, exampleFragment);

           transaction.addToBackStack(null);

           transaction.commit();

        }


        //used to send data through interface methods which will be defined in fragment

        public void sendDataToFragment(){

           fragment.sendData(Your data to be send);

        }


 }

在您的Fragment类中实现此接口,一旦Acitivity在此接口上调用任何方法,它将在此Fragment中调用


公共类ExampleFragment扩展Fragment实现ExampleActivity.OnDataListerner {


//interface callback which is called when Activity call its method. 

public void sendData(ArrayList<String> data){

      //Here is your data which can be consumed 

}

}


希望这可以帮助。


查看完整回答
反对 回复 2021-05-12
  • 3 回答
  • 0 关注
  • 262 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信