【问题标题】:How to highlight row in ListView without onClick?如何在没有 onClick 的情况下突出显示 ListView 中的行?
【发布时间】:2017-10-15 09:49:47
【问题描述】:

我需要自动突出显示 ListView 中的一行,而不需要 onClick。我的应用程序所做的是在食品到期日低于 90 天时对特定食品发出警报(突出显示)。我已经在 Stack Overflow 上搜索了一个解决方案,但所有的亮点都是使用 onClick 实现的。我已经为我的 ListView 实现了 onClick 突出显示(这不是我想要的),当食品到期日低于 90 天时,有什么方法可以自动实现突出显示?任何帮助将不胜感激!

当我点击产品 Milo 时会出现突出显示,如何让突出显示在 90 天以下过期的食品上自动显示

这是我的 XML 布局

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_above="@+id/AddProduct"
        android:id="@+id/listView2"
        android:layout_centerHorizontal="true"
        android:layout_alignParentTop="true"
        android:choiceMode="multipleChoice"
        android:listSelector="@drawable/Selector"
        />

我的 Java 文件

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_inventory);
    AddProduct = (Button) findViewById(R.id.AddProduct);
    camera = (ImageButton) findViewById(R.id.camera);
    AddProduct.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(Inventory.this, AddProduct.class));
        }
    });
    camera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getApplicationContext(), BarcodeCaptureActivity.class);
            startActivityForResult(intent, BARCODE_READER_REQUEST_CODE);

        }
    });

    mList = (ListView) findViewById(R.id.listView2);
    arrayAdapter = new ItemsAdapter(this, android.R.layout.simple_list_item_1, items);
    mList.setAdapter(arrayAdapter);
    database = FirebaseDatabase.getInstance().getReference("All Barcodes");
    final List<String> keys = new ArrayList<>(); // will contain list of keys corresponding to listview item
    database.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(final DataSnapshot dataSnapshot) {
            arrayAdapter.clear();
            for(final DataSnapshot snapshot : dataSnapshot.getChildren()){
                arrayAdapter.notifyDataSetChanged();

                Calendar c = Calendar.getInstance();
                SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
                String dateNow = df.format(c.getTime());
                String exp = snapshot.child("expiration").getValue().toString();
                String barcode = snapshot.child("barcode").getValue().toString();
                String name = snapshot.child("pname").getValue().toString();
                String q =  snapshot.child("quantity").getValue().toString();

                Date d1 = null;
                Date d2 = null;
                try{
                    d1 = df.parse(exp);
                    d2 = df.parse(dateNow);
                }
                catch(Exception e){
                }

                long diff =  d1.getTime() - d2.getTime();
                long hours = diff/(60*60*1000);
                long days = hours/24;

                if (days<=90){
                    NotificationGenerator.openActivityNotification(getApplicationContext(),barcode, name, days);
                    Log.i( "Item expring in: " , days + " days");
                    Log.i("Item's barcode is " , barcode);



                }
                else{
                    Log.i("Item expring in: " , days + " days");
                }

                String value = (String) snapshot.child("expiration").getValue();

                items eachItem = new items(name,value.toString(),Long.toString(days),q);

                arrayAdapter.add(eachItem);

                keys.add(snapshot.getKey());


            }
            arrayAdapter.notifyDataSetChanged();

            mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {

                    view.setSelected(true);
                    String myKey = keys.get(i);
                    Intent intent  = new Intent(Inventory.this,Edit.class);
                   intent.putExtra("value",myKey);
                   startActivity(intent);
                }
            });
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}

我的 ListView 适配器

public class ItemsAdapter extends ArrayAdapter<items> {
private ArrayList<items> itemObjects;

public ItemsAdapter(Context context, int textViewResourceId, ArrayList<items> itemObjects) {
    super(context, textViewResourceId, itemObjects);
    this.itemObjects = itemObjects;
}

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

    View v = convertView;

    // first check to see if the view is null. if so, we have to inflate it.
    // to inflate it basically means to render, or show, the view.

    if (v == null) {

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

        //inflating the tex views from list_items.xml
        v = inflater.inflate(R.layout.list_items, null);
    }

