Android-观察实时数据无法通过片段工作

时间:2020-04-29 22:45:27

标签: android android-fragments android-livedata mutablelivedata

我有2个活动片段,一个是列表片段,另一个是细节片段,细节片段显示了列表片段中所选项目的详细信息,还有一个按钮可以更改列表项目“状态”的设置顺序。

点击“订单”按钮后,我想将选定的项目移至准备好的位置。

我尝试通过共享视图模型进行观察,但是在设置值时onchange方法未调用。

enter image description here

这是一个viewModel:

package com.example.ordermanager.fragments;
import android.database.ContentObserver;
import android.os.Handler;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.ordermanager.fragments.orderlist.dummy.DummyContent;

import java.util.List;

public class SharedViewModel extends ViewModel {

    private MutableLiveData<DummyContent.DummyItem> item = new MutableLiveData<DummyContent.DummyItem>();

    public void setItem(DummyContent.DummyItem value){
        item.setValue(value);
    }

    public MutableLiveData<DummyContent.DummyItem> getItem(){
        return item;
    };

}

ListFragment:

public class OrderItemFragment extends Fragment {

    // TODO: Customize parameter argument names
    private static final String ARG_COLUMN_COUNT = "column-count";
    // TODO: Customize parameters
    private int mColumnCount = 1;
    private OnListFragmentInteractionListener mListener;
    private SharedViewModel vm;
    private RecyclerView recyclerView;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public OrderItemFragment() {
    }

    // TODO: Customize parameter initialization
    @SuppressWarnings("unused")
    public static OrderItemFragment newInstance(int columnCount) {
        OrderItemFragment fragment = new OrderItemFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
        }

        vm = ViewModelProviders.of(this).get(SharedViewModel.class);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_order_item_list, container, false);

        // Set the adapter
        if (view instanceof RecyclerView) {
            Context context = view.getContext();
            recyclerView = (RecyclerView) view;
            if (mColumnCount <= 1) {
                recyclerView.setLayoutManager(new LinearLayoutManager(context));
            } else {
                recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
            }

            recyclerView.setAdapter(new MyOrderItemRecyclerViewAdapter(DummyContent.ITEMS, mListener));
        }


        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Observer<DummyItem> itemObserver = new Observer<DummyItem>() {
            @Override
            public void onChanged(@Nullable DummyItem selectedItem) {
                //this never happening
                Log.e("hereeeee","dfgdfg");
                recyclerView.getAdapter().notifyDataSetChanged();
            }
        };

        vm.getItem().observe(this, itemObserver);
    }



    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnListFragmentInteractionListener) {
            mListener = (OnListFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnListFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */


    public interface OnListFragmentInteractionListener {
        // TODO: Update argument type and name
        void onListFragmentInteraction(DummyItem item);
    }
}

DetailsFragment:

public class OrderDetailFragment extends Fragment {

    private SharedViewModel mViewModel;
    private DummyContent.DummyItem selectedItem;
    private Button ReadyBtn;

    public static OrderDetailFragment newInstance() {
        return new OrderDetailFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.order_detail_fragment, container, false);

        Bundle bundle = getArguments();

        if(bundle != null){
                selectedItem = (DummyContent.DummyItem)getArguments().getSerializable("item");

                TextView tv = (TextView) view.findViewById(R.id.detailid);
                tv.setText(selectedItem.content);

        }
        ReadyBtn = view.findViewById(R.id.readyBtn);
        ReadyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(selectedItem != null){
                    selectedItem.isReady = true;
                    mViewModel.getItem().setValue(selectedItem);
                }
            }
        });

        return view;
    }



    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mViewModel = ViewModelProviders.of(this).get(SharedViewModel.class);

    }

}

观察者位于ListFragment OnViewCreated函数中

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

当您在函数中声明局部变量时,在函数调用结束时它们会被销毁。因此,您需要将itemObserver存储在一个字段中。

旁注...
除非您创建一个不推荐的自定义构造函数,否则不需要在片段中使用默认的空构造函数。

关于recyclerview,我建议您详细阅读this(尤其是ListAdapter部分)。

答案 1 :(得分:0)

您应在调用notifyDataSetChanged()方法之前更改适配器中的数据。现在,您在itemObserver中获得了新的价值,但您没有更改适配器。

UPD。我已经解决了问题!初始化代码SharedViewModel中的密钥。在两种情况下,都应将活动附加到ViewModelProviders类上,但是您使用了它,实际上,您有两个不同的实例,而不是应该附加到父活动的一个实例。因此,将初始化代码更改为 mViewModel = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);,它将起作用!