【Android】listview选中行字体变大

来源:互联网 发布:淘宝销售方案 编辑:程序博客网 时间:2024/05/16 15:26

目标:listview中item使用textview,当item选中时,字体为25px;当item未选中时,字体21px

device

之前想了很久,以为同listview选中行字体颜色一样,使用xml文件中使用selector就可以改变了,但是一直上网查找资料,都没有找到selector中改变字体大小的命令。后来网友提醒我,可以在adapter中的getview中修改。现将重要的代码放上:

?
1
2
//全局变量,记录选中的item 
public static int select_item = -1;

先使用全局变量记录选中的item,然后在listview的OnItemSelectedListener中实时更新选中的item,并且使用adapter.notifyDataSetChanged()刷新listview数据。

?
1
2
3
4
5
6
7
8
9
10
11
listview_listMenu.setOnItemSelectedListener(new OnItemSelectedListener(){
    @Override
    public void onItemSelected(AdapterView<?>arg0, View arg1, int arg2, long arg3){
    select_item = arg2; //当前选择的节目item
  
    listAdapter.notifyDataSetChanged(); //通知adapter刷新数据
    }
  
    public void onNothingSelected(AdapterView<?> arg0) {
    }
});

接着在adapter的getview中修改字体大小。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Override
public View getView(int position, View convertView, ViewGroup parent) 
{
    convertView = LayoutInflater.from(context.getApplicationContext()).inflate(R.layout.menulistitem, null);
    TextView listItem = (TextView)convertView.findViewById(R.id.name_menu);
    listItem.setText(list.get(position).get("name_menu").toString());
      
    this.select_item = LiveChannelsActivity.select_item;
  
    try{
        if(this.select_item == position){
            listItem.setTextSize(25);   //选中的Item字体:25px
        }
        else
            listItem.setTextSize(21);   //未选中的Item字体:21px
    }catch(Exception ex){
        ex.printStackTrace();
    }
 
      
    return convertView;
}

这样就可以了。

0 0