2012-12-03 19 views
1

我試圖創建一個通用的自定義組合框庫。從Java代碼更改XML選擇器(不可繪製)

如何更改xml代碼 - > java代碼。

請提示我。

<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:state_enabled="true" android:state_pressed="false"> 
     <shape android:shape="rectangle">    
<padding android:bottom="5dp" android:left="5dp" android:top="5dp" /> 
      <stroke android:width="1px" android:color="@color/textbox_border_color" /> 
      <solid android:color="@color/textbox_nomal_color" /> 
      <corners android:bottomRightRadius="15dp" /> 
     </shape> 
    </item> 
    <item android:state_enabled="true" android:state_pressed="true"> 
     <shape android:shape="rectangle"> 
      <padding android:bottom="5dp" android:left="5dp" android:top="5dp" /> 
      <stroke android:width="1px" android:color="@color/textbox_border_color" /> 
      <solid android:color="@color/textbox_pressed_color" /> 
      <corners android:bottomRightRadius="15dp" />    
     </shape> 
    </item> 
    <item android:state_enabled="false"><shape android:shape="rectangle"> 
      <padding android:bottom="5dp" android:left="5dp" android:top="5dp" /> 
      <stroke android:width="1px" android:color="@color/textbox_border_color" /> 
      <solid android:color="@color/textbox_disable_color" /> 
      <corners android:bottomRightRadius="15dp" /> 
     </shape> 
    </item> 
</selector> 

回答

0

使用StateListDrawable如通過代碼seeting選擇:

StateListDrawable states = new StateListDrawable(); 
states.addState(new int[] {android.R.attr.state_pressed}, 
    getResources().getDrawable(R.drawable.pressed)); 
states.addState(new int[] {android.R.attr.state_focused}, 
    getResources().getDrawable(R.drawable.focused)); 
states.addState(new int[] { }, 
    getResources().getDrawable(R.drawable.normal)); 

imageView.setImageDrawable(states); //YOUR IMAGE HERE 
//AND FOR BUTTON 
button.setBackgroundDrawable(states);//FOR BUTTON 

這可能有助於