【发布时间】:2021-10-08 12:39:13
【问题描述】:
我已经创建了选项卡布局,并且在一个片段中,我使用按钮将数据传输到位于选项卡布局第二位置的其他片段。因此,当我单击第一个片段中的按钮时,应将文本字符串发送到第二个片段,并应显示在该片段的文本视图中。
【问题讨论】:
标签: java android-studio fragment android-tablayout android-viewpager2
我已经创建了选项卡布局,并且在一个片段中,我使用按钮将数据传输到位于选项卡布局第二位置的其他片段。因此,当我单击第一个片段中的按钮时,应将文本字符串发送到第二个片段,并应显示在该片段的文本视图中。
【问题讨论】:
标签: java android-studio fragment android-tablayout android-viewpager2
如果您要传输 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);
}
【讨论】:
要么将这些数据放在 Activity 中的变量中,Fragment 可以从父 Activity 访问该数据..
【讨论】: