Android的资源引用(3)(Layout、Menu、Style、Them、Attribute、assets)

本文详细介绍了Android中的资源管理,包括Layout、Menu、Style和Theme的使用方法,以及属性Attribute和原始资源Assets的处理方式。文章通过示例展示了如何在XML文件和Java代码中引用这些资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、Layout资源时放在/res/layout/目录下面,layout资源下面的根元素通常为布局管理器,在每个布局管理器中定义各种的view.

二、使用菜单menu资源,资源时放在/res/menu/目录下面,资源的根元素通常为<menu ...../>元素,其中menu的用法在,另一片有介绍menu的一些用法

三、样式Style,该资源存放在/res/values/目录下面,样式资源的根元素通常为<resources......./>,该元素中可以包含多个<style....../>子元素,每一个<style.../>定义一个样式。

 

<style...../>元素指定如下的两个属性。

name:样式的名称

parent:样式继承父样式,该样式继承父样式的全部定义,也可以覆盖父样式的指定格式

 

<style...../>包含多个<item..../>子元素。

如下:

<resources>
  <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="DefaultFontStyle">
        <item name="android:textSize">29sp</item>
        <item name="android:textColor">#101010</item>
    </style>

    <style name="DefaultBackgroud" parent="DefaultFontStyle">
        <item name="android:background">#3cf968</item>
    </style>
    <style name="DefaultStyle" parent="@style/DefaultBackgroud">
    </style>
    <style name="TextViewFontStyle">
        <item name="android:textSize">30sp</item>
    </style>

    <style name="ButtonDefault">
        <item name="android:background">@drawable/pzb</item>
        <item name="android:focusable">true</item>
        <item name="android:clickable">true</item>
        <item name="android:layout_margin">20dp</item>
    </style>

    <style name="EditTextDefault">
        <item name="android:background">@drawable/ps</item>
        <item name="android:textColor">#ec7272</item>
        <item name="android:layout_marginLeft">10dp</item>
        <item name="android:layout_marginRight">10dp</item>
    </style>

    <style name="ButtonChange">
        <item name="android:background">@drawable/button_selector</item>
        <item name="android:layout_margin">20dp</item>
    </style>

    <style name="Button_gradient">
        <item name="android:textSize">20sp</item>
        <item name="android:background">@drawable/button_selector_gradient</item>
    </style>
</resources>

在布局文件中可已使用

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.asus.styletheme.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="测试andoid的style和theme"
        android:id="@+id/test_style"
        style="@style/TextViewFontStyle"/>
    <Button
        android:layout_width="30dp"
        android:layout_height="20dp"
        android:id="@+id/pz"
        style="@style/ButtonDefault"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="37dp"
        android:id="@+id/edit_test"
        style="@style/EditTextDefault"/>
    <Button
        android:layout_width="50dp"
        android:layout_height="50dp"
        style="@style/ButtonChange"
        android:id="@+id/button_test"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button_gradient"
        android:text="test"
        style="@style/Button_gradient"/>
</LinearLayout>

效果图

 

 

四、主题资源使用,主题资源通常也放在/res/values/目录下面,主题资源的xml文件同样也是以<resource..../>作为根元素,同样也是使用<style..../>元素来定义主题样式。

主题和样式的区别:

1、主题不能作用于单个的view组件上面,主题应该是对整个应用中的所有activity起作用,或者对指定的activity起作用。

2、主题定义的格式应该是改变外观的格式,比如:窗口标题,窗口边框

 

如:

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

使用:

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <service android:name=".service.MyService"></service>
    <service android:name=".service.MyService1"></service>
    <service android:name=".service.ChangeService"></service>

    <receiver android:name=".SmsReceiver.SmsReceiver">
        <intent-filter><action android:name="android.provider.Telephony.SMS_RECEIVED"/>
        </intent-filter>
    </receiver>


    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

五、属性attribute资源的使用:资源也是存放在/res/values目录下面,根元素也是<resource..../>

包含两个属性:

1、attr子元素:定义一个属性

2、declare-styleable子元素,内一个styleable对象就是一组attr属性组合:

 

 

七、assets资源

       除了上面介绍的各种XML文件、图片文件之外,Android应用可能还需要用到大量其他类型的资源,比如声音资源等。实际上,声音对于Android应用非常重要,选择合适的音效可以让Android应用增色不少。类似于声音文件及其他各种类型的文件,只要Android没有为之提供专门的支持,这种资源都被称为原始资源。Android 的原始资源可以放在如下两个地方。
  1、位于/res/raw/目录下,Android SDK会处理该目录下的原始资源,Android SDK会在R清单类中为该目录下的资源生成一个索引项。
  2、位于/assets/目录下,该目录下的资源是更彻底的原始资源。Android 应用需要通过AssetManager来管理该目录下的原始资源。


  Android SDK会为位于/res/raw/目录下的资源在R清单类中生成一个索引项,接下来在XML文件中可通过如下语法格式来访问它:
  @[<package_ name>: ]raw/file_ name
  在Java代码中则按如下语法格式来访问:
  [<package_ name>.]R.raw. <file_ name>

 

