2013-07-02 4 views
0

Я борюсь с этим уже с часами, и я не могу найти решение, надеюсь, кто-то может мне помочь.
У меня есть ListView с настраиваемым адаптером, расширяющим BaseAdapter, и каждый элемент списка расширяет LinearLayout, содержащий только TextView. Я начал в основном с How to add a custom button state.
Это файл макета list_item.xml элемента списка:Android: пользовательское состояние выбора никогда не получает «true»

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res/com.example.mypackage" 
    android:id="@+id/newItem" 
    app:state_playing="true" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="@drawable/item_selector" 
    android:orientation="horizontal" > 

    <TextView 
     android:id="@+id/textview" 
     style="@style/Text_View_Style_White" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:duplicateParentState="true" 
     android:ellipsize="marquee" 
     android:focusableInTouchMode="true" 
     android:marqueeRepeatLimit="marquee_forever" 
     android:padding="3dp" 
     android:scrollHorizontally="true" 
     android:singleLine="true" 
     android:textColor="@drawable/item_text_selector" /> 
</LinearLayout> 

Вот соответствующий код BaseAdapter:

class AlbumListAdapter extends BaseAdapter implements Checkable { 

    private Context mContext; 

    public AlbumListAdapter(Context context) { 
     mContext = context; 
    } 

    @Override 
    public int getCount() { 

     return listSize; // is a variable 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     AlbumViewHolder albumHolder = null; 
     if (convertView == null) { 
      // Inflate the layout 
      LayoutInflater li = getActivity().getLayoutInflater(); 
      convertView = li.inflate(R.layout.list_item, null); 
      albumHolder = new AlbumViewHolder(mContext, null); 
      albumHolder.albumTitle = (TextView) convertView 
        .findViewById(R.id.textview); 

      convertView.setTag(albumHolder); 
     } else { 
      albumHolder = (AlbumViewHolder) convertView.getTag(); 
     } 

     albumHolder.albumTitle.setText("Some text in the TextView"); 
     albumHolder.albumTitle.setSelected(true); 

     if (myBooleanCondition) 
     { 
      albumHolder.setPlaying(true); 
      albumHolder.refreshDrawableState(); 

      for (int i = 0; i < albumHolder.getDrawableState().length; i++) { 
       if (albumHolder.getDrawableState()[i] != 0) 
        System.out.println(TAG + " State i = " 
        + i + " -> " + getResources().getResourceEntryName(albumHolder.getDrawableState()[i])); 
      } 
     } 

     return convertView; 
    } 
} 

и здесь класс элемента списка расширения LinearLayout:

static class AlbumViewHolder extends LinearLayout { 

     private static final int[] STATE_PLAYING_SET = { R.attr.state_playing }; 
     private boolean mIsPlaying = false; 
     TextView albumTitle; 

     public AlbumViewHolder(Context context, AttributeSet attrs) { 
      super(context, attrs); 
     } 

     public void setPlaying(boolean isPlaying) { 
      mIsPlaying = isPlaying; 
     } 

     @Override 
     protected int[] onCreateDrawableState(int extraSpace) { 
      final int[] drawableState = super 
        .onCreateDrawableState(extraSpace + 1); 
      if (mIsPlaying) { 
       System.out.println(TAG 
         + " - onCreateDrawableState() -> mIsPlaying = " 
         + mIsPlaying); 
       mergeDrawableStates(drawableState, STATE_PLAYING_SET); 
      } 
      return drawableState; 
     } 
    } 

Вот attrs.xml

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <declare-styleable name="music"> 
     <attr name="state_playing" format="boolean" /> 
     <attr name="playing" format="boolean" /> 
    </declare-styleable> 
</resources> 

и здесь 2 Селекторы пытаются использовать состояние селектора state_playing, один для фона в LinearLayout каждого элемента (item_selector.xml):

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res/com.example.mypackage"> 

    <item android:drawable="@color/blue_fluo3" app:state_playing="true"/> 
    <item android:drawable="@color/orange_fluo" android:state_pressed="true" app:state_playing="false"/> 
    <item android:drawable="@color/orange_fluo" android:state_activated="true" app:state_playing="false"/> 
    <item android:drawable="@android:color/transparent" app:state_playing="false"/> 

</selector> 

и один для TextColor из TextView (item_text_selector .xml):

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res/com.example.mypackage"> 

    <item app:state_playing="true" android:color="@color/orange_fluo"/> 
    <item android:state_pressed="true" app:state_playing="false" android:color="@color/black"/> 
    <item android:state_activated="true" app:state_playing="false" android:color="@color/black"/> 
    <item app:state_playing="false" android:color="@android:color/white"/> 

</selector> 

результат одинаков для и другое: state_playing, кажется, работает, но только в состояние «ложь», потому что если я добавить строку в начале государственного списка селектора с <item app:state_playing="false" android:color="@color/yellow"/> для текстовый селектор и <item android:drawable="@color/red" app:state_playing="false"/> для фонового селектора все работает как ожидалось, я вижу LinearLayout с красным фоном и текстом с желтым текстом!
Я действительно не знаю, что попробовать больше ... (даже если я установить свойство по умолчанию к объектам (app:state_playing="true") в макете XML это не работает!

Любая помощь, подсказка или опыт обмен чрезвычайно ценится!

+0

не знаю об этом ?! При необходимости я могу предоставить дополнительную информацию! – Andre

ответ

0

Это выглядит хорошо для меня, но я предлагаю установки duplicateParentState в макете контейнера, как показано ниже. у меня есть смутное воспоминание о возникновении проблем вдоль этих линий самих ...

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:app="http://schemas.android.com/apk/res/com.example.mypackage" 
android:id="@+id/newItem" 
android:duplicateParentState="true" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:background="@drawable/item_selector" 
android:orientation="horizontal" > 

<TextView 
    android:id="@+id/textview" 
    style="@style/Text_View_Style_White" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:duplicateParentState="true" 
    android:ellipsize="marquee" 
    android:focusableInTouchMode="true" 
    android:marqueeRepeatLimit="marquee_forever" 
    android:padding="3dp" 
    android:scrollHorizontally="true" 
    android:singleLine="true" 
    android:textColor="@drawable/item_text_selector" /> 

 Смежные вопросы

  • Нет связанных вопросов^_^