同时更改不同密度的多个布局

时间:2015-10-22 10:58:38

标签: android android-layout android-studio android-xml

如果我对同一个视图有三种不同的布局(比方说,一个用于手机,一个用于平板电脑,一个用于平板电脑),我想添加/更改三个共享的属性(比方说, android:background),有没有办法在一个地方添加/更改它,并在其他两个布局中自动更新?有复制粘贴的替代方法吗?

2 个答案:

答案 0 :(得分:1)

不幸的是不是真的。您可以为每组元素设置单独的布局,并使用Toolbar将它们包含在每个后续布局中,然后只更新单个布局将更新所有元素。但这意味着要有很多独立的布局。一个很好的例子是使用单独的<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar" style="@style/Toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" /> 布局,如下所示:

工具栏布局

Toolbar

然后在您要使用的所有布局中使用此行<include layout="@layout/toolbar" />

stack build

此技术可应用于您喜欢的任何内容,并允许您将来仅编辑每个单独的布局一次,并在您使用它的任何地方应用它。您还可以在include或代码下编辑这些布局中的尺寸。

实现你想要的唯一其他方法是在代码中明确地处理它,但我不建议这样做。

答案 1 :(得分:1)

您可以为使用final ForegroundColorSpan whiteSpan = new ForegroundColorSpan(ContextCompat.getColor(this, android.R.color.white)); SpannableStringBuilder snackbarText = new SpannableStringBuilder("Hello, I'm white!"); snackbarText.setSpan(whiteSpan, 0, snackbarText.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); Snackbar.make(view, snackbarText, Snackbar.LENGTH_LONG) .show(); 属性的窗口小部件(例如TextView或LinearLayout)应用style,并确定该样式中的background属性。 更改background中的background属性会影响此样式之前应用的所有小部件。

http://developer.android.com/guide/topics/ui/themes.html