列表查看项目文本不改变颜色

时间:2015-06-03 16:54:04

标签: java android xml android-fragments android-activity

我尝试使用自定义适配器更改列表项的文本颜色,以便它们各自都有自己的颜色但我收到的错误是我不知道如何修复。如何解决这个错误?

enter image description here

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class FragmentLineChooserList extends android.support.v4.app.Fragment {

    ListView list_linechooser;

    String[] listContent = {
            "Line 1",
            "Line 2",
            "Line 3"
    };

    private boolean mTwoPane;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View v = inflater.inflate(R.layout.fragment_line_chooser_list, container, false);

        list_linechooser = (ListView)v.findViewById(R.id.list_linechooser);
        MyColoringAdapter adapter = new MyColoringAdapter(this,listContent);
        list_linechooser.setAdapter(adapter);

        return v;
    }

    private class MyColoringAdapter extends ArrayAdapter<String> {
        private final Context context;
        private final String[] values;

        public MyColoringAdapter(Context context, 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.list_item);
            textView.setText(values[position]);
            int textColorId = R.color.white;
            switch (position) {
                case 0:
                    textColorId = R.color.green; break;
                case 1:
                    textColorId = R.color.orange; break;
                case 2:
                    textColorId = R.color.blue; break;
            }
            textView.setTextColor(getResources().getColor(textColorId));
            return rowView;
        }
    }
}

1 个答案:

答案 0 :(得分:2)

MyColoringAdapter的构造函数的第一个参数是ContextFragment不是Context,因此您无法将this传递给构造函数,因为您尝试在片段中进行操作。

您可以通过调用getActivity()来获取片段活动(这是一个上下文)。