Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

android - How to set background color for each item listview depanding on variable value

I have a very simple question but Google does not show me a proper answer. I need to setBackground color for each item in my listview depanding on variable value. handle status item needs to be one color and done has to be another.

Listview adapter

class ListViewAdapter extends BaseAdapter{

Context context;
LayoutInflater inflater;
String[] time;
String[] clientName;
String[] district;
String[] address;
String[] goods;
String[] price;
String[] status;

public ListViewAdapter(Context context, String[] time, String[] clientName, String[] district, String[] address, String[] goods, String[] price, String[] status) {
    this.context = context;
    this.time = time;
    this.clientName = clientName;
    this.district = district;
    this.address = address;
    this.goods = goods;
    this.price = price;
    this.status = status;
}


@Override
public int getCount() {
    return clientName.length; // было 0
}

@Override
public Object getItem(int position) {
    return null;
}


@Override
public long getItemId(int position) {
    return 0;
}

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

    TextView txtclientName;
    TextView txttime;
    TextView txtdistrict;
    TextView txtaddress;
    TextView txtgoods;
    TextView txtprice;

    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View itemView = inflater.inflate(R.layout.listview_item, parent, false);

    // Locate the TextViews in listview_item.xml
    txtclientName = (TextView) itemView.findViewById(R.id.clientNameSingle);
    txttime = (TextView)itemView.findViewById(R.id.timeSingle);
    txtdistrict = (TextView)itemView.findViewById(R.id.districtSingle);
    txtaddress = (TextView) itemView.findViewById(R.id.addressSingle);
    txtgoods = (TextView)itemView.findViewById(R.id.goodsSingle);
    txtprice = (TextView)itemView.findViewById(R.id.priceSingle);

    // Capture position and set to the TextViews
    txtclientName.setText(clientName[position]);
    txttime.setText(time[position]);
    txtdistrict.setText(district[position]);
    txtaddress.setText(address[position]);
    txtgoods.setText(goods[position]);
    txtprice.setText(price[position]);

    itemView.setBackgroundColor(Color.parseColor("#00FF7F"));

    return itemView;
}
}

Orderlist class

public class OrderList extends Activity {

ListView list;
ListViewAdapter adapter;
String[] time;
String[] clientName;
String[] district;
String[] address;
String[] goods;
String[] price;
String[] status;


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listview_main);

    time = new String[]{"09:00", "09:00"};
    clientName = new String[]{"Анна", "Ольга"};
    district = new String[]{"Калининский", "Калининский"};
    address = new String[]{"Морская набережная д35", "Проспект Непокоренных 49"};
    goods = new String[]{"Елка 1.8м", "Сосна 2м"};
    price = new String[]{"1499", "2299"};
    status = new String[]{"done", "handle"};

    list = (ListView) findViewById(R.id.listview);

    // Pass results to ListViewAdapter Class
    adapter = new ListViewAdapter(this, time, clientName, district, address, goods, price, status);

    // Binds the Adapter to the ListView
    list.setAdapter(adapter);

    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            Animation animation1 = new AlphaAnimation(0.3f, 1.0f);
            animation1.setDuration(2000);
            view.startAnimation(animation1);


            Intent intent = new Intent(OrderList.this, SingleItemView.class);
            intent.putExtra("time", time);
            intent.putExtra("clientName", clientName);
            intent.putExtra("district", district);
            intent.putExtra("address", address);
            intent.putExtra("goods", goods);
            intent.putExtra("price", price);
            intent.putExtra("position", position);
            intent.putExtra("status", status);
            startActivity(intent);

        }

    });
}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If all you need is to set the color of one of the rows in the ListView then you can do this:

In your ListView Layout "listview_item" give the root layout an id. Eg. "rlMainLayout"

In your getView method you need to get a reference to the layout object. If it is a RelativeLayout then it would look something like this:

final RelativeLayout rlMainLayout = (RelativeLayout) convertView.findViewById(R.id.rlMainLayout);

Now you can set the color to your RelativeLayout object like this:

rlMainLayout.setBackgroundColor(Color.RED);

----------------------------------------------------------

-- EDIT --

A STEP-BY-STEP EXAMPLE

(Please be advised that I did this in a Text Editor program .. so there could be some typos. )

