为了防止看错内容,下面讲解要实现的内容
方法有很多中,这里使用notifyDataSetChanged 来刷新内容个人感觉更为简单点
首先可以先定义一个位置,然后点击item的时候把positon 赋值给自己定义位置,然后在绑定数据的地方修改文字颜色以及背景色即可 下面看下代码
package com.hly.recyclerview;import android.graphics.Color;import android.os.Build;import android.support.annotation.RequiresApi;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import android.util.Log;import android.view.View;import android.widget.LinearLayout;import android.widget.TextView;import java.util.ArrayList;import java.util.List;public class MainActivity extends AppCompatActivity {private RecyclerView recyclerView;RecyclerViewAdapter adapter;List<String> list = new ArrayList<>();int currentPosition = 0;@RequiresApi(api = Build.VERSION_CODES.M)@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);recyclerView = findViewById(R.id.recy);for (int i = 0; i < 15; i++) {list.add("");}recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));adapter = new RecyclerViewAdapter(this, R.layout.list_item, list);recyclerView.setAdapter(adapter);adapter.setOnItemClickListner(new RecyclerViewAdapter.OnItemClickListner() {@Overridepublic void onItemClickListner(View v, int position) {currentPosition = position;adapter.notifyDataSetChanged();}});adapter.setCallBack(new RecyclerViewAdapter.CallBack() {@Overridepublic <T> void convert(IViewHolder holder, T bean, int position) {TextView textView = (TextView) holder.getView(R.id.txt);LinearLayout linearLayout = (LinearLayout) holder.getView(R.id.li);if (position ==currentPosition){textView.setTextColor(Color.parseColor("#D61642"));linearLayout.setBackgroundColor(Color.parseColor("#FFFEBE"));}else{textView.setTextColor(Color.parseColor("#1A1B1B"));linearLayout.setBackgroundColor(Color.parseColor("#b5b5b5"));}}});}}
全部内容展示了出来,是不是很简单,
demo 地址 ,记得给个star
如果觉得《RecyclerView 点击Item 改变文字颜色以及所在的背景色》对你有帮助,请点赞、收藏,并留下你的观点哦!