ListView selected item drawable

前端 未结 3 1498
面向向阳花
面向向阳花 2020-12-21 06:55

I have a problem in my ListView. I want to change the background of selected item when I select it to a custom drawable that I have, but it doesn\'t work.

I want t

相关标签:
3条回答
  • 2020-12-21 07:34
    dynamicListView.setOnItemClickListener(new OnItemClickListener() {
    
       @Override
       public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
           //arg1 will give you that view   
           arg1.setBackgroundColor(Color.BLUE); 
        }
    });
    
    0 讨论(0)
  • 2020-12-21 07:37

    In touch mode there is no selected or focused state.

    However, you can have a checked state (even without a checkbox) and use that to change properties upon "selection". In your java code where you set up to display your list add this line after you define the listview:

    getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    

    Then in your state list XML change this:

    android:state_selected="true"
    

    to this:

    android:state_activated="true"
    

    So now you should have:

    <selector xmlns:android="http://schemas.android.com/apk/res/android"> 
        <item android:state_activated="true"  
            android:drawable="@drawable/selected_item"/> 
        <item android:drawable="@android:color/transparent" /> 
    </selector> 
    

    And finally, set the background for your row view to point to your selector file:

    <TextView xmlns:android="http://schemas.android.com/apk/res/android" 
        android:id="@+id/txt_category_row"  
        android:gravity="center" 
        android:layout_width="match_parent"  
        android:textColor="@color/BLACK" 
        android:layout_height="55dp"  
        android:padding="10dp" 
        android:text="@string/hello"  
        android:layout_marginTop="5dp" 
        android:textAppearance="?android:attr/textAppearanceLarge" 
        android:background="@drawable/item_selector" /> 
    

    You didn't give a name for your state list XML so I just used "item_selector". You should replace that with whatever the name of that file actually is.

    0 讨论(0)
  • 2020-12-21 07:37

    You should use CheckableFrameLayout as list item view. You can find it here - CheckableFrameLayout

    You can see there, that when you click the list item, it changes background drawable to anything you want.

    0 讨论(0)
提交回复
热议问题