我们如何为回收站视图的每个列表项(每行)设置onClickListener,为列表的不同对象设置不同的活动

时间:2019-06-20 11:16:26

标签: android android-activity android-recyclerview onclicklistener onitemclicklistener

我需要为recycler view的每个列表项设置 OnClickListener
我想通过单击每个列表视图项来导航到其他活动。

到目前为止,我已经设法通过回调将点击位置传递给then列表中每个点击项的相同活动。但是,当我从列表中单击某个项目时,我想开始其他活动。

假设我想单击文本为“ dd”的行,则应转到名为“ abc”的活动

请帮助我。请。

这是主要活动:

public class MainActivity extends AppCompatActivity implements WordAdapter.OnNoteListener {
    private RecyclerView recyclerView;
    private static final String TAG = MainActivity.class.getCanonicalName();

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

        recyclerView = findViewById(R.id.home_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        recyclerView.setLayoutManager(layoutManager);

        List<Word> wordList = new ArrayList<>();


        wordList.add(new Word(R.drawable.ic_launcher_background, "dd"));
        wordList.add(new Word(R.drawable.ic_launcher_background, "ss"));
        wordList.add(new Word(R.drawable.ic_launcher_background, "cc"));


        WordAdapter adapter = new WordAdapter(this);
        recyclerView.setAdapter(adapter);
        adapter.addItems(wordList);
    }

    @Override
    public void onNoteClick(int position) {
        Log.d(TAG, "clicked on the position:" + position);
Intent intent = new Intent(this, abc.class);
        this.startActivity(intent);
    }
}

这是名为WordAdapter的适配器

public class WordAdapter extends RecyclerView.Adapter<WordAdapter.ViewHolder> {

    private List<Word> wordList;
    private OnNoteListener mOnNoteListener;

    public WordAdapter(List<Word> wordList, OnNoteListener onNoteListener) {
        this.wordList = wordList;
        this.mOnNoteListener = onNoteListener;
    }

    public WordAdapter(OnNoteListener onNoteListener) {
        this(new ArrayList<Word>(), onNoteListener);
    }

    public void addItems(List<Word> items) {
        wordList.addAll(items);
        notifyDataSetChanged();
    }

    public void clear() {
        wordList.clear();
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_items, viewGroup, false);
        return new ViewHolder(view, mOnNoteListener);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewholder, int position) {
        int resource = wordList.get(position).getImageResource();
        String title = wordList.get(position).getTitle();
        viewholder.setData(resource, title);
    }

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

    static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private ImageView imageView;
        private TextView title;

        private OnNoteListener onNoteListener;

        public ViewHolder(@NonNull View itemView, OnNoteListener onNoteListener) {
            super(itemView);

            imageView = itemView.findViewById(R.id.imageView);
            title = itemView.findViewById(R.id.word);
            this.onNoteListener = onNoteListener;

            itemView.setOnClickListener(this);
        }

        private void setData(int resource, String titleText) {
            imageView.setImageResource(resource);
            title.setText(titleText);
        }

        @Override
        public void onClick(View view) {
            onNoteListener.onNoteClick(getAdapterPosition());
        }
    }

    public interface OnNoteListener {
        void onNoteClick(int position);
    }
}

3 个答案:

答案 0 :(得分:0)

更新您的界面,使其包含ViewHolder作为参数。

public interface OnNoteListener {
    public void onNoteClick(ViewHolder viewHolder);    // Don't need position anymore, since you can call viewHolder.getAdapterPosition() directly.
}

有关完成此操作的完整过程,请查看@sm_happy提供的link

然后在“活动”的onNoteClick()方法中更改“文字”

viewHolder.textView.setText(viewHolder.textView.getText().toString() + "dd");    // Although the better option would be to instead keep a parameterized string in your resources file.

launch a new Activity

答案 1 :(得分:0)

您的Adapter班级的interface如下所示:

public class AdapterClass extends RecyclerView.Adapter<AdapterClass.Viewholder>{

private OnItemClick onItemClick;

public NotificationAdapter(Context context) {
       onItemClick = (OnItemClick)context;
    }

public interface OnItemClick {
        void onClick(int position);
    }

@Override
    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {

holder.layout.setOnClickListener(v -> {
            onItemClick.onClick(position);
        });

    }
}

