2

I have a ListView that contains several TextView items. This list is created at runtime, and can vary in size. I would like to set the background of a TextView item based on a float value generated at runtime. I am using an ArrayAdapter.

setListAdapter(new ArrayAdapter<String>(this, R.layout.list_fruit,ratios));  
final ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setBackgroundColor(Color.LTGRAY);
((TextView) listView.getChildAt(0)).setBackgroundColor(Color.CYAN);

The last line throws a NullPointerException. For some reason I cannot access this TextView inside the listView. How am I supposed to set the background color of a TextView dynamically if I don't know the color until runtime?

3 Answers3

2

Simply find the TextView as:

TextView myTextView = (TextView)findViewById(R.id.yourTextViewId);

And do what ever you want for example:

myTextView.setTextColor(color); 
myTextView.setBackgroundColor(color);

EDIT:

Please find on this site how to implement "android custom adapter"?

Yaqub Ahmad
  • 27,569
  • 23
  • 102
  • 149
  • 1
    but he says it in a ListView.... That means you'll have to create a custom adapter and not use a standard adapter such as setListAdapter. The best way is to create a public class that extends ListAdapter then you can override the definitions for getView where can do anything you want to your textviews like Yaqub suggests – Martin Aug 02 '12 at 05:14
  • Exactly. But he can still use `setListAdapter()`. I guess. – Sudarshan Bhat Aug 02 '12 at 05:27
  • using setListAdapter throws a NullPointerException after defining my own unique Custom Adapter – CodingWoodsman Aug 03 '12 at 01:24
0

CustomAdapter.java:

public class CustomAdapter extends ArrayAdapter<String>{

    Context mContext;
    String list[];
    LayoutInflater mInflater;
    public static HashMap<Integer, String> idList=new HashMap<Integer,String>();

    public CustomAdapter(Context context, int textViewResourceId,String[] objects) {
        super(context, textViewResourceId, objects);

        mContext=context;
        list=objects;
        mInflater=LayoutInflater.from(context);
        for(int i=0;i<list.length;i++){
            idList.put(i,"false");
        }
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        final ViewHolder holder;
        if(convertView==null){
            convertView=mInflater.inflate(R.layout.list_fruit,null);
            holder=new ViewHolder();

            holder.mTextView=(TextView)convertView.findViewById(R.id.mTextViewId);  
            convertView.setTag(holder);
        }
        else
            holder=(ViewHolder)convertView.getTag();

        idList.put(position, "true");           

        if(idList.get(position)=="true")
            holder.mTextView.setBackgroundColor(Color.GRAY);
        else
            holder.mTextView.setBackgroundColor(Color.WHITE);

        return convertView;
    }
    class ViewHolder{
        TextView mTextView;
    }
}

list_fruit.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/mTextViewId" 
    android:background="#fff"
    android:textColor="#333"
    android:padding="5dip"/>

Now,

setListAdapter(new CustomAdapter(this, R.layout.list_fruit,ratios));  
final ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setBackgroundColor(Color.LTGRAY);
((TextView) listView.getChildAt(0)).setBackgroundColor(Color.CYAN);

Now,whichever textview will be clicked,will get GRAY color,and others are WHITE colored.

Hiral Vadodaria
  • 19,158
  • 5
  • 39
  • 56
  • This is the kind of thing I am looking for, unfortunately I am still getting errors: 1. the variable _names_ is undefined so I created a String[] names variable in CustomAdapter, 2. When calling the _setListAdapter()_ method the CustomAdapter passed in had to have its template removed, 3. I had to remove _android._ from the android.R.layout.list_fruit argument passed in. When I eventually get this to compile, the _setListAdapter_ line crashes with a NullPointerException – CodingWoodsman Aug 03 '12 at 01:15
  • Please check the code now.i have done few fixes.I missed out few change in variable names in my previous code.Now it seems to be ready for you.Though,let me know if any problem occurs. – Hiral Vadodaria Aug 03 '12 at 04:46
0

I assume you want to change color of list items selectively. For that you have to write your own custom adapter and override getView() method. Inside getView() you can change the color of any item depending on the position.

This link may help you write a custom adapter.

your getView() should look something like this -

 @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View rowView = convertView;
        StockQuoteView sqView = null;

        if(rowView == null)
        {
            // Get a new instance of the row layout view
            LayoutInflater inflater = activity.getLayoutInflater();
            rowView = inflater.inflate(R.layout.stock_quote_list_item, null);

            // Hold the view objects in an object,
            // so they don't need to be re-fetched
            sqView = new StockQuoteView();
            sqView.ticker = (TextView) rowView.findViewById(R.id.ticker_symbol);
            sqView.quote = (TextView) rowView.findViewById(R.id.ticker_price);

            // Cache the view objects in the tag,
            // so they can be re-accessed later
            rowView.setTag(sqView);
        } else {
            sqView = (StockQuoteView) rowView.getTag();
        }

        if(position == 3) {
            rowView.setBackgroundColor(#030303);
        }

        // Transfer the stock data from the data object
        // to the view objects
        StockQuote currentStock = stocks.get(position);
        sqView.ticker.setText(currentStock.getTickerSymbol());
        sqView.quote.setText(currentStock.getQuote().toString());

        return rowView;
    }

Hope that helps.

Sudarshan Bhat
  • 3,772
  • 2
  • 26
  • 53