【问题标题】:how to send data from one fragment to an other fragment using interface in tablayout如何使用tablayout中的接口将数据从一个片段发送到另一个片段
【发布时间】:2021-10-08 12:39:13
【问题描述】:

我已经创建了选项卡布局,并且在一个片段中,我使用按钮将数据传输到位于选项卡布局第二位置的其他片段。因此,当我单击第一个片段中的按钮时,应将文本字符串发送到第二个片段,并应显示在该片段的文本视图中。

【问题讨论】:

    标签: java android-studio fragment android-tablayout android-viewpager2


    【解决方案1】:

    如果您要传输 int、long、String 等数据。那么您可以在创建第二个 Fragment 时将数据包装在 Bundle 中,并使用 getArguments() 方法在其 onCreate() 方法中获取第二个 Fragment 中的所有数据。

    在 onClick(View view) 方法的第一个片段中-

         onClick(View view){ 
           
            YourSecondFragment secondFragment=new YourSecondFragment();
            Bundle args=new Bundle();
            args.putString("create a key for your string ",your string value);
            secondFragment.setArguments(args);
            
           //.. and rest code of creating fragment transaction and commit.
    

    然后在YourSecondFragment的onCreate(Bundle savedInstanceState)方法中

            if(getArguments()!=null)
             {
              
         your_text_variable= getArguments().getString("the same key that you put in first fragment",null);
           
              }
    

    最后在secondFragment的onCreateView()方法中-

          if(your_text_variable!=null)
           {
             yourTextView.setText(your_text_variable);
              }
    

    【讨论】:

    • 这很好,但我可以使用界面与片段一起高潮。不是捆绑包
    【解决方案2】:

    要么将这些数据放在 Activity 中的变量中,Fragment 可以从父 Activity 访问该数据..

    或使用Shared View Model.

    【讨论】:

      猜你喜欢
      • 2015-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多