[英]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.