更新片段视图

时间:2017-11-12 07:38:19

标签: java android android-adapter fragment-oncreateview

我需要更新片段视图,以便我可以实时更新我的​​回收视图,因为值来自我的数据库。我目前在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获取的参数。

1 个答案:

答案 0 :(得分: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触发任何其他活动的更新。