自定义控制中的通胀布局 - 如何?

kat*_*tit 14 android android-layout

我已经知道如何在这里创建自定义控件: Android界面 - 需要有关使用哪些小部件的建议

如何创建SAME,但是在XML中创建控件的布局,只是在代码中膨胀它?不像在这个例子中我必须手动创建每个控件.

我用作基础的LinearLayout的第一个问题是不支持setView()命令.我应该延伸其他东西吗?

编辑:我发现了这个:http: //developer.android.com/guide/topics/ui/custom-components.html 和这个:http: //developer.android.com/resources/samples/ApiDemos/src/com/例如/机器人的/ apis /视图/ List4.html

好像我需要复合控制.我只需要一些代码.如何从XML中扩展控件的内容?BOth文章和样本说我可以,但如何?

big*_*nes 23

你必须使用这样的布局:

<?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>
Run Code Online (Sandbox Code Playgroud)

在哪里<merge>意味着"将我内心的一切都放入父母我将被夸大".

然后在代码中:

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);
    }
    // ......
}
Run Code Online (Sandbox Code Playgroud)

此时,您可以使用复合控件,就像它是LinearLayout一样,因此您必须在外部布局中指定,例如,如果您希望它是垂直的,或者您可以在构造函数中将其设置为默认值.