0

我需要更新片段视图,以便我可以在值从我的数据库实时进入时更新我的​​回收视图。我目前在 OnCreateView 方法中执行此操作,但这不允许我在切换选项卡时进行更新。

public class UserFragment extends Fragment {

public UserFragment() {
}

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

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_blank, container, false);

    RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
    rv.setHasFixedSize(false);
    final ArrayList<widgetData> dummie_list = new ArrayList<>();
    FirebaseAuth mAuth = FirebaseAuth.getInstance();
    final MyAdapter adapter = new MyAdapter(dummie_list);
    rv.setAdapter(adapter);

    DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("contacts").child(mAuth.getUid());
    ref.addListenerForSingleValueEvent(
            new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for(DataSnapshot ds: dataSnapshot.getChildren())
                    {
                        if(!dummie_list.contains(new widgetData(ds.getValue(String.class), "FUCK FIREBASE", 0)))
                        {
                            dummie_list.add(new widgetData(ds.getValue(String.class), "FUCK FIREBASE", 0));
                            adapter.notifyDataSetChanged();

                        }
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    //handle databaseError
                }
            });

    LinearLayoutManager llm = new LinearLayoutManager(getActivity());
    rv.setLayoutManager(llm);

    return rootView;
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        //Update view here
    }
}

}

setUserVisibleHint 是导致问题的原因,因为似乎无法更新视图,因为我无权访问 OnCreateView 获取的参数。

4

1 回答 1

0

您正在使用 ViewPager 。因此向寻呼机添加一个 PageChange 侦听器并为您要更新的每个片段提供回调。

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

// optional 
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }

// optional 
@Override
public void onPageSelected(int position) {
 // Call a callback here to fragment to initialize update
      }

// optional 
@Override
public void onPageScrollStateChanged(int state) { }

});

或者您可以使用EventBus触发任何其他事件的更新。

于 2017-11-12T07:58:35.090 回答