从Fragment更新RecycleView?

时间:2015-06-24 04:28:52

标签: java android android-recyclerview

我正在尝试向此RecycleView添加一个Object。当我将对象添加到初始ArrayList时,它们都会显示出来。但是,当我尝试添加一个对象并从HomeFragment调用notifyDataSetChanged时,UI上没有任何反应。

HomeFragment.java

Your Order

HomeAdapter.java

public class HomeFragment extends Fragment {
    View myView;
    private RecyclerView mRecyclerView;
    private HomeAdapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private ArrayList<Note> myNotes;
    private Activity activity;

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

        mRecyclerView = (RecyclerView) myView.findViewById(R.id.list12313);

        //linear layout manager
        mLayoutManager = new LinearLayoutManager(activity);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

        //adapter
        myNotes = new ArrayList<Note>();
        myNotes.add(new Note("Welcome to WITS Mobile", "Logged in as: " + LoginActivity.witsName));
        myNotes.add(new Note("Version 0.1 ALPHA", "- Early Internal Alpha"));
        //myNotes.add(new Note());

        mAdapter = new HomeAdapter(myNotes, activity);
        mRecyclerView.setAdapter(new SlideInBottomAnimationAdapter(mAdapter));

        setHasOptionsMenu(true);
        return myView;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.first, menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId())
        {
            case R.id.action_add:
                addItem();
                return true;
            case R.id.action_CLR:
                clear();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public void addItem()
    {
        Note e = new Note("New Title", "New Body");
        mAdapter.addItem(e);
    }

    public void clear()
    {
        mAdapter.clear();
    }
}

1 个答案:

答案 0 :(得分:0)

取出这一行:

mRecyclerView.setHasFixedSize(true);

固定大小表示项目的数量,而不是布局大小