【问题标题】:Android. How to adjust height and width of a custom component using XML attributes?安卓。如何使用 XML 属性调整自定义组件的高度和宽度?
【发布时间】:2011-12-31 04:11:09
【问题描述】:

有没有办法使用 XML 属性调整自定义组件的高度和宽度?

例如,我创建了一个组件及其布局。

这是组件的 XML 布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:text="TextView" />

</LinearLayout>

这里有一个简单的类来扩展这个布局:

public class CustomComponent extends LinearLayout
{
    public CustomComponent(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        LayoutInflater inflater = (LayoutInflater)context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        ViewGroup view = (ViewGroup)inflater.inflate(
            R.layout.custom_component, null);
        addView(view);
    }
}

自定义组件用于某些 Activity 的布局,如下所示:

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

    <view
        class = "com.tests.CustomComponent"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>

该组件旨在被拉伸到屏幕的全尺寸(这就是它的布局参数设置为“fill_parent”的原因),但这永远不会发生。

谁能帮我解决这个问题?

【问题讨论】:

    标签: android xml components height width


    【解决方案1】:

    看到您的CustomComponent 扩展了LinearLayout,您只需将布局直接膨胀到其中(将this 解析为ViewGroup,因为您的CustomComponent 将是持有视图):

    public class CustomComponent extends LinearLayout
    {
        public CustomComponent(Context context, AttributeSet attrs)
        {
            super(context, attrs);
            inflate( context, R.layout.custom_component, this );
        }
    }
    

    如果这不起作用,请尝试仅提供带有上下文的构造函数:

    public class CustomComponent extends LinearLayout
    {
        public CustomComponent(Context context)
        {
            super(context);
            inflate( context, R.layout.custom_component, this );
        }
    }
    

    【讨论】:

    • 第一个解决方案很好,但第二个是不可能的,因为当您在 XML 布局中添加视图时,它会一直搜索构造函数(上下文、属性集)
    • 感谢您的快速回答,让我度过了愉快的一天。第一个解决方案有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 2012-09-13
    • 2023-03-15
    • 1970-01-01
    • 2020-11-13
    • 2019-05-27
    相关资源
    最近更新 更多