You will need to alter your custom adapter class. Important: You will want to use a model class (in this case called MyListData). It will help when you need to maintain your software to separate your model from your views.

public class MyListDataAdapter extends ArrayAdapter<MyListData> {

    private static final String TAG = "MyListDataAdapter";


    public MyListDataAdapter(Context context, ArrayList<MyListData> data) {
        super(context, 0, data);

    }

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

        final MyListData data = getItem(position);

        if(convertView == null){
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.listview_item, parent, false);
        }
        TextView txtclientName;
        TextView txttime;
        TextView txtdistrict;
        TextView txtaddress;
        TextView txtgoods;
        TextView txtprice;

        // Locate the TextViews in listview_item.xml
        txtclientName = (TextView) itemView.findViewById(R.id.clientNameSingle);
        txttime = (TextView)itemView.findViewById(R.id.timeSingle);
        txtdistrict = (TextView)itemView.findViewById(R.id.districtSingle);
        txtaddress = (TextView) itemView.findViewById(R.id.addressSingle);
        txtgoods = (TextView)itemView.findViewById(R.id.goodsSingle);
        txtprice = (TextView)itemView.findViewById(R.id.priceSingle);

        RelativeLayout rlMainLayout = (RelativeLayout) convertView.findViewById(R.id.rlMainLayout);
        Color originalColorValue = tvNumberOfItems.getDrawingCacheBackgroundColor();

        // Capture position and set to the TextViews
        txtclientName.setText(data.getClientName());
        txttime.setText(data.getTime());
        txtdistrict.setText(data.getDistrict());
        txtaddress.setText(data.getAddress());
        txtgoods.setText(data.getGoods());
        txtprice.setText(data.getPrice());

        if(data.getIsSelected){
            rlMainLayout.setBackgroundColor(Color.RED);
        }
        else{
            rlMainLayout.setBackgroundColor(originalColorValue);
        }

        return itemView;
    }

}

Now you need a model class to hold the data. Let's call it MyListData (But you call it what you like)

public class MyListData {

    // Add more as you need
    // I have used the ones you have defined...
    private String time;
    private String clientName;
    private String district;
    private String address;
    private String goods;
    //... but I think price should be of type double so that you can do calculations if needed
    private String price;
    private String status;
    private boolean isSelected = false;

    public MyListData(){
    }


    public void setTime(String time){ this.time = time; }
    public void setClientName(String clientName){ this.clientName = clientName; }
    public void setDistrict(String district){ this.district = district; }
    public void setAddress(String address){ this.address = address; }
    // TODO: !! ..Please add the others goods, price, status ..
    public void setIsSelected(boolean isSelected){ this.isSelected = isSelected; }

    // Now add your public getters!!
    public String getTime(){ return this.time; }
    public String getClientName(){ return this.setClientName; }
    // TODO: !! ... Please add the others for goods, price, status...
    public boolean getIsSelected(){ return this.isSelected; }

}

Your custom ListView layout could look something like the following. Please notice the root layout has an identifier rlMainLayout!

    <?xml version="1.0" encoding="utf-8"?>
        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
                android:id="@+id/rlMainLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingTop="5dp"
            android:paddingBottom="5dp"
            >

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        >

        <TextView
            android:id="@+id/tvTime"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        >

        <TextView
            android:id="@+id/tvAddress"
            android:text="address"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

    </LinearLayout>

</RelativeLayout>

In your Activity (eg. in the onCreate() method) where the ListView you will need to populate the data for the ListView. This should not be done on the UI Thread

    // This will contain all the data you need from you model class in an ArrayList
    ArrayList<MyListData> arrayListData = new ArrayList<MyListData>();
    MyListDataAdapter adapter = new MyListDataAdapter(this, arrayListData);

    for (MyListData g : result) {
        adapter.add(g);
    }
    list.setAdapter(adapter);

Also in the activity where the ListView is to be maintained set up some onClick event handlers if you need them: (I find that one of the small advantages of the ListView is that the onClick event is easier it implement than in the RecycleView)

list = (ListView) findViewById(R.id.listview);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
        MyListData data = (MyListData) parent.getItemAtPosition(position);
        data.setIsSelected = true;

        // Update the listview with the changes to your MyListData
        adapter.notifyDataSetChanged();

    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...