赞
踩
1.字体颜色只是在按下那一瞬间改变,松手后立刻恢复
效果
只是在res/color文件下创建item_text_selector.xml文件
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:color="@color/colorAccent" android:state_pressed="true"></item> <item android:color="@color/colorPrimaryDark" android:state_pressed="false"></item> </selector>
然后在TextView中引用即可
android:textColor="@color/item_text_selector"
2.字体颜色按下后就一直为改变的颜色,松手后不会恢复,直到下一个Item选中后才恢复
效果
处理思想:在适配器里写好字体变化的相关逻辑,然后在外部事件监听中改变某个值,通知字体改变。
将item_text_selector.xml中的state_pressed改为state_selected
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:color="@color/colorAccent" android:state_selected="true"></item> <item android:color="@color/colorPrimaryDark" android:state_selected="false"></item> </selector>
依然在TextView中引用
然后在自定义的适配器代码中
//当前Item被点击的位置 private int currentItem; public void setCurrentItem(int currentItem) { this.currentItem = currentItem; }
然后在getView()方法中
//设置文字 内容 holder.mTextView.setText(mList.get(position)); if (currentItem == position) { //如果被点击,设置当前TextView被选中 holder.mTextView.setSelected(true); } else { //如果没有被点击,设置当前TextView未被选中 holder.mTextView.setSelected(false); } return convertView;
最后在Activity中编写ListView的Item点击事件
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //改变选中状态 adapter.setCurrentItem(position); //通知ListView改变状态 adapter.notifyDataSetChanged(); } });
适配器的完整代码
public class MyAdapter extends BaseAdapter { //当前Item被点击的位置 private Context mContext; private List<String> mList; public MyAdapter(Context context, List<String> list) { this.mContext = context; this.mList = list; } //当前Item被点击的位置 private int currentItem = -1; public void setCurrentItem(int currentItem) { this.currentItem = currentItem; } @Override public int getCount() { return mList.size(); } @Override public Object getItem(int position) { return mList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { convertView = LayoutInflater.from(mContext).inflate(R.layout.item_listview, null); holder = new ViewHolder(convertView); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } //设置文字 内容 holder.mTextView.setText(mList.get(position)); if (currentItem == position) { //如果被点击,设置当前TextView被选中 holder.mTextView.setSelected(true); } else { //如果没有被点击,设置当前TextView未被选中 holder.mTextView.setSelected(false); } return convertView; } class ViewHolder { TextView mTextView; public ViewHolder(View convertView) { mTextView = (TextView) convertView.findViewById(R.id.tv_text); } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。