如何更改 ListFragment 中某些行的颜色?
Posted
技术标签:
【中文标题】如何更改 ListFragment 中某些行的颜色?【英文标题】:How to change color of certain row inside ListFragment? 【发布时间】:2014-07-06 05:39:53 【问题描述】:我有一个 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()
的变体,但没有成功。
【问题讨论】:
【参考方案1】:您需要像这样创建自己的适配器类:
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;
【讨论】:
【参考方案2】:使用 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;
【讨论】:
以上是关于如何更改 ListFragment 中某些行的颜色?的主要内容,如果未能解决你的问题,请参考以下文章