【问题标题】:Is RecyclerView refreshed when AlertDialog's positive button gets pressed按下 AlertDialog 正按钮时 RecyclerView 是否刷新
【发布时间】:2018-08-10 07:20:33
【问题描述】:

我的 MainActivity 有一个 RecyclerView 适配器,并且通过 AlertDialog 添加到此 RecyclerView 的数据,该 AlertDialog 将输入的文本传递给 MainActivity。当按下对话框中的肯定按钮时,即使我在传递新输入后从未调用 notifyItemInserted() 或 notifyDatasetChange(),回收站视图也会以某种方式刷新。我想知道这是怎么发生的,我的猜测是在对话框中按下肯定按钮后,recyclerview 会以某种方式刷新

自定义警报对话框代码:

 public class CustomDialog extends AppCompatDialogFragment {
        OnNoteAddedListener onNoteAddedListener;

    public interface OnNoteAddedListener {
        public void onClick(String note);
    }

    public CustomDialog(OnNoteAddedListener onNoteAddedListener) {
        this.onNoteAddedListener = onNoteAddedListener;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        // Get the layout inflater
        final LayoutInflater inflater = getActivity().getLayoutInflater();
        final View dialogLayout = inflater.inflate(R.layout.dialog_box, null);
        // Inflate and set the layout for the dialog
        // Pass null as the parent view because its going in the dialog layout
        builder.setView(dialogLayout).setPositiveButton("Ok", new DialogInterface.OnClickListener() {@Override
            public void onClick(DialogInterface dialog, int id) {
                EditText addNote = dialogLayout.findViewById(R.id.note_text);
                String note = addNote.getText().toString();
                onNoteAddedListener.onClick(note);
            }
        }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                CustomDialog.this.getDialog().cancel();
            }
        });
        return builder.create();
    }
}

适配器代码:

class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>
{
    private static final String TAG = "RecyclerViewAdapter";
    private List<String> notesList;
    private Context mContext;
    private SendPositionConnector sendPositionConnector;
public interface SendPositionConnector
{
    public void sendPosition(int position);
}

public RecyclerViewAdapter(List<String> notesList, Context mContext)
{
    this.notesList = notesList;
    this.mContext = mContext;
    this.sendPositionConnector = (MainActivity)mContext;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
{
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_listitem, parent, false);
    ViewHolder holder = new ViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int position)
{
    Log.d(TAG, "onBindViewHandler: called");
    viewHolder.noteContent.setText(notesList.get(position));
    viewHolder.parentLayout.setOnLongClickListener(new View.OnLongClickListener(){
        @Override
        public boolean onLongClick(View view)
        {
            Log.d(TAG, "onLongClick: long clicked on");
            sendPositionConnector.sendPosition(position);
            return false;
        }
    });
}

@Override
public int getItemCount()
{
    return notesList.size();
}

public class ViewHolder extends RecyclerView.ViewHolder
{
    TextView noteContent;
    RelativeLayout parentLayout;
    ImageView bullet;

    public ViewHolder(@NonNull View itemView)
    {
        super(itemView);
        bullet = itemView.findViewById(R.id.bullet);
        noteContent = itemView.findViewById(R.id.text_content);
        parentLayout = itemView.findViewById(R.id.parent_layout);
    }
}
}

活动代码:

public class MainActivity extends AppCompatActivity implements RecyclerViewAdapter.SendPositionConnector
{
    private static final String TAG = "MainActivity";
    private List<String> notesList = new ArrayList<>();
    private RecyclerView recyclerView;
    private RecyclerViewAdapter adapter;
    private int position;
    public AgentAsyncTask agentAsyncTask;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    recyclerView = findViewById(R.id.my_recycler_view);
    registerForContextMenu(recyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    agentAsyncTask = new AgentAsyncTask(notesList, getApplicationContext(), true, new AgentAsyncTask.OnRead(){
        @Override
        public void onRead(List<String> notesList)
        {
            if(!notesList.isEmpty())
                MainActivity.this.notesList = notesList;
            adapter = new RecyclerViewAdapter(notesList, MainActivity.this);
            recyclerView.setAdapter(adapter);
        }
    });
    agentAsyncTask.execute();
}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.add_menu, menu);
    return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    // Handle item selection
    switch (item.getItemId())
    {
        case R.id.add_note:
            showDialogBox(item);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
protected void onStop()
{
    super.onStop();
    new AgentAsyncTask(notesList, getApplicationContext(), false, new AgentAsyncTask.OnRead(){
        @Override
        public void onRead(List<String> notesList)
        {
            if(!notesList.isEmpty())
                MainActivity.this.notesList = notesList;
        }
    }).execute();
}
@Override
protected void onDestroy()
{
    super.onDestroy();
}

private boolean showDialogBox(MenuItem menuItem)
{
    AppCompatDialogFragment dialogFragment = new CustomDialog(new CustomDialog.OnNoteAddedListener(){
        @Override
        public void onClick(String note)
        {
            Log.d(TAG, "onClick: "+ note);
            notesList.add(note);
        }
    });
    dialogFragment.show(getSupportFragmentManager(),"Adding");
    return true;
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.context_menu, menu);
}


