如何在Listview中查看textview的背景颜色

时间:2016-09-04 13:26:35

标签: android listview textview background-color

我试图在ListView中突出显示某些字符串。因此,我尝试设置TextView的背景颜色,这是该ListView的实际元素。但是,使用setBackgroundResource和setBackgroundColor的下面代码不会导致默认颜色设置的更改。我究竟做错了什么?我还可以使用其他预期的设计方案,如何在Listview中实现个别条目的突出显示。

提前谢谢!

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(LOG_TAG, "Enter onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        dao = MealDAO.getInstance(this);
        List<Meal> mealList = dao.getAllMeals();

        mealListeAdapter = new ArrayAdapter<>(
                this, // Die aktuelle Umgebung (diese Activity)
                R.layout.meal_list_item, // ID der XML-Layout Datei
                R.id.meal_list_item_textview, // ID des TextViews
                mealList); // Beispieldaten in einer ArrayList

        ListView mealListView = (ListView) findViewById(R.id.listview_mealliste);
        mealListView.setAdapter(mealListeAdapter);

        for(int i=0; i<mealList.size(); i++) {
            Meal meal = mealList.get(i);
            if(meal.toString().indexOf("(!)") > 0) {
                TextView view = (TextView) mealListeAdapter.getView(i, null, null);
                view.setBackgroundResource(R.color.colorAccent);
                view.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.colorAccent));
            }
        }

        ...
     }

1 个答案:

答案 0 :(得分:0)

在listview适配器上

,您可以通过将颜色设置为视图/ textview项来更改getview函数中的颜色。 就我而言,可以用这个来完成。

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
     View rowView;
     if (convertView == null) {
         rowView = getActivity().getLayoutInflater().inflate(
             R.layout.searchitemview, null);
     } else {
         rowView = convertView;
     }


     TextView firstTextView = (TextView) rowView
         .findViewById(R.id.txtTitle);
     firstTextView.setText((position + 1) + ". " +
         items.get(position).first);

     if ((position % 2) == 0) {
         // convertView.setBackgroundColor(color_arr[position]);
         rowView.setBackgroundResource(R.drawable.cell_shapegrey);
     } else {
         rowView.setBackgroundResource(R.drawable.cell_shape);
     }
     TextView batas = (TextView) rowView.findViewById(R.id.batasumur);
     if (items.get(position).fiveth.contains("17")) {
         batas.setBackgroundResource(R.drawable.rounded_red);
     } else if (items.get(position).fiveth.contains("emaja")) {
         batas.setBackgroundResource(R.drawable.rounded_oren);
     } else {
         batas.setBackgroundResource(R.drawable.rounded_green);
     }
     batas.setText(items.get(position).fiveth);
     return rowView;
 }