Question

I have a ListView which displays a list with two TextViews. On one of them, I want to apply a specific color. All the data (and colors) are provided by a Json file from web service.

I use a simple adapter which I want to use. Could someone indicate how to put the specific color for each item?

Here is my class:

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();
        }
    }
}
Was it helpful?

Solution

The better way to achieve what you want is to create custom adapter. Here I am giving you an example to achieve your goal...

Activity Layout---> activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <ListView
        android:id="@+id/list_view"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

List Item Layout---> listview_routes_row.xml

<?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>

Custom SimpleAdapte---> CustomSimpleAdapter.java

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;
    }

}

Activity Class---> MainActivity.java

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);
    }

}

I think it will help you. If you have any problem then let me know.

OTHER TIPS

For creating custom view for each item you'll have to create your own adapter instead of using the defaults one, but it's pretty easy:

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;
    }
}

you can try this:textview.setTextColor(color);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top