通过上面的索引项,Androiad 应用就可以非常方便地访问/raw目录下的原始资源了。至于获取原始资源之后如何处理,则完全取决于实际项目的需要。AssetManager是一个 专门管理assets目录下原始资源的管理器类,AssetManager提供了如
下两个常用方法来访问Assets资源。
1、InputStream open(String fileName): 根据文件名来获取原始资源对应的输入流。
2、AssetFileDescriptor openFd(String fileName): 根据文件名来获取原始资源对应的AssetFileDescriptor。AssetFileDescriptor 代表了一项原始资源的描述,应用程序可通过AssetFileDescriptor来获取原始资源。

 

实例:

创建raw和assets文件,分别在其中添加两个.mp3的文件,实现音乐播放.

package com.example.asus.summary2;

import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import java.io.IOException;

/**
 * Created by asus on 2018/7/28.
 */

public class AssetsActivity extends AppCompatActivity implements View.OnClickListener{

    private MediaPlayer mediaPlayer1;
    private MediaPlayer mediaPlayer2;
    protected void onCreate(Bundle saveInstanceState) {
        super.onCreate(saveInstanceState);
        setContentView(R.layout.ass_activity);
        Button raw_m=findViewById(R.id.raw_m);
        Button assets_m=findViewById(R.id.assets_m);
        raw_m.setOnClickListener(this);
        assets_m.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.assets_m:{
                AssetManager manager=getAssets();
                try {
                    AssetFileDescriptor descriptor=manager.openFd("ass.mp3");
                    mediaPlayer2=new MediaPlayer();
                    mediaPlayer2.setDataSource(descriptor.getFileDescriptor());
                    mediaPlayer2.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                mediaPlayer2.start();
                break;
            }
            case R.id.raw_m:{
                mediaPlayer1=MediaPlayer.create(this,R.raw.ra);
                try {
                    mediaPlayer1.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                mediaPlayer1.start();
                break;
            }
            default:
                break;
        }
    }
}

 

<think>好的,用户遇到了Android布局中layout_width属性报错的问题,需要找到解决方案。首先,我需要回忆常见的导致这个错误的原因。根据经验,这种错误通常XML布局文件中的属性使用不当有关。比如,可能在错误的布局管理器中使用不支持的属性,或者在设置属性时格式错误。 接下来,我要检查用户提供的引用内容,看是否有相关线索。引用[1]提到用户无法设计Android表单,并显示Android 4.4版本的问题,可能涉及到SDK版本或工具的问题。引用[2]讨论的是Auto Layout中preferredMaxLayoutWidth的设置,这可能与布局计算有关,但用户的问题是关于layout_width的错误。引用[3]是关于重建错误的计算,可能不太相关,暂时不考虑。 用户的问题“layout_width not allowed error”通常出现在XML布局中,当在某个视图组件中错误地使用了android:layout_width属性。可能的原因包括: 1. 在根布局中使用了错误的属性,比如在FrameLayout的子元素中错误地使用了layout_width,但实际上可能应该用其他属性,但这种情况比较少见。 2. 可能用户将属性写错了地方,例如在应该使用android:width的地方错误地用了android:layout_width,比如在Shape或自定义View中。 3. 另一个常见情况是在使用ConstraintLayout时,子视图未正确添加约束,导致layout_width不被允许,但通常错误提示不同。 4. 还有一种可能是用户在错误的标签内使用了该属性,比如在<shape>或<selector>等非View组件中错误添加了layout_width属性。 根据引用[2],提到了在布局过程中动态设置preferredMaxLayoutWidth,这可能涉及到代码中动态调整布局宽度,但用户的问题是关于XML中的错误,所以可能更多需要检查XML结构。 解决方案步骤可能包括: - 检查XML布局文件,确认是否有拼写错误,比如android:layout_width是否正确拼写。 - 确保在支持layout_width的View组件中使用该属性,例如TextView、Button等,而不是在不受支持的组件中。 - 检查父容器的类型,比如在LinearLayout或RelativeLayout中,子View必须指定layout_widthlayout_height,否则会报错。 - 如果用户在使用自定义View,可能需要确认是否在自定义属性中错误地使用了系统属性。 - 确保SDK工具构建工具是最新的,避免因版本问题导致的解析错误,如引用[1]中提到的SDK问题,可能需要更新或重新安装SDK。 另外,查看错误的具体提示信息,如果是“attribute layout_width not allowed here”,通常意味着当前标签不支持该属性,比如在<item>标签内错误添加了layout_width。例如,在定义样式或选择器时,可能会错误地在<item>中使用布局属性,而正确的做法是在样式中为特定View指定属性。 例如,在样式文件中: <style name="MyStyle"> <item name="android:layout_width">match_parent</item> <!-- 正确 --> </style> 但如果在一个非View的标签中使用,比如在<shape>标签中: <shape> <item android:layout_width="10dp"/> <!-- 错误 --> </shape> 这会导致错误,因为<shape>标签不支持layout_width属性。 因此,用户需要检查报错位置的标签类型,确认是否支持该属性。如果不支持,应改用其他合适的属性,如android:width或android:height,或者调整布局结构。 总结步骤: 1. 检查XML中的标签是否正确,是否在支持layout_width的View中使用。 2. 确认父容器是否需要子View指定layout_widthlayout_height。 3. 确保没有在非View组件(如<shape>、<selector>)中使用布局属性。 4. 更新Android SDK构建工具到最新版本,避免兼容性问题。 5. 清理并重建项目,有时缓存可能导致错误无法正确解析。 如果用户按照以上步骤检查,应该能定位并解决问题。另外,提供示例代码帮助用户对比正确错误的写法会更有帮助,比如展示正确的布局文件结构,以及常见的错误案例。</think>### 解决Android布局中`layout_width`属性报错的方法 在Android开发中,`layout_width`属性报错通常是由于XML布局文件中的属性使用不当或环境配置问题引起的。以下是逐步排查解决问题的步骤: --- #### **1. 检查XML属性拼写作用域** - **错误示例**:在非View组件(如`<shape>`、`<selector>`)中使用`android:layout_width`,系统会提示属性不被允许[^2]。 ```xml <!-- 错误:在<shape>中使用layout_width --> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <item android:layout_width="10dp"/> <!-- 此处报错 --> </shape> ``` - **正确写法**:在View组件(如`<TextView>`、`<LinearLayout>`)中使用该属性: ```xml <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Hello World"/> ``` --- #### **2. 确保父布局的约束条件** - 如果父容器是`LinearLayout`、`RelativeLayout`或`ConstraintLayout`,子View**必须**指定`layout_width``layout_height`,否则会报错。 ```xml <!-- 正确:子View明确声明宽高 --> <LinearLayout> <Button android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout> ``` --- #### **3. 避免在代码中动态设置属性时的冲突** - 如果在代码中动态修改布局属性(如通过`setLayoutParams`),需确保与XML中的属性不冲突。例如: ```java // Java代码中设置宽度 View view = findViewById(R.id.my_view); ViewGroup.LayoutParams params = view.getLayoutParams(); params.width = ViewGroup.LayoutParams.MATCH_PARENT; view.setLayoutParams(params); ``` --- #### **4. 更新SDK构建工具** - 引用[1]提到SDK版本问题可能导致布局编辑器异常。检查并更新以下内容: 1. 打开Android Studio的 **SDK Manager**。 2. 确认已安装最新版本的**Android SDK Build-Tools****Platform Tools**。 3. 在项目的`build.gradle`中同步依赖版本: ```groovy android { compileSdkVersion 34 buildToolsVersion "34.0.0" } ``` --- #### **5. 清理项目缓存** - 缓存可能导致布局解析错误。尝试以下操作: 1. 点击菜单栏的 **File > Invalidate Caches / Restart**。 2. 选择 **Invalidate and Restart**。 3. 重新构建项目。 --- #### **6. 检查自定义View的属性** - 如果使用了自定义View,确保未在XML中错误混用系统属性。例如: ```xml <!-- 自定义View应使用自定义命名空间 --> <com.example.MyCustomView xmlns:app="http://schemas.android.com/apk/res-auto" app:customWidth="100dp" <!-- 正确 --> android:layout_width="match_parent"/> <!-- 正确 --> ``` --- ### 示例对比 - **错误案例**:在`<item>`标签中误用`layout_width` ```xml <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:layout_width="50dp"> <!-- 报错 --> </selector> ``` - **正确修复**:改用`android:width` ```xml <shape xmlns:android="http://schemas.android.com/apk/res/android"> <size android:width="50dp" android:height="50dp"/> <!-- 正确 --> </shape> ``` --- ### 相关问题 1. 如何解决Android Studio布局编辑器无法预览的问题? 2. `ConstraintLayout`中子View未设置约束会导致什么错误? 3. Android XML中`android:width``android:layout_width`有什么区别?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值