无论我做什么,我在片段内的recyclelerview都不会更新

时间:2016-02-17 13:06:09

标签: android android-fragments android-recyclerview android-volley

现在已经过了一个星期,我真的很想要一个解决方案,因为我需要在本周内向我的客户提供更新。因此,我在片段中有一个recyclerview,其中填充了使用volley库从Web服务获取的数据。如果将新数据添加到数据库,我希望recyclelerview重新加载/更新以实现更改或新添加的更改。现在,我尝试了很多方法,但未能实现我的需要。我尝试过以下方法:

-notifyDataSetChanged()在我的适配器内的处理程序内,onclick

-adapter.notifyItemRangeChanged(0,adapter.getItemCount());

处理程序内的

-recyclerView.invalidate()也是如此 - 分离并附加当前片段

- 也尝试了下面的代码。好吧,它起作用,因为它刷新整个活动并返回到第一页的初始片段

Intent intent = getActivity().getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK
    | Intent.FLAG_ACTIVITY_NO_ANIMATION);
    getActivity().overridePendingTransition(0, 0);
    getActivity().finish();

    getActivity().overridePendingTransition(0, 0);
    startActivity(intent);

片段类

public class AddPlaylist extends Fragment {

RecyclerView recyclerView;
RecyclerAdapter adapter;
String[] id,title;
ArrayList<String> artist;
TextView text;

CreatePlaylist createPlaylist;

private CoordinatorLayout coordinatorLayout;
private FloatingActionButton fab;
 View view;

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

    coordinatorLayout = (CoordinatorLayout) view.findViewById(R.id
            .coordinatorLayout);

    fab = (FloatingActionButton) view.findViewById(R.id.fab);

    text = (TextView) view.findViewById(R.id.text);

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showInputDialog();
        }
    });

    id = getArguments().getStringArray("id");
    title = getArguments().getStringArray("title");

    artist = new ArrayList<String>(Arrays.asList(title));

    recyclerView= (RecyclerView) view.findViewById(R.id.my_recycler_view);
    adapter = new RecyclerAdapter("addplaylist", id, artist, getActivity());
    recyclerView.setAdapter(adapter);
    recyclerView.invalidate();
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    adapter.notifyItemRangeChanged(0, adapter.getItemCount());

    final Handler mHandler = new Handler();

    mHandler.post(new Runnable() {

        @Override
        public void run() {

            adapter.notifyDataSetChanged();
            adapter.notifyItemRangeChanged(0, adapter.getItemCount());
            recyclerView.invalidate();

            Fragment frg = null;
            frg = getFragmentManager().findFragmentByTag("playlist");
            Bundle bundle = new Bundle();
            AddPlaylist addPlaylist = new AddPlaylist();
            bundle.putStringArray("id", JsonArray.ids);
            bundle.putStringArray("title", JsonArray.titles);
            addPlaylist.setArguments(bundle);
            final FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.detach(addPlaylist);
            ft.attach(addPlaylist);
            ft.commit();

        }
    });

    return view;
}

protected void showInputDialog() {

    // get prompts.xml view
    LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
    View promptView = layoutInflater.inflate(R.layout.input_dialog, null);
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
    alertDialogBuilder.setView(promptView);

    final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
    // setup a dialog window
    alertDialogBuilder.setCancelable(false)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    //text.setText("Hello, " + editText.getText());
                    createPlaylist.createPlaylist(editText.getText().toString());

                    /*Intent intent = getActivity().getIntent();
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK
                            | Intent.FLAG_ACTIVITY_NO_ANIMATION);
                    getActivity().overridePendingTransition(0, 0);
                    getActivity().finish();

                    getActivity().overridePendingTransition(0, 0);
                    startActivity(intent);*/
                    /*Bundle bundle = new Bundle();
                    Collections collections = new Collections();
                    AddPlaylist addPlaylist = new AddPlaylist();
                    bundle.putStringArray("id", JsonArray.ids);
                    bundle.putStringArray("title", JsonArray.titles);
                    bundle.putString("fragment", "addfragment");
                    addPlaylist.setArguments(bundle);
                    Fragment frg = null;
                    frg = getFragmentManager().findFragmentByTag("playlist");
                    final FragmentTransaction ft = getFragmentManager().beginTransaction();
                    ft.detach(collections);
                    ft.attach(frg);
                    ft.commit();*/



                    /*getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                        }
                    });*/

                    /*FragmentManager fragmentTransaction = getFragmentManager();
                    android.app.FragmentTransaction transaction = fragmentTransaction.beginTransaction();
                    Bundle bundle = new Bundle();
                    AddPlaylist addPlaylist = new AddPlaylist();
                    bundle.putStringArray("id", JsonArray.ids);
                    bundle.putStringArray("title", JsonArray.titles);
                    addPlaylist.setArguments(bundle);
                    transaction.addToBackStack("xyz");
                    transaction.add(R.id.containerView, addPlaylist);
                    //transaction.setTransition(FragmentTransaction.TRANSIT_ENTER_MASK);
                    transaction.commit();*/

                    adapter.notifyItemRangeChanged(0, adapter.getItemCount());
                }
            })
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });

    // create an alert dialog
    AlertDialog alert = alertDialogBuilder.create();
    alert.show();
}

@UiThread
protected void dataSetChanged() {
    adapter.notifyDataSetChanged();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    id = getArguments().getStringArray("id");
    title = getArguments().getStringArray("title");

    artist = new ArrayList<String>(Arrays.asList(title));

    adapter = new RecyclerAdapter("addplaylist", id, artist, getActivity());
    adapter.notifyDataSetChanged();
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try{
        createPlaylist = (CreatePlaylist) activity;
    }catch(Exception e) {

    }
}

public interface CreatePlaylist{

     void createPlaylist(String name);

    }
}

对于凌乱的代码感到抱歉。这就是我所有人都尝试过的。

1 个答案:

答案 0 :(得分:2)

这种情况发生了,因为你的适配器会丢失&#34;。首先,您创建适配器。这很好。然后你得到新的数据。你要做的是创建另一个适配器,并在第二个适配器中更改数据,该数据没有附加到RecyclerView。

它不是最优雅的解决方案,但它会起作用。在onActivityResult

中更改这些行
 artist = new ArrayList<String>(Arrays.asList(title));

adapter = new RecyclerAdapter("addplaylist", id, artist, getActivity());

List<String> newArtist = new ArrayList<String>(Arrays.asList(title));
artist.clear();
artist.addAll(newArtist);
adapter.notifyDataSetChanged();

由于您的列表artist是对象,当您将其传递给您的Recycler适配器,并且您更新相同的实例,相同的列表,因此您不需要创建新的适配器,因为适配器仍然具有访问权限同一个实例。把它想象成一桶水。您可以清空铲斗或填充铲斗,但铲斗保持不变。