如何为每个项目列表视图设置背景颜色,该列表项取决于可变值 [英] How to set background color for each item listview depanding on variable value

查看:82
本文介绍了如何为每个项目列表视图设置背景颜色,该列表项取决于可变值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的问题,但Google没有给我合适的答案.我需要为listview中的每个项目设置setgroundground颜色,该颜色取决于变量值. handle状态项必须是一种颜色,而done必须是另一种颜色.

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.

列表视图适配器

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

订单清单类

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

        }

    });
}
}

推荐答案

如果只需要设置ListView中某一行的颜色,则可以执行以下操作:

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

在您的ListView布局中,"listview_item"为根布局指定一个ID.例如. "rlMainLayout"

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

在您的getView方法中,您需要获取对布局对象的引用.如果它是RelativeLayout,则它将类似于以下内容:

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

现在,您可以像这样将颜色设置为RelativeLayout对象:

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

rlMainLayout.setBackgroundColor(Color.RED);

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

-编辑-

分步示例

(请注意,我是在文本编辑器"程序中完成此操作的,所以可能会有一些错别字.)

您将需要更改自定义适配器类.重要说明:您将要使用模型类(在本例中为MyListData).当您需要维护软件以将模型与视图分开时,它将提供帮助.

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

}

现在,您需要一个模型类来保存数据.我们称它为MyListData(但是您可以随便叫它什么)

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

}

您的自定义ListView布局可能类似于以下内容.请注意,根布局的标识符为rlMainLayout

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>

在您的Activity(例如,在onCreate()方法中)中的ListView,您将需要填充ListView的数据.这应该在用户界面线程上完成

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

还要在要维护ListView的活动中,设置一些onClick事件处理程序(如果需要): (我发现ListView的一个小优点是onClick事件比RecycleView更容易实现)

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

    }
});

这篇关于如何为每个项目列表视图设置背景颜色,该列表项取决于可变值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