1

我正在尝试在单击时将行设置为粗体。但是当我尝试将视图转换为 TextView 时,它给了我一个 ClassCastException,如下所示 -

setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
  int position, long id) {
            TextView tv = (TextView)view;
            tv.setTypeface(null, Typeface.BOLD);
        }
        });

我究竟做错了什么?我应该怎么做?

编辑:

我的适配器看起来像 -

public class CountryListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final ArrayList<String> names;

public CountryListAdapter(Activity context, ArrayList<String> names) {
    super(context, R.layout.rowlayout, names);
    this.context = context;
    this.names = names;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    View rowView = inflater.inflate(R.layout.rowlayout, null, true);
    TextView textView = (TextView) rowView.findViewById(R.id.label);
    textView.setText(names.get(position));

    return rowView;
}
}
4

2 回答 2

7

您的适配器代码显示了失败的主要原因:

根据您的适配器代码,view您投射的是 rowView,而不是 textView。所以您也应该以这种方式访问​​它。这就是为什么你得到ClassCastException.

 public void onItemClick(AdapterView<?> parent, View view,
 int position, long id) {
        View rowView = view
        TextView tv = (TextView) rowView.findViewById(R.id.label);
        tv.setTypeface(null, Typeface.BOLD);
    }
    });
于 2011-11-16T22:29:03.077 回答
0

您确定您的列表项是TextView? 通常它是一个更复杂的结构(例如 a LinearLayout)。如果是这种情况,您需要TextView使用findById().

于 2011-11-16T22:33:45.090 回答