Android 使用简单适配器更改ListView中的TextView背景色

Android 使用简单适配器更改ListView中的TextView背景色,android,listview,android-listview,adapter,listadapter,Android,Listview,Android Listview,Adapter,Listadapter,我有一个列表视图,它显示一个包含两个文本视图的列表。在其中一个上,我想应用一种特定的颜色。所有数据(和颜色)都由web服务的Json文件提供 我使用一个我想使用的简单适配器。有人能告诉我如何为每件商品添加特定的颜色吗 这是我的班级: public class NetworkTimeTableFragment extends Fragment { private ProgressDialog pDialog; private static String mylat; p

我有一个列表视图,它显示一个包含两个文本视图的列表。在其中一个上,我想应用一种特定的颜色。所有数据(和颜色)都由web服务的Json文件提供

我使用一个我想使用的简单适配器。有人能告诉我如何为每件商品添加特定的颜色吗

这是我的班级:

public class NetworkTimeTableFragment extends Fragment {

    private ProgressDialog pDialog;

    private static String mylat;
    private static String mylng;

    // JSON Node names
    private static final String TAG_NAME = "shop_name";
    private static final String TAG_SHORT = "shop_address";
    private static final String TAG_ID = "shop_url";
    private static final String TAG_COLOR = "feuilletez";
    TextView shop_address;
    TextView shop_name;
    TextView shop_url;
    ImageButton feuilletez;
    private ListView list;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();

    public NetworkTimeTableFragment(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_timetable, container, false);

        // Calling async task to get json
        new GetJson().execute();

        return rootView;
    }

    /**
     * Async task class to get json by making HTTP call
     */
    private class GetJson extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            // Showing progress dialog
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Loading...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            String myurl = "routes.json";

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(myurl, ServiceHandler.GET);

            JSONArray array = null;
            try {
                array = new JSONArray(jsonStr);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                for (int i = 0; i < array.length(); i++) {
                    JSONObject jsonObject = array.getJSONObject(i);
                    String id = jsonObject.getString("id");
                    System.out.println("id --->" + id);
                    String url = jsonObject.getString("url");
                    System.out.println("url --->" + url);
                    String created_at = jsonObject.getString("created_at");
                    System.out.println("created_at --->" + created_at);
                    String updated_at = jsonObject.getString("updated_at");
                    System.out.println("updated_at --->" + updated_at);
                    String short_name = jsonObject.getString("short_name");
                    System.out.println("short_name --->" + short_name);
                    String long_name = jsonObject.getString("long_name");
                    System.out.println("long_name --->" + long_name);
                    String desc = jsonObject.getString("desc");
                    System.out.println("desc --->" + desc);
                    String type = jsonObject.getString("type");
                    System.out.println("type --->" + type);
                    String type_name = jsonObject.getString("type_name");
                    System.out.println("type_name --->" + type_name);
                    String color = jsonObject.getString("color");
                    System.out.println("color --->" + color);

                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put(TAG_NAME, long_name);
                    map.put(TAG_SHORT, short_name);
                    map.put(TAG_COLOR, color);
                    map.put(TAG_ID, id);
                    oslist.add(map);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            list = (ListView) getActivity().findViewById(R.id.list);
            ListAdapter adapter = new SimpleAdapter(
                    getActivity(),
                    oslist,
                    R.layout.listview_routes_row,
                    new String[]{TAG_NAME, TAG_SHORT, TAG_COLOR},
                    new int[]{R.id.long_name, R.id.short_name});

            list.setAdapter(adapter);

            list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    //  Intent intent = new Intent(NewsActivity.this, NewsActivity.class);
                    //intent.putExtra("shopurl",oslist.get(+position).get(TAG_URL));
                    // overridePendingTransition(R.anim.animationin, R.anim.animationout);
                    //  startActivity(intent);
                }
            });

            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
        }
    }
}
公共类NetworkTimeTableFragment扩展片段{
私人对话;
私有静态字符串mylat;
私有静态字符串mylng;
//JSON节点名称
私有静态最终字符串TAG_NAME=“shop_NAME”;
私有静态最终字符串TAG\u SHORT=“shop\u address”;
私有静态最终字符串标记\u ID=“shop\u url”;
私有静态最终字符串标记\u COLOR=“feuilletez”;
TextView商店地址;
TextView商店名称;
TextView商店网址;
图像按钮feuilletez;
私有列表视图列表;
//ListView的Hashmap
ArrayList oslist=新的ArrayList();
公用网络TimeTableFragment(){}
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
视图根视图=充气机。充气(R.layout.fragment\u时间表,容器,错误);
//调用异步任务以获取json
新建GetJson().execute();
返回rootView;
}
/**
*异步任务类通过HTTP调用获取json
*/
私有类GetJson扩展异步任务{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
//显示进度对话框
pDialog=newprogressdialog(getActivity());
设置消息(“加载…”);
pDialog.setCancelable(假);
pDialog.show();
}
@凌驾
受保护的Void doInBackground(Void…arg0){
//创建服务处理程序类实例
ServiceHandler sh=新的ServiceHandler();
字符串myurl=“routes.json”;
//向url发出请求并获得响应
字符串jsonStr=sh.makeServiceCall(myurl,ServiceHandler.GET);
JSONArray数组=null;
试一试{
数组=新的JSONArray(jsonStr);
}捕获(JSONException e1){
//TODO自动生成的捕捉块
e1.printStackTrace();
}
试一试{
对于(int i=0;i”+id);
字符串url=jsonObject.getString(“url”);
System.out.println(“url-->”+url);
String created_at=jsonObject.getString(“created_at”);
System.out.println(“created_at-->”+created_at);
String updated_at=jsonObject.getString(“updated_at”);
System.out.println(“更新时间--->”+更新时间);
String short_name=jsonObject.getString(“short_name”);
System.out.println(“短名称-->”+短名称);
String long_name=jsonObject.getString(“long_name”);
System.out.println(“long\u name-->”+long\u name);
String desc=jsonObject.getString(“desc”);
System.out.println(“desc-->”+desc);
字符串类型=jsonObject.getString(“类型”);
System.out.println(“type-->”+type);
String type_name=jsonObject.getString(“type_name”);
System.out.println(“type\u name-->”+type\u name);
字符串颜色=jsonObject.getString(“颜色”);
System.out.println(“颜色-->”+颜色);
HashMap=newHashMap();
地图放置(标签名称、长名称);
map.put(TAG_SHORT,SHORT_name);
地图放置(标签颜色、颜色);
地图放置(标签标识,标识);
添加(地图);
}
}捕获(JSONException e){
e、 printStackTrace();
}
返回null;
}
@凌驾
受保护的void onPostExecute(void结果){
super.onPostExecute(结果);
list=(ListView)getActivity().findViewById(R.id.list);
ListAdapter=新的SimpleAdapter(
getActivity(),
奥斯陆,
R.layout.listview\u routes\u行,
新字符串[]{TAG_NAME,TAG_SHORT,TAG_COLOR},
新的int[]{R.id.long_name,R.id.short_name});
list.setAdapter(适配器);
list.setOnItemClickListener(新的AdapterView.OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父级、视图、,
内部位置,长id){
//意向意向=新意向(NewsActivity.this,NewsActivity.class);
//intent.putExtra(“shopurl”,oslist.get(+position.get(TAG_URL));
//覆盖转换(R.anim.animationin,R.anim.animationout);
//星触觉(意向);
}
});
//关闭进度对话框
if(pDialog.isShowing())
pDialog.disclose();
}
}
}

