版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Lamphogani/article/details/77932592
效果
代码
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_centerHorizontal="true"
android:gravity="center_vertical"
android:text="item"
android:textColor="@color/colorTv" />
<ImageView
android:id="@+id/iv"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_centerVertical="true"
android:layout_marginLeft="15dp"
android:layout_toRightOf="@id/tv"
android:scaleType="center"
android:src="@mipmap/icon_check_mark"
android:visibility="gone" />
</RelativeLayout>
public class MyAdapter extends BaseAdapter {
private Context mContext;
private int checkItemPosition = -1;
public MyAdapter(Context context) {
this.mContext = context;
}
public void setCheckItem(int position) {
checkItemPosition = position;
notifyDataSetChanged();
}
@Override
public int getCount() {
return 20;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder;
if (view == null) {
view = LayoutInflater.from(mContext).inflate(R.layout.item_layout, viewGroup, false);
holder = new ViewHolder();
holder.tv = view.findViewById(R.id.tv);
holder.iv = view.findViewById(R.id.iv);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
fillData(i, holder);
return view;
}
private void fillData(int position, ViewHolder holder) {
if (checkItemPosition != -1) {
if (checkItemPosition == position) {
holder.tv.setTextColor(mContext.getResources().getColor(R.color.colorAccent));
holder.iv.setVisibility(View.VISIBLE);
} else {
holder.tv.setTextColor(mContext.getResources().getColor(R.color.colorTv));
holder.iv.setVisibility(View.GONE);
}
}
}
private static class ViewHolder {
private TextView tv;
private ImageView iv;
}
}
ListView listview = (ListView) findViewById(R.id.listview);
myAdapter = new MyAdapter(this);
listview.setAdapter(myAdapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
myAdapter.setCheckItem(i);
}
});