2012-11-24 35 views
1

我在自定义视图上遇到StateListDrawable的大问题。 我有一个直接从LinearLayout继承的自定义视图,并且在它的XML布局中,背景是一个简单的状态列表drawable,可以按照当前状态的顺序启用或禁用视图的背景。我不明白是为什么,如果我在我的自定义视图调用StateListDrawable不能在自定义视图中工作

this.SetEnabled(false); 

,背景不会改变。

也许我的问题不是很清楚,所以我做了一个简单的例子。 你可以下载它here。 看看“ViewCustom.java”文件并找到FIXME标签。

希望有人能帮助我。

P.S. 与按钮关联的相同状态列表可以工作,但在我的自定义视图中不可以。

ViewCustom.java

public class ViewCustom extends LinearLayout { 

public ViewCustom(Context context, AttributeSet attrs) { 
    super(context, attrs); 

    //Inflate layout 
    final LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    inflater.inflate(R.layout.view_custom, this); 


    /**FIXME: Try to set "enabled" to false in order to get the 
    * "panel_disabled" background, but it doesn't work. 
    */ 
    this.setEnabled(false); 
} 

}

View.custom.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="@drawable/sld_panel" 
    android:orientation="vertical" > 
</LinearLayout> 

sld_panel.xml

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:drawable="@drawable/panel_disabled" android:state_enabled="false"/> 
    <item android:drawable="@drawable/panel_enabled" android:state_enabled="true"/> 
</selector> 
+0

请注明代码在你的问题的例子。 – PearsonArtPhoto

+0

@PearsonArtPhoto - 我按照要求附上了代码。 – GiveEmTheBoot

回答

1

的问题是,你无法禁用只是一个线性布局。你需要做的是禁用它的一切。 This question答案,但它归结为两件事之一。

  1. 您可以通过setVisibility(View.GONE)使布局消失。
  2. 你可以像这样通过查看每个项目迭代,由东西:

    for (int i = 0; i < myLayout.getCount(); i++){ 
        View view = getChildAt(i); 
        view.setEnabled(false); // Or whatever you want to do with the view. 
    } 
    
+1

是的,它非常简单!我试图循环使用LinearLayout的子集合并禁用其中的所有项目。它工作得很好......谢谢! – GiveEmTheBoot

相关问题