您可以尝试以下操作:textview.setTextColor(颜色)

你可以试试这个:textview.setTextColor(color)

要为每个项目创建自定义视图,您必须创建自己的适配器,而不是使用默认适配器,但这非常简单:

public class CustomAdapter extends SimpleAdapter {
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = super.getView(position, convertView, parent);
        Object item = getItem(position);
        TextView text = v.findViewById(//your text view id);
        ColorStateList color = //get color for item;
        text.setTextColor(color);
        return v;
    }
}

要为每个项目创建自定义视图,您必须创建自己的适配器,而不是使用默认适配器,但这非常简单:

public class CustomAdapter extends SimpleAdapter {
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = super.getView(position, convertView, parent);
        Object item = getItem(position);
        TextView text = v.findViewById(//your text view id);
        ColorStateList color = //get color for item;
        text.setTextColor(color);
        return v;
    }
}
更好的实现方法
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/long_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="10dip" />

    <TextView
        android:id="@+id/short_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="10dip" />

</LinearLayout>
public class CustomSimpleAdapter extends SimpleAdapter {

    private List<Map<String, Object>> itemList;
    private Context mContext;
    private static final String TAG_COLOR = "color";
    private static final String TAG_NAME = "shop_name";
    private static final String TAG_SHORT = "shop_address";

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

        this.itemList = (List<Map<String, Object>>) data;
        this.mContext = context;
    }

    /* A Static class for holding the elements of each List View Item
     * This is created as per Google UI Guideline for faster performance */
    class ViewHolder {
        TextView textLong;
        TextView textShort;
    }

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

        ViewHolder holder = null;

        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.listview_routes_row, null);
            holder = new ViewHolder();

            // get the textview's from the convertView
            holder.textLong = (TextView) convertView.findViewById(R.id.long_name);
            holder.textShort = (TextView) convertView.findViewById(R.id.short_name);

            // store it in a Tag as its the first time this view is generated
            convertView.setTag(holder);
        } else {
            /* get the View from the existing Tag */
            holder = (ViewHolder) convertView.getTag();
        }

        /* update the textView's text and color of list item */
        holder.textLong.setText((CharSequence) itemList.get(position).get(TAG_NAME));
        holder.textShort.setText((CharSequence) itemList.get(position).get(TAG_SHORT));
        holder.textShort.setTextColor((Integer) itemList.get(position).get(TAG_COLOR));

        return convertView;
    }

}
public class MainActivity extends Activity {

    private static final String TAG_NAME = "shop_name";
    private static final String TAG_SHORT = "shop_address";
    private static final String TAG_COLOR = "color";

    private List<Map<String, Object>> itemList = new ArrayList<Map<String, Object>>();
    private Map<String, Object> map;
    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.list_view);

        //Sample data insertion into the list
        map = new LinkedHashMap<String, Object>();
        map.put(TAG_NAME, "textview11");
        map.put(TAG_SHORT, "textview12");
        map.put(TAG_COLOR, Color.BLUE);
        itemList.add(map);

        map = new LinkedHashMap<String, Object>();
        map.put(TAG_NAME, "textview21");
        map.put(TAG_SHORT, "textview22");
        map.put(TAG_COLOR, Color.GREEN);
        itemList.add(map);

        map = new LinkedHashMap<String, Object>();
        map.put(TAG_NAME, "textview31");
        map.put(TAG_SHORT, "textview32");
        map.put(TAG_COLOR, Color.RED);
        itemList.add(map);

        /* create an adapter for listview*/
        SimpleAdapter adapter = new CustomSimpleAdapter(this, itemList,
                R.layout.listview_routes_row, new String[] { TAG_NAME, TAG_SHORT }, new 
                int[] { R.id.long_name, R.id.short_name });

        listView.setAdapter(adapter);
    }

}