现在您的Activity将实现此界面,如下所示:

         public class MainActivity extends AppCompatActivity implements AdapterClass.OnItemClick {


                @Override
                public void onClick(int position) {
                    Log.d(TAG, "clicked on the position:" + position);
                    startNewActivity(position);
                }

                private void startNewActivity(int position){
                Intent intent = new Intent(MainActivity.this, NewActivity.class);
                //Pass your data here if required
                intent.putExtra("key_for_data", position); 

                startActivity(intent);
        }
    }

答案 2 :(得分:0)

因此,我将在修改原始代码后附加完整的解决方案。

public class WordAdapter extends RecyclerView.Adapter<WordAdapter.ViewHolder> {


    private List<Word> wordList;
    private OnNoteListener mOnNoteListener;

    public WordAdapter(List<Word> wordList, OnNoteListener onNoteListener) {
        this.wordList = wordList;
        this.mOnNoteListener = onNoteListener;
    }

    public WordAdapter(OnNoteListener onNoteListener) {
        this(new ArrayList<Word>(), onNoteListener);
    }

    public void addItems(List<Word> items) {
        wordList.addAll(items);
        notifyDataSetChanged();
    }

    public void clear() {
        wordList.clear();
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_items, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewholder, int position) {
        int resource = wordList.get(position).getImageResource();
        String title = wordList.get(position).getTitle();
        viewholder.bind(resource, title, mOnNoteListener);
    }

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

    static class ViewHolder extends RecyclerView.ViewHolder {

        private ImageView imageView;
        private TextView title;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            imageView = itemView.findViewById(R.id.imageView);
            title = itemView.findViewById(R.id.word);
        }

        private void bind(final int resource, final String titleText, final OnNoteListener listener) {
            imageView.setImageResource(resource);
            title.setText(titleText);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.onNoteClick(titleText);
                }
            });
        }
    }

    public interface OnNoteListener {
        void onNoteClick(String dataClicked);
    }
}


如您所见,我更改了一些代码,以便您可以传递数据而不是位置。在下面,您可以看到启动新活动的代码。

    public class MainActivity extends AppCompatActivity implements WordAdapter.OnNoteListener {

    private RecyclerView recyclerView;

    private static final String TAG = MainActivity.class.getCanonicalName();

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

        recyclerView = findViewById(R.id.home_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        recyclerView.setLayoutManager(layoutManager);

        List<Word> wordList = new ArrayList<>();


        wordList.add(new Word(R.drawable.ic_launcher_background, "dd"));
        wordList.add(new Word(R.drawable.ic_launcher_background, "ss"));
        wordList.add(new Word(R.drawable.ic_launcher_background, "cc"));


        WordAdapter adapter = new WordAdapter(this);
        recyclerView.setAdapter(adapter);
        adapter.addItems(wordList);
    }

    @Override
    public void onNoteClick(String dataClicked) {
        Log.d(TAG, "clicked on the position:" + dataClicked);
        Intent intent = new Intent(MainActivity.this, SecondActivity.class);
        intent.putExtra(STRING_EXTRA, dataClicked);
        startActivity(intent);
    }
}


对于第二个活动,我添加了一些基本内容。

    public class SecondActivity extends AppCompatActivity {


    public static final String TAG = SecondActivity.class.getSimpleName();

    public static String STRING_EXTRA = "string_extra";

    private TextView textView = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_activity);
        textView = findViewById(R.id.tv_received);
        parseIntent(getIntent());
    }

    private void parseIntent(Intent intent) {
        if (intent != null) {
            Bundle extras = intent.getExtras();
            assert extras != null;
            String received = extras.getString(STRING_EXTRA);
            textView.setText(received);
        }

    }
}


我添加了一个基本的xml布局(second_activity.xml):

 <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SecondActivity">

    <TextView
        android:id="@+id/tv_received"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="received from activity one"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>


现在,您需要将活动注册到清单,并且应该完成。

   <aplication tag here>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
</application>

        <activity android:name=".SecondActivity" />