简体   繁体   中英

How to change the font of textview when it is a part of listview using SimpleAdapter

Following is my code :

And I wanna change the font of a Textview whose id is 'name12'. Need Help. Thank you in advance.

String rid = jObj.getString(TAG_RID);
String name = jObj.getString(TAG_NAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_RID, rid);
map.put(TAG_NAME, name);
oslist.add(map);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v, new String[] { TAG_NAME }, new int[] { R.id.name12});
l1.setAdapter(adapter);

you can extend TextView class and set font inside.

After that you can use this TextView in R.layout.list_v

public class TextViewWithFont extends TextView {

    public TextViewWithFont(Context c) {
        this(c, null);
    }

    public TextViewWithFont(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setTypeface(Typeface.createFromAsset(context.getAssets(), "fontname.ttf"));
    }

    public TextViewWithFont(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

}

The better way to achieve what you want is to create custom adapter. Which will provide you more control.

If you want simple adapter to use any how, Do the following:

public class CustomAdapter extends SimpleAdapter {
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = super.getView(position, convertView, parent);
        Object item = getItem(position);
        //iterate to this view and it's child and if it's an instance of textview set the color 
        ColorStateList color = //get color for item;
        text.setTextColor(color);
        return v;
    }
}

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