Android ListView setTypeFace和setBackgroundDrawable

时间:2012-08-07 17:16:27

标签: android android-listview android-arrayadapter

我有一个带有OnItemClickListener的ListView,我在其中设置背景以指示行已被选中

itemList.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {

        String item = (String) arg0.getItemAtPosition(position);
        boolean itemSelected = selectedItems.contains(item);

        if (!itemSelected) {
            selectedItems.add(item);
            v.setBackgroundDrawable(getResources().getDrawable(R.drawable.listitem_selected));
        } else {
            selectedItems.remove(item);
            v.setBackgroundDrawable(null);
        }
    });

如果我为ListView使用默认适配器,则ListView行会正确突出显示

ArrayList<String> listOfItems = new ArrayList<String>();

....
final ArrayAdapter<String> itemAdapter = new ArrayAdapter<String>(this, R.layout.list_item, listOfItems);

如果我使用扩展ArrayAdapter的自定义适配器以便我可以将TextView的字体设置为自定义字体,则可以正确设置字体,但背景突出显示不再有效。有什么想法吗?

public class ListItemAdapter extends ArrayAdapter<String> {
    private final Context context;
    private final ArrayList<String> values;

    public ListItemAdapter(Context context, ArrayList<String> values) {
        super(context, R.layout.list_item, values);
        this.context = context;
        this.values = values;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.list_item, parent, false);
        TextView textView = (TextView) rowView.findViewById(R.id.text1);

        Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/font-file.otf"); 
        textView.setTypeface(tf);
        textView.setText(values.get(position));
        return rowView;
    }
}

2 个答案:

答案 0 :(得分:1)

试试这个。它起作用了。它也可能对你有帮助。

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.list_item, parent, false);
    TextView textView = (TextView) rowView.findViewById(R.id.text1);

    Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/font-file.otf"); 
    textView.setTypeface(tf);
    textView.setText(values.get(position));

    rowView.setOnClickListener(new OnClickListener() {              
        @Override
        public void onClick(View arg0) {
            arg0.setBackgroundResource(R.drawable.<background>);                    
        }
    });
    return rowView;
}

答案 1 :(得分:0)

您还需要在getView()方法

中设置行视图背景