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>

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...