繁体   English   中英

StateListDrawable在自定义视图中不起作用

[英]StateListDrawable doesn't work in a custom view

我在自定义视图上遇到StateListDrawable的大问题。 我有一个直接从LinearLayout继承的自定义视图,并且在其XML布局中,背景是一个简单的状态列表可绘制对象,可按其当前状态设置启用或禁用该视图的背景。 我不明白的是为什么我打电话

this.SetEnabled(false);

在我的自定义视图中,背景不会改变。

也许我的问题不是很清楚,所以我做了一个简单的例子。 您可以在这里下载。 查看“ ViewCustom.java”文件并找到FIXME标记。

希望可以有人帮帮我。

PS与按钮关联的相同状态列表可绘制有效,但在我的自定义视图上无效。

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>

问题是,您不能仅禁用线性布局。 您需要做的就是禁用其中的所有内容。 这个问题回答了这个问题 ,但归结为两件事之一。

  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. } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM