[英]How can I use the negative of an Android attribute in XML?
我有一个简单的相对布局,其中包含一个图标的ImageView
和一个标题的TextView
:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/Test.NavBar.Heading"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal">
<ImageView
style="@style/Test.NavBar.Heading.Icon"
android:id="@+id/test_logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"/>
<TextView
style="@style/Test.NavBar.Heading.Text.Large"
android:id="@+id/test_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/test_logo"
android:layout_toEndOf="@+id/test_logo"
android:layout_alignTop="@id/test_logo"
android:layout_alignBottom="@id/test_logo"
android:gravity="center_vertical"
android:text="My Title"/>
</RelativeLayout>
这嵌入在另一个视图中,该视图使我的视图水平居中。 一切都很好,除了我需要将布局置于TextView
而不是RelativeLayout
。
我唯一可以访问的是一个属性,该属性为我提供了ImageView
项目的宽度,即iconWidth
。 通常,您可以使用margin属性偏移布局,例如,在上面我可以添加
android:layout_marginLeft="?attr/iconWidth"
但这会将布局推向右侧而不是左侧。 相反,我需要做类似的事情:
android:layout_marginLeft="-?attr/iconWidth"
当然不是有效的语法。
我必须在单个布局中执行此操作,并且必须在XML中执行此操作,并且不能要求添加其他属性。 鉴于这些限制,如何根据需要偏移RelativeLayout
的内容?
经过各种尝试找到最佳解决方案之后,我发现最好的方法是在文本后简单添加另一个图标,但使其不可见:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/Test.NavBar.Heading"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal">
<ImageView
style="@style/Test.NavBar.Heading.Icon"
android:id="@+id/test_logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"/>
<TextView
style="@style/Test.NavBar.Heading.Text.Large"
android:id="@+id/test_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/test_logo"
android:layout_toEndOf="@+id/test_logo"
android:layout_alignTop="@id/test_logo"
android:layout_alignBottom="@id/test_logo"
android:gravity="center_vertical"
android:text="My Title"/>
<ImageView
style="@style/Test.NavBar.Heading.Icon"
android:id="@+id/test_blank"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/test_title"
android:layout_toEndOf="@+id/test_title"
android:src="@drawable/ic_launcher"
android:visibility="invisible"/>
</RelativeLayout>
有了这个额外但不可见的图标, TextView
现在位于RelativeLayout
的中间,这解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.