如何更改ListFragment中某些行的颜色?

时间:2014-05-18 01:47:41

标签: android android-fragments android-listview fragment android-listfragment

我有一个ListFragment,我用这样的数据填充:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), 
            android.R.layout.simple_list_item_1, mNames);

对于mNames中的某些名称,我希望文本具有不同的颜色。我怎么能做到这一点?

我试过这个来计算子视图,但它返回0:

public void onActivityCreated(Bundle savedInstanceState) {
    ListView listView = getListView();
    int count = listView.getChildCount();
    super.onActivityCreated(savedInstanceState);
    Log.w("COUNT", "" + count);
}

我也尝试过在ArrayAdapter中覆盖getView()的变体,但没有成功。有什么建议吗?

2 个答案:

答案 0 :(得分:0)

您需要像这样创建自己的适配器类:

public class MyListAdapter extends BaseAdapter {

    LayoutInflater inflater;
    List<String> items;


    public MyGridAdapter(Context context, List<String> items) {
        this.items = items;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }


    @Override
    public int getCount() {
        return items.size();
    }


    @Override
    public Object getItem(int position) {
        return items.get(position);
    }


    @Override
    public long getItemId(int position) {
        return position;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = inflater.inflate(android.R.layout.simple_list_item_1, null);
        }

        if (items.get(position).equals("James")){
            // Do what you want with it
        }

        return convertView;
    }

}

答案 1 :(得分:0)

使用 ArrayAdapter

更改原始文字颜色
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), 
android.R.layout.simple_list_item_1, myList) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView text = (TextView) view.findViewById(android.R.id.text1);
//flag is a boolean for selected raws
if(flag== True){
  text.setTextColor(Color.BLACK);
}   
return view;
}
};

使用 SimpleAdapter

更改原始颜色
public class MySimpleAdapter extends SimpleAdapter {

public MySimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
//change color is a method to pass selected raws for change color
if (changecolor(position)) ((TextView)view.findViewById(R.id.main_name)).setTextColor(0xffff0000);
return view;
}

}

快乐编码