2012-12-03 18 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 

这可能有助于