【问题标题】:Inflating layout in custom control - how?在自定义控件中膨胀布局 - 如何?
【发布时间】:2011-05-05 17:07:01
【问题描述】:

我有关于如何在这里创建自定义控件的想法: Android interface - need suggestions on what widgets to use

如何制作相同的但在 XML 中创建控件的布局并在代码中膨胀它?不像在这个例子中我必须手动创建每个控件。

我的第一个问题是用作基础的 LinearLayout 不支持 setView() 命令。我应该扩展其他内容吗?

编辑:我发现 这: http://developer.android.com/guide/topics/ui/custom-components.html 还有这个: http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List4.html

看来我需要复合控制。我只需要一点代码。如何从 XML 扩充控件的内容?文章和示例都说我可以,但如何?

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    你必须使用这样的布局:

    <?xml version="1.0" encoding="utf-8"?>
    <merge xmlns:android="http://schemas.android.com/apk/res/android">
      <View android:layout_width="fill_parent"
      android:layout_height="0px"
      android:layout_weight="1"
      android:background="#0F0"/>
      <View android:layout_width="fill_parent"
      android:layout_height="0px"
      android:layout_weight="1"
      android:background="#0FF"/>
    </merge>
    

    &lt;merge&gt; 的意思是“将我体内的所有东西都放入我将被充气到的父级中”。

    然后在代码中:

    public class CControl extends LinearLayout {
    
        public CControl(Context context) {
            this(context, null);
        }
    
        public CControl(Context context, AttributeSet attrs) {
            super(context, attrs);
    
            LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    
            inflater.inflate(R.layout.tryout, this);
        }
        // ......
    }
    

    此时,您可以像使用 LinearLayout 一样使用复合控件,因此您必须在外部布局中指定,例如,如果您希望它是垂直的,或者您可以在构造函数。

    【讨论】:

    • 这样更好。如果我不想以 LinearLayout 为基础怎么办?我应该扩展视图吗?我正在为我的复合控件寻找最轻的容器。无论如何,我都会将它插入到带有 LinearLayout 的 Activity 中,所以我不需要另一个嵌套级别。
    • @katit:如果我要创建一个全新的视图,我会扩展 View,在 onDraw() 中绘制所有内容。您需要复合控件的布局,因为它必须以某种方式成为可重用的统一体,并且选择主要取决于您希望如何布局子视图。我不会太担心优化,除非你显示数百个(无论如何这都会很糟糕)。
    • 知道了。我不会表现出饥饿感。通常是 2-3 或者 4。我喜欢从头开始学习最好的方法。但是这里似乎使用布局就可以了。
    猜你喜欢
    • 1970-01-01
    • 2012-06-17
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    相关资源
    最近更新 更多