简体   繁体   中英

Change TextView colour and text in getView(…) in ListView adapter

I've searched for this and I could find exactly the answer I needed...

I have a navigation drawer ListView , and I when an item is clicked in the list, I want to be able to get the TextView from it, and change its background colour, text colour and make the text bold.

I've tried getting the TextView by doing the following;

adapter_navList = new ArrayAdapter<String>(this, R.layout.listview_navdrawer, drawerItems) {
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);

        TextView item = (TextView) lv_navList.getItemAtPosition(i); 
        // Code to set the background, formatting, colour, etc.

        return view;
    }
};
lv_navList.setAdapter(adapter_navList);

However, I keep receiving the following error:

java.lang.ClassCastException: java.lang.String cannot be cast to android.widget.TextView

How would I resolve this issue?

You can use the following:

adapter_navList = new ArrayAdapter<String>(this, R.layout.listview_navdrawer, drawerItems) {
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);

        TextView mytextview=(TextView)view;
        mytextview.setTextColor(Color.BLUE); 
        mytextview.setTextSize(14);
        // Other code you may want to add

        return view;
    }
};
lv_navList.setAdapter(adapter_navList);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM