如何为我的Recyclerview处理项目onClick

时间:2017-08-01 01:11:37

标签: java android android-recyclerview

我正在构建一个涉及Recyclerview的应用。我想在单击每个项目时启动一个对话框(以编辑该项目的内容)但是现在,我只想在每个项目单击该项目的唯一ID时显示一个Toast消息。有关stackoverflow的例子,但所有这些都是不同的方法,我无法弄清楚如何将它们实现到我的应用程序(我还在学习Recyclerviews)。这是我尝试处理点击操作但它没有做任何事情:

recyclerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(addTaskActivity, view + " is clicked", Toast.LENGTH_SHORT).show();
            }
        });

根本没有任何事情发生。以下是我的MainActivity.javaCustomCursorAdapter.java个文件。

public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {

    private static final String TAG = MainActivity.class.getSimpleName();
    private static final int LOADER_ID = 0;

    private CustomCursorAdapter customCursorAdapter;
    RecyclerView recyclerView;
    private AddTaskActivity addTaskActivity;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = (RecyclerView) findViewById(R.id.recyclerViewTasks);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        customCursorAdapter = new CustomCursorAdapter(this);
        recyclerView.setAdapter(customCursorAdapter);

        recyclerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(addTaskActivity, view + " is clicked", Toast.LENGTH_SHORT).show();
            }
        });

        new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
                int id = (int) viewHolder.itemView.getTag();

                String itemId = Integer.toString(id);
                Uri uri = TaskContract.TaskEntry.CONTENT_URI;
                uri = uri.buildUpon().appendPath(itemId).build();

                getContentResolver().delete(uri, null, null);

                getSupportLoaderManager().restartLoader(LOADER_ID, null, MainActivity.this);

            }
        }).attachToRecyclerView(recyclerView);


        FloatingActionButton floatingActionButton = (FloatingActionButton) findViewById(R.id.fab_btn);

        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent addTaskIntent = new Intent(MainActivity.this, AddTaskActivity.class);
                startActivity(addTaskIntent);
            }
        });

        getSupportLoaderManager().initLoader(LOADER_ID, null, this);
    }

    @Override
    protected void onResume() {
        super.onResume();

        getSupportLoaderManager().restartLoader(LOADER_ID, null, this);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, final Bundle loaderArgs) {

        return new AsyncTaskLoader<Cursor>(this) {

            Cursor cursor = null;

            @Override
            protected void onStartLoading() {
                if (cursor != null) {
                    deliverResult(cursor);
                } else {
                    forceLoad();
                }
            }
            @Override
            public Cursor loadInBackground() {

                try {
                    return getContentResolver().query(TaskContract.TaskEntry.CONTENT_URI,
                            null,
                            null,
                            null,
                            TaskContract.TaskEntry.COLUMN_PRIORITY);

                } catch (Exception e) {
                    Log.e(TAG, "Failed to load data.");
                    e.printStackTrace();
                    return null;
                }
            }

            public void deliverResult(Cursor data) {
                cursor = data;
                super.deliverResult(data);
            }
        };
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        customCursorAdapter.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
            customCursorAdapter.swapCursor(null);
        }

}

这是我的自定义适配器:

public class CustomCursorAdapter extends RecyclerView.Adapter<CustomCursorAdapter.TaskViewHolder>{
    private Cursor cursor;
    private Context con;

    public CustomCursorAdapter(Context context) {
        this.con = context;
    }

    @Override
    public TaskViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(con).inflate(R.layout.task_layout, parent, false);
        return new TaskViewHolder(view);
    }

    @Override
    public void onBindViewHolder(TaskViewHolder holder, int position) {

        int index = cursor.getColumnIndex(TaskContract.TaskEntry._ID);
        int descriptionOfIndex = cursor.getColumnIndex(TaskContract.TaskEntry.COLUMN_DESCRIPTION);
        int priorityofIndex = cursor.getColumnIndex(TaskContract.TaskEntry.COLUMN_PRIORITY);

        cursor.moveToPosition(position);

        final int id = cursor.getInt(index);
        String description = cursor.getString(descriptionOfIndex);
        int priority = cursor.getInt(priorityofIndex);

        holder.itemView.setTag(id);
        holder.taskDescriptionView.setText(description);

        String priorityString = "" + priority;
        holder.priorityView.setText(priorityString);

        GradientDrawable priorityCircle = (GradientDrawable) holder.priorityView.getBackground();
        int priorityColor = getPriorityColor(priority);
        priorityCircle.setColor(priorityColor);

    }

    private int getPriorityColor(int priority) {
        int priorityColor = 0;

        switch(priority) {
            case 1: priorityColor = ContextCompat.getColor(con, R.color.materialRed);
                break;
            case 2: priorityColor = ContextCompat.getColor(con, R.color.materialOrange);
                break;
            case 3: priorityColor = ContextCompat.getColor(con, R.color.materialYellow);
                break;
            default: break;
        }
        return priorityColor;
    }

    @Override
    public int getItemCount() {
        if (cursor == null) {
            return 0;
        }
        return cursor.getCount();
    }

    public Cursor swapCursor(Cursor c) {
        if (cursor == c) {
            return null;
        }
        Cursor temp = cursor;
        this.cursor = c;

        if (c != null) {
            this.notifyDataSetChanged();
        }
        return temp;
    }

    public class TaskViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        TextView taskDescriptionView;
        TextView priorityView;

        public TaskViewHolder(View itemView) {
            super(itemView);

            taskDescriptionView = (TextView) itemView.findViewById(R.id.taskDescription);
            priorityView = (TextView) itemView.findViewById(R.id.priorityTextView);

            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            int position = getLayoutPosition();

        }
    }
}

编辑尝试了此实现,但我无法调用其他活动的方法:

public class TaskViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        TextView taskDescriptionView;
        TextView priorityView;

        public TaskViewHolder(View itemView) {
            super(itemView);

            taskDescriptionView = (TextView) itemView.findViewById(R.id.taskDescription);
            priorityView = (TextView) itemView.findViewById(R.id.priorityTextView);

            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            int position = getLayoutPosition();
            addTaskActivity.onClickAddTask(view);

        }
    }

2 个答案:

答案 0 :(得分:1)

您可以使用以下代码实现它

public class TaskViewHolder extends RecyclerView.ViewHolder {

            TextView taskDescriptionView;
            TextView priorityView;

            public TaskViewHolder(View itemView) {
                super(itemView);

                taskDescriptionView = (TextView) itemView.findViewById(R.id.taskDescription);
                priorityView = (TextView) itemView.findViewById(R.id.priorityTextView);

                itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(v.getContext(),"Clicked " + v.getId(),Toast.LENGTH_SHORT).show();
                }
            });
            }


        }

答案 1 :(得分:0)

您将onClick()置于错误的位置。

    public class TaskViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

            TextView taskDescriptionView;
            TextView priorityView;

            public TaskViewHolder(View itemView) {
                super(itemView);

                taskDescriptionView = (TextView) itemView.findViewById(R.id.taskDescription);
                priorityView = (TextView) itemView.findViewById(R.id.priorityTextView);

                itemView.setOnClickListener(this);
            }

            @Override
            public void onClick(View view) {
                int position = getLayoutPosition();
    /*  your onclick method here */
                    Log.d(TAG, "Element " + position + " clicked.");


            }
        }