【问题标题】:Android - Observing on live data not working from fragmentAndroid - 观察无法从片段中工作的实时数据
【发布时间】:2020-08-14 04:50:21
【问题描述】:

我在activityty中有2个片段,一个列表片段和详细信息片段,详细信息片段显示列表片段中的选定项目详细信息,并且有按钮可以更改列表项“状态”设置为准备就绪。

当按钮 Order 已准备好单击时,我想将所选项目移动到准备好的位置。

我尝试使用共享视图模型进行观察,但是当我在其中设置值时,onchange 方法没有调用。

这是一个视图模型:

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;
    };

}

列表片段:

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 函数中

有什么想法吗?

【问题讨论】:

    标签: android android-fragments android-livedata mutablelivedata


    【解决方案1】:

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

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

    【讨论】:

    • 看到itemobserver里面的评论了吗?为可观察项设置新值时,永远不会调用更改函数的观察者。
    • @GiorgiAbashidze 啊,我已经解决了这个问题! SharedViewModel 的初始化代码中的密钥。在这两种情况下,您都应该将activity 附加到ViewModelProviders 类,但是您使用this,实际上您有两个不同的实例,而不是一个应该附加到父活动的实例。所以,把初始化代码改成mViewModel = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);就行了!
    • 编辑你的第一个答案,在那里添加你的解决方案,我会接受的
    【解决方案2】:

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

    附带说明...
    除非您创建自定义构造函数,否则片段中不需要默认的空构造函数,不推荐这样做。

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

    【讨论】:

      猜你喜欢
      • 2021-07-28
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-27
      • 1970-01-01
      相关资源
      最近更新 更多