android - 如何使用 LiveData 和 ViewModel 类将数据从 Activity 发送到 Fragment
问题描述
现在,LiveData 非常流行,我如何使用 ViewModel 和 LiveData 将数据从活动发送到片段,反之亦然?请用编码示例进行解释。
解决方案
活动中
public class MyActivity extends AppCompatActivity {
MyViewModel myViewModel;
Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
handler = new Handler();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, MyFragment.newInstance())
.commitNow();
}
//Make View Holder Object
myViewModel=ViewModelProviders.of(this).get(MyViewModel.class);
myViewModel.init();
myViewModel.sendData("Hello kamy");
// Make thread to send data again
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
@Override
public void run() {
myViewModel.sendData("How are You ?");
}
});
}
}).start();
}
}
在 ViewModel 类中
public class MyViewModel extends ViewModel {
// TODO: Implement the ViewModel
private MutableLiveData<String> stringMutableLiveData;
public void init()
{
stringMutableLiveData=new MutableLiveData<>();
}
public void sendData(String msg)
{
stringMutableLiveData.setValue(msg);
}
public LiveData<String> getMessage()
{
return stringMutableLiveData;
}
}
在片段中
public class MyFragment extends Fragment {
private MyViewModel mViewModel;
private TextView textView;
public static MyFragment newInstance() {
return new MyFragment();
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.my_fragment, container, false);
textView=(TextView)view.findViewById(R.id.message);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
ViewModelProviders.of(getActivity()).get(MyViewModel.class).getMessage().observe(this, new Observer<String>() {
@Override
public void onChanged(@Nullable String message) {
textView.setText(message);
Toast.makeText(getContext(),message,Toast.LENGTH_SHORT).show();
}
});
}
}
片段xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/my"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.my.MyFragment">
<TextView
android:id="@+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MyFragment"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
推荐阅读
- pandas - Matplotlib Subplot Boxplot x 刻度标签不显示
- c# - 如何在 c# 中通过 OLEDB 在 Access SQL 通配符查询中使用文字下划线?
- java - 当文件为空时,Apache Camel 2.17 RouteBuilder 路由不起作用
- java - 如何过滤 Spring 的页面
对象使用 java8 的 filter() 并返回 Page - powershell - 如何将 Invoke-SilentlyAndReturnExitCode 实现为 Powershell 模块功能?
- powershell - 使用 powershell 进行文本操作
- android - Android 在消息应用程序中输入动画
- mysql - 在mysql数据库中存储多个用户数据的最佳方法是什么?
- r - 在 R 中使用 Rank 函数时包括前导零
- c - 这个malloc错误是什么意思?损坏的顶部尺寸?