    /*
     * Recall that the variable position is sent in as an argument to this method.
     * The variable simply refers to the position of the current object in the list. (The ArrayAdapter
     * iterates through the list we sent it)
     *
     * Therefore, i refers to the current Item object.
     */
    items i = itemObjects.get(position);

    //If i is not null
    if (i != null) {

        // obtaining a reference to the TextViews.
        // These TextViews are created in the XML files we defined.
        TextView ProdName = (TextView) v.findViewById(R.id.ProductName);
        TextView ProdNameValue = (TextView) v.findViewById(R.id.ProductNameData);
        TextView ExpiryDate = (TextView) v.findViewById(R.id.ExpiryDate);
        TextView ExpiryDateData = (TextView) v.findViewById(R.id.ExpiryDateData);
        TextView ExpiryIn = (TextView) v.findViewById(R.id.ExpiryIn);
        TextView ExpiryInData = (TextView) v.findViewById(R.id.ExpiryInData);
        TextView BarCode = (TextView) v.findViewById(R.id.BarCode);
        TextView BarCodeData = (TextView) v.findViewById(R.id.BarCodeData);

        // check to see if each individual text view is null.
        // if text view is not null (means containing the reference) , it will assign text/value!
        if (ProdName != null){
            ProdName.setText("Name: ");
        }
        if (ProdNameValue != null){
            ProdNameValue.setText(i.getName());
        }
        if (ExpiryDate != null){
            ExpiryDate.setText("Expiry Date: ");
        }
        if (ExpiryDateData != null){
            ExpiryDateData.setText(i.getValue());
        }
        if (ExpiryIn != null){
            ExpiryIn.setText("Expiry In (Days): ");
        }
        if (ExpiryInData != null){
            ExpiryInData.setText(i.getDays());
        }
        if (BarCode != null){
            BarCode.setText("Quantity: ");
        }
        if (BarCodeData != null){
            BarCodeData.setText(i.getQuantity());
        }
    }

    // the view must be returned to our activity
    return v;

}

【问题讨论】:

    标签: android listview


    【解决方案1】:

    您应该在添加到期日期时在适配器中执行此操作,检查是否超过 90 天,然后提供您想要的颜色。

    【讨论】:

      【解决方案2】:

      可能您的 item 对象有一个引用到期日期的字段(如果达到 90 天以下),因此在您的适配器中的 (get view) 方法中,您需要检查项目数组中每个 item 对象中的该字段,如果这个字段达到 90 天以下,然后更改此项目列表的背景颜色,使其突出显示。

      【讨论】:

        【解决方案3】:

        您应该使用 xml 选择器作为 listview 的每个项目的背景以及列表项状态。完整的代码 sn-p 如下 -

        ListView项目layout/layout_listview_item.xml的布局-

        <?xml version="1.0" encoding="utf-8"?>
        <LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="horizontal"
            android:background="@drawable/listview_item_bg">
                <TextView       android:id="@+id/textForList"
                android:layout_height="fill_parent"
                android:layout_width="wrap_content"
                android:padding="10sp"  />
        .
        .
        .
        </LinearLayout>
        

        listview 项目的背景drwable/listview_item_bg.xml-

            <selector xmlns:android="http://schemas.android.com/apk/res/android">
        
            <item android:state_focused="true">
            <shape>
                <solid android:color="#66FFFFFF" />
            </shape>
        </item>
            <item>
            <shape>
                <solid android:color="#FF666666" />
            </shape>
        </item>
        
        </selector>
        

        然后在适配器的getView() 方法上将layout_listview_item.xml 添加到您的listview -

         @Override
            public View getView(int position,  View convertView, ViewGroup parent) {
        
                View v = convertView;
        
                // first check to see if the view is null. if so, we have to inflate it.
                // to inflate it basically means to render, or show, the view.
        
                if (v == null) {
        
                    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        
                    //inflating the tex views from list_items.xml
                    v = inflater.inflate(R.layout.layout_listview_item, null);
                }
        
        .
        .
        .
        .
        .
        
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-09-24
          • 1970-01-01
          • 2021-01-30
          • 2019-10-19
          • 2020-08-15
          • 2020-01-19
          • 2014-12-23
          • 1970-01-01
          相关资源
          最近更新 更多