当前位置:   article > 正文

深入分析 Android Activity (八)

深入分析 Android Activity (八)

深入分析 Android Activity (八)

1. Activity 的资源管理

在 Android 应用开发中,合理的资源管理可以提高应用的效率和用户体验。资源管理涉及到布局文件、字符串、图片、颜色等各种资源的使用和管理。

1.1 使用资源 ID

在代码中引用资源时,可以通过资源 ID 来访问这些资源。

// Accessing a string resource
String myString = getString(R.string.my_string);

// Accessing a color resource
int myColor = ContextCompat.getColor(this, R.color.my_color);

// Accessing a drawable resource
Drawable myDrawable = ContextCompat.getDrawable(this, R.drawable.my_drawable);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

1.2 动态加载资源

动态加载资源在不同的场景中非常有用,比如根据用户选择加载不同的布局或图片。

// Dynamically loading a layout
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.my_layout, null);

// Dynamically loading a drawable
Drawable drawable = getResources().getDrawable(R.drawable.my_drawable, getTheme());
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

1.3 资源的本地化

Android 提供了资源的本地化支持,可以根据用户的语言和地区自动加载相应的资源。

<!-- res/values/strings.xml -->
<string name="hello">Hello</string>

<!-- res/values-es/strings.xml -->
<string name="hello">Hola</string>
  • 1
  • 2
  • 3
  • 4
  • 5
// Getting localized string resource
String hello = getString(R.string.hello);
  • 1
  • 2

1.4 使用 TypedArray 访问资源

TypedArray 是一种方便的方式,可以批量访问一组资源。

<!-- res/values/attrs.xml -->
<declare-styleable name="MyCustomView">
    <attr name="customColor" format="color" />
    <attr name="customSize" format="dimension" />
</declare-styleable>
  • 1
  • 2
  • 3
  • 4
  • 5
// Accessing resources via TypedArray
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView);
int customColor = a.getColor(R.styleable.MyCustomView_customColor, Color.BLACK);
int customSize = a.getDimensionPixelSize(R.styleable.MyCustomView_customSize, 0);
a.recycle();
  • 1
  • 2
  • 3
  • 4
  • 5

2. Activity 的配置变更处理

配置变更(如屏幕旋转、语言更改等)会导致 Activity 被销毁并重新创建。开发者可以通过重写 onConfigurationChanged 方法来处理特定配置变更,避免 Activity 重新创建。

2.1 在 Manifest 文件中声明配置变更

<activity android:name=".MyActivity"
    android:configChanges="orientation|screenSize|keyboardHidden">
</activity>
  • 1
  • 2
  • 3

2.2 重写 onConfigurationChanged 方法

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Handle configuration changes
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        // Handle landscape orientation
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
        // Handle portrait orientation
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2.3 保存和恢复实例状态

Activity 被销毁并重新创建时,可以使用 onSaveInstanceStateonRestoreInstanceState 保存和恢复实例状态。

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("key", "value");
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    if (savedInstanceState != null) {
        String value = savedInstanceState.getString("key");
        // Use the restored data
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

3. Activity 的视图层次结构

Activity 的视图层次结构由多个 ViewGroupView 组成。理解视图层次结构有助于优化布局和性能。

3.1 使用 View Hierarchy Inspector

Android Studio 提供了 View Hierarchy Inspector 工具,可以用来分析和调试视图层次结构。

// Use View Hierarchy Inspector to analyze the view hierarchy
  • 1

3.2 优化布局层次结构

过多的嵌套布局会影响性能。使用 ConstraintLayout 可以减少嵌套层次,提高性能。

<!-- Using ConstraintLayout to reduce nesting -->
<ConstraintLayout 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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello, World!"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</ConstraintLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

3.3 了解 View 的绘制流程

View 的绘制流程包括测量(measure)、布局(layout)和绘制(draw)。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    // Measure child views
}

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    super.onLayout(changed, left, top, right, bottom);
    // Position child views
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    // Draw view content
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

4. Activity 的性能优化

优化 Activity 的性能可以提高应用的响应速度和用户体验。

4.1 避免主线程阻塞

长时间的操作应在后台线程中完成,避免阻塞主线程。

// Performing a long-running operation on a background thread
new Thread(new Runnable() {
    @Override
    public void run() {
        // Long-running operation
        final String result = performOperation();
        
        // Post result back to the main thread
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // Update UI with the result
                textView.setText(result);
            }
        });
    }
}).start();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

4.2 使用 ViewStub 延迟加载

ViewStub 是一个轻量级的视图,可以用来延迟加载布局。

<!-- Using ViewStub to delay load a layout -->
<ViewStub
    android:id="@+id/viewStub"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout="@layout/my_layout" />
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
// Inflating the ViewStub
ViewStub viewStub = findViewById(R.id.viewStub);
View inflated = viewStub.inflate();
  • 1
  • 2
  • 3

4.3 优化布局渲染

减少布局层次和优化布局可以提高渲染性能。使用 ConstraintLayout 替代嵌套的 LinearLayoutRelativeLayout

<!-- Optimizing layout with ConstraintLayout -->
<ConstraintLayout 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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello, World!"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</ConstraintLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

总结

通过对 Android Activity 的深入理解和灵活应用,可以实现丰富的用户体验和高效的应用程序。理解其生命周期、权限管理、数据传递、动画效果、导航和返回栈管理、资源管理、配置变更处理、视图层次结构、性能优化等方面的知识,有助于开发出性能优异且用户友好的应用程序。不断学习和实践这些知识,可以提升应用程序的质量和用户满意度。

欢迎点赞|关注|收藏|评论,您的肯定是我创作的动力

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/738293
推荐阅读
相关标签
  

闽ICP备14008679号