【问题标题】:Android include tag not overriding layout attributesAndroid包含标签不覆盖布局属性
【发布时间】:2013-08-06 03:29:52
【问题描述】:

我在将<include> 与<merge> 结合使用时遇到问题。我正在使用最新的 Android SDK (4.3) 在 Eclipse 上进行开发。这是我的示例代码:

test_merge.xml

<merge xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <View
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#FFFF0000" >
    </View>

</merge>

test_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <include layout="@layout/test_merge" 
        android:layout_width="100dp" 
        android:layout_height="100dp"/>

</LinearLayout>

MyActivity.java

public class MyActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_main);
    }
}

问题是我应该在左上角看到一个红色方块,100x100dp。相反,整个屏幕都是红色的。因此,由于某种原因,&lt;include&gt; 中的android:layout_width 和android:layout_height 属性无效。

我已阅读文档,它说为了通过 &lt;include&gt; 标签覆盖属性,我必须覆盖 android:layout_width 和 android:layout_height,我已经这样做了。

我做错了什么?

【问题讨论】:

    标签: android attributes include margin


    【解决方案1】:

    使用merge 时,没有父级可以应用100dps。尝试切换到 FrameLayout 而不是 merge 或(甚至更好)在这种情况下,您可以删除 merge 并让 View 成为根。

    编辑:

    将 test_merge.xml 更改为:

    <View xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#FFFF0000" >
    </View>
    

    【讨论】:

    • 100dp 的宽度和高度不会应用于&lt;View&gt; 吗?据我了解,当编译器看到include 标签时,它会进入布局,复制&lt;merge&gt; 中的所有内容并将其放在&lt;include&gt; 的位置。
    • @user2566395 是的。你理解的没错,但是View里面可以有不止一个merge,所以它不会在那里应用layout_width。
    【解决方案2】:

    尝试在您包含的 layout 中将这些属性设为 0

    <merge xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="0dp"
        android:layout_height="0dp" >
    
        <View
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:background="#FFFF0000" >
        </View>
    
    </merge>
    

    【讨论】:

    • 这不会出错吗?这些值需要dp 或px 等单位。
    • @MaciejGórski 是的,谢谢你赶上这个......赶时间。我已经编辑了我的答案
    • 现在什么都看不见了。 &lt;include&gt; 根本不使用属性。
    猜你喜欢
    • 1970-01-01
    • 2016-07-17
    • 2012-03-11
    • 2012-07-18
    • 1970-01-01
    • 2018-02-22
    • 1970-01-01
    • 2013-03-04
    • 1970-01-01
    相关资源
    最近更新 更多