按下时更改列表视图行中textview的样式

时间:2012-03-25 13:02:13

标签: android android-listview android-adapter

单击该行时,我想更改列表视图行中textview的样式。该文本应保持聚焦,直到按下另一行。我正在使用BaseAdapter的子类在列表视图中构建行。如果我能得到一些帮助来实现这一目标会很棒。

这是我的基本适配器类的一部分。

   public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    MyHolder holder;
    LayoutInflater inflater = context.getLayoutInflater();
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.street_listrow, null);
        holder = new MyHolder();
        holder.txtViewStreet= (TextView) convertView
                .findViewById(R.id.StreetName);
        holder.txtViewArea = (TextView) convertView
                .findViewById(R.id.StreetArea);
        holder.txtViewDist = (TextView) convertView
                .findViewById(R.id.StreetDistance);
        holder.ivGo = (ImageView) convertView.findViewById(R.id.StreetGo);
        convertView.setTag(holder);
    } else {
        holder = (MyHolder) convertView.getTag();;
    }

      holder.txtViewStreet.setText(street.get(position).getStreet());
      holder.txtViewArea.setText(street.get(position).getArea());
      holder.ivGo.setBackgroundResource(R.drawable.goicon);
      int tempDist = Integer.parseInt(street.get(position).getDistance());
      if(tempDist>1000){
          Double bigDist = (double)tempDist / 1000;
          dist = df.format(bigDist) +" km";
      }else{
          dist = tempDist+" m";
      }
      holder.txtViewDist.setText(dist);
    return convertView;
}

我希望txtViewStreet在单击的行上将颜色更改为绿色。

基本上:

ROW1

Row2

ROW3

用户按行第2行

ROW1

行2

ROW3

用户按行第1行

ROW1

行2

ROW3

1 个答案:

答案 0 :(得分:0)

您可以在适配器类中创建一个包含当前所选项的字段:

int current = -1;

每次单击onItemClick()

中的行时,此位置都会更新
protected void onListItemClick(ListView l, View v, int position, long id) {
        adapter.current = position;
        adapter.notifyDataSetChanged();
    }

然后在您的getView()方法中:

//...
holder.txtViewStreet.setText(street.get(position).getStreet());
if (position == current) {
    holder.txtViewStreet.setTextColor(Color.GREEN);
} else {
    holder.txtViewStreet.setTextColor(Color.WHITE); // or what is your default color
}
//...