2017-10-15 4 views
1

onClick없이 ListView의 행을 자동으로 강조 표시해야합니다. 내 앱이하는 일은 식량 만기일이 90 일 미만일 때 특정 식품 항목에 경고 (강조 표시)를하는 것입니다. 솔루션에 대해 Stack Overflow를 검색했지만 모든 주요 기능은 onClick을 사용하여 구현됩니다. 나는 나의 ListView를위한 onClick Highlight를 구현했다. (나는 원했던 것이 아니다.) 식량의 유효 기한이 90 일을 넘었을 때 자동으로 하이라이트를 구현할 수있는 방법이 있는가? 어떤 도움이라도 대단히 감사하겠습니다!onClick을 사용하지 않고 ListView에서 행을 강조 표시하는 방법은 무엇입니까?

내가 하이라이트 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" 
     /> 

내 자바 파일

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

} 

답변

0

은 90 일 다음 원하는 색상을 줄 경우에는 유효 기간 체크를 추가 할 때 어댑터에서이 작업을 수행해야합니다.

0

목록 항목 상태가 각각 listview 인 각 항목의 백그라운드에는 xml selector를 사용해야합니다. drwable/listview_item_bg.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 항목 - -

<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() 방법 - 당신의 listviewlayout_listview_item.xml를 추가

레이아웃 ListView 항목 layout/layout_listview_item.xml의 - 전체 코드는 아래와 같습니다

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

. 
. 
. 
. 
. 

    } 
0

아마도 아이템 개체의 유효 기간을 참조하는 필드가 있습니다 (90 일 미만일 경우), 어댑터의 (뷰보기) 메소드에서 아이템 배열에있는 모든 아이템 객체의 해당 필드를 확인해야합니다. 필드가 90 일 미만에 도달하면 강조 표시 될 수 있도록이 항목에 대한 목록의 배경색을 변경하십시오.

관련 문제