android中layout的作用,Android layout文件中 '?' 的作用

在Android layout文件中,属性引用资源一般使用@,例如

android:textColor="@color/white"

但在一些系统文件中我们也可以看到有这样的写法

android:textColor="?android:color/textColor"

我们知道@是引用已经定义好的资源,如@color/white、@android:color/white,那 ‘?’ 呢?下面是文档中的解释

Referencing style attributes

A style attribute resource allows you to reference the value of an attribute in the currently-applied theme. Referencing a style attribute allows you to customize the look of UI elements by styling them to match standard variations supplied by the current theme, instead of supplying a hard-coded value. Referencing a style attribute essentially says, “use the style that is defined by this attribute, in the current theme.”

To reference a style attribute, the name syntax is almost identical to the normal resource format, but instead of the at-symbol (@), use a question-mark (?), and the resource type portion is optional. For instance:

?[:][/]

For example, here’s how you can reference an attribute to set the text color to match the “primary” text color of the system theme:

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:textColor="?android:textColorSecondary"

android:text="@string/hello_world" />

也就是说 ‘?’ 用来引用主题中的资源值,以显示当前主题的风格类型。

一般设置主题有几个方法,

在AndroidManifest中,application标签里,这样会将主题应用到application下面所有的activity中

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

...

application>

在AndroidManifest.xml中,activity标签里,这样只给该activity设置主题

android:theme="@style/AppTheme"

android:label="@string/app_name" >

intent-filter>

activity>

在Activity中代码设置,需要在setContent()方法前调用

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setTheme(R.style.AppTheme);

setContentView(R.layout.activity_main);

}

例子:

主题style/AppTheme

style>

9d8c217772994efd9515ffc6c75d2472.jpg

主题style/AppTheme.Another

0f02cf26393e4413a3e791f3aa7588ed.jpg

可以看到主题将所有view的background都设置为#ffff8800。原因是android:background是View的一个通用属性,如果View自身没有再去设定这个值的话,就会使用当前主题下的值。

如果我们只想改变某一个view的背景颜色怎么办?这里就可以使用?这个符号。首先在attrs.xml中定义一个标签

attr>

resources>

在主题中设置这个标签的值

在布局中引用这个主题值

...

>

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerInParent="true"

android:background="?attr/customBackground"

android:textSize="30sp"/>

RelativeLayout>

结果如下

e00ba2292f544b038623266eee49eb2c.jpg

如果我们再定义一些其他主题,如:

那么只需要设置相应的主题就可以改变view的属性值。

还可以再主题里设置更多的标签,这样就可以完成像夜间主题这种背景、字体颜色等一系列属性同时改变。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值