@Override
public boolean onContextItemSelected(MenuItem menuItem)
{
    switch(menuItem.getItemId())
    {
        case R.id.delete:
            notesList.remove(position);
            adapter.notifyItemRemoved(position);
            adapter.notifyItemRangeChanged(position, notesList.size());
            return true;
        default:
            return false;
    }
}

@Override
public void sendPosition(int position)
{
    this.position = position;
}

private static class AgentAsyncTask extends AsyncTask<Void, Void, List<String>>
{
    private List<String> notesList;
    private boolean flag;
    OnRead onRead;
    Context context;
    AppDataBase dataBase;
    private static final String TAG = "AgentAsyncTask";
    public interface OnRead
    {
        public void onRead(List<String> notesList);
    }
    private AgentAsyncTask(List<String> notesList,Context context,boolean flag, OnRead onRead)
    {
        this.notesList = notesList;
        this.onRead = onRead;
        this.flag = flag;
        this.context = context;
    }

    @Override
    protected List<String> doInBackground(Void... params)
    {
        dataBase = Room.databaseBuilder(context, AppDataBase.class, "database-name").build();
        if(!flag)
        {
            Gson gson = new Gson();
            Type type = new TypeToken<List<String>>() {}.getType();
            String json = gson.toJson(notesList, type);
            Log.d(TAG, "doInBackground: "+json);
            Notes notes = new Notes();
            notes.setNoteContent(json);
            notes.setUid(1);
            dataBase.notesDao().insertNotes(notes);
            return notesList;
        }
        else
        {
            Gson gson = new Gson();
            String notesListContent = dataBase.notesDao().getNotes();
            if(dataBase.notesDao().getCount() != 0)
            {
                notesList = gson.fromJson(notesListContent, new TypeToken<List<String>>()
                {
                }.getType());
            }
            else
            {
                return notesList;
            }
            return notesList;
        }
    }
    @Override
    protected void onPostExecute(List<String> notesList)
    {
        super.onPostExecute(notesList);
        if(flag)
            onRead.onRead(notesList);
    }
}
}

【问题讨论】:

  • 添加您的适配器和 mainactivity 代码
  • @prashant17 我想知道在对话框中按下肯定按钮时活动中的 recyclerview 是否刷新,如果是,这是如何发生的。谢谢。
  • 您需要添加该代码以便我们告诉您。
  • @DavidLiu 添加了代码

标签: java android android-recyclerview


【解决方案1】:

可能发生的情况是,当对话框返回时,它会导致 RecyclerView 重新布局,从而重新绑定视图。但是这很容易出现错误,因为它可能没有更新回收器关于列表长度或项目视图类型等内容,因此应始终使用适当的 notify 方法。

【讨论】:

    【解决方案2】:

    当您在按下肯定按钮后从对话框中获取文本到主要活动时。 将您传递给适配器和调用方法的新文本附加到您的列表中

    adapter.notifyDataSetChanged();
    

    【讨论】:

    • 我知道我们需要调用这个方法,但它在不调用该方法的情况下工作。我想知道它为什么以及如何工作。
    • 如果您不调用此方法,那么只有在您删除项时才会崩溃。您只是不会在插入时的某个索引上显示某些项目
    • @EpicPandaForce 没有发生,它以某种方式令人耳目一新,你能看看我的代码并告诉我怎么做吗?
    猜你喜欢
    • 2012-04-25
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多