我在滑动标签布局中有多个片段。我想将数据从第一个选项卡传递到其他选项卡。请提供代码。同时传递数据标签时,应从第一标签滑动到第二标签。请帮我。预先感谢
答案 0 :(得分:0)
考虑使用 ViewModel (https://developer.android.com/topic/libraries/architecture/viewmodel) (https://developer.android.com/topic/libraries/architecture/adding-components)
首先,打开项目的 ROOT build.gradle 文件(而不是应用程序或模块的文件),然后添加google()存储库,如下所示:
allprojects {
repositories {
google()
jcenter()
}
}
然后,只需在 APP MODULE build.gradle 中将该库添加到Gradle中,然后就可以开始在项目中使用 ViewModel :
implementation "androidx.lifecycle:lifecycle-extensions:2.0.0" // Its Version May Vary
要使用 ViewModel :
创建 ViewModel类并定义要传递的数据
public class MyViewModel extends ViewModel {
// Assume you wanted to Pass the Data of 'name' from 1st Tab to 2nd Tab
String name = "";
void resetData() { // Function that will Reset the Data
name= "";
}
}
比方说,第一个标签是FragmentA,第二个标签是FragmentB,当您从第一个标签滑动到第二个标签时,您想传递“名称”数据
现在,在 FragmentA 中,您可以设置 ViewModel 的“名称”数据,然后再将数据传递给 FragmentB
public class FragmentA extends Fragment {
private MyViewModel myViewModel ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// MUST Initialize your ViewModel
myViewModel = ViewModelProviders.of(getActivity()).get(MyViewModel.class);
}
protected void onStart() {
super.onStart();
// You can Set your Value anywhere, Let Set the Value at onStart as an Example
// Set your Name Data to "Pritham Bnr"
myViewModel.name= "Pritham Bnr"
}
}
注意:每当您想要设置ViewModel的“名称”数据时,只需使用代码myViewModel.name= "Value you want to Set"
现在,当您从第一个选项卡(FragmentA)滑动到第二个选项卡(FragmentB) <时,您可以从FragmentB的ViewModel中获取“名称”数据/ p>
public class FragmentB extends Fragment {
private MyViewModel myViewModel ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// MUST Initialize your ViewModel
myViewModel = ViewModelProviders.of(getActivity()).get(MyViewModel.class);
}
protected void onStart() {
super.onStart();
// You can Get your Value anywhere by call "myViewModel.name", Let Get the Value at onStart as an Example
// Using Toast to Display the 'name' Data pass from FragmentA using ViewModel
Toast.makeText(getContext(), myViewModel.name, Toast.LENGTH_SHORT).show();
}
// for Example, If you want Clear the Data when Swipe Back to FragmentA, you can call resetData() function of the ViewModel
// Let say we Clear the Data when the Fragment onStop() as you Swipe back to FragmentA
// This is Optional, just an Example Telling you how to Reset the Data if you want to
protected void onStop() {
super.onStop();
// Reset Data when Screen is Being Swipe to FragmentA
// After Call this function, the ViewModel previous Data of "Pritham Bnr" will be Reset and become "" empty value.
// So FragmentA now will get "" Data from the ViewModel
myViewModel.destroyViewModelData();
}
}
注意:每当您想要获取ViewModel的“名称”数据时,只需使用代码myViewModel.name
ViewModel 不仅可以存储String,Int,Double等数据类型,还可以存储 Object ,这在传递大量数据时非常有用< / strong>从片段到片段。
这是将数据从片段传递到片段的简单方法之一。
希望这会有所帮助,谢谢。