Include a TextView and override the text
我有一个TextView用作菜单页面的标题:
1 2 3 4 5 6 7 8 | <TextView android:id="@+id/menuTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Menu" android:textColor="@color/white" android:textSize="25sp" android:textStyle="bold" /> |
现在我需要在我的应用程序的每个子菜单上使用具有相同颜色,大小和样式的TextView。与其将整个TextView粘贴复制到每个布局,而没有更改每个文本,我认为我会使用TextView进行一个布局,并将其包括在每个子菜单视图中,仅覆盖文本。
我的代码如下:
/layout/menutextview.xml:
1 2 3 4 5 6 7 8 9 | <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/menuTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/default" android:textColor="@color/white" android:textSize="25sp" android:textStyle="bold" /> |
每个布局xml文件中的include尝试覆盖text属性:
1 2 3 | <include layout="@layout/menutextview" android:text="@string/menu" /> <include layout="@layout/menutextview" android:text="@string/settings" /> |
但是默认文本随处显示。任何人都有ID吗?可能是什么问题?
关于,
Mattias
Include不能用于"替代"子级属性。它不知道您将包括哪种布局,它只会将其充气并将其添加到当前布局中。
要动态更改文本,需要在代码中进行。
1 2 3 4 5 | final TextView textView1 = (TextView) findViewById(R.id.menuTextView); textView1.setText(R.string.menu); final TextView textView2 = (TextView) findViewById(R.id.settingsTextView); textView2.setText(R.string.settings); |
尝试使用样式,并让TextView实现该样式。这将使维护视图的一致性更加容易。
您可以使用DataBinding实现此目的。首先,在子布局中定义一个变量:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?xml version="1.0" encoding="utf-8"?> <layout xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" xmlns:android="http://schemas.android.com/apk/res/android"> <data> <variable name="buttonText" type="String" /> </data> <android.support.v7.widget.AppCompatTextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{buttonText}"/> </layout> |
然后将其设置在包含它的另一个布局文件中:
1 2 3 4 5 | <!-- .... other views --> <include layout="@layout/inc_icon_button" bind:buttonText="@{`Put your String here`}" /> <!-- .... other views --> |
最好的情况是,您在父级布局中还会有一个变量,以便仅转发绑定。
您可以使用以下解决方案:
我从这一方面使用了信息。