Break through the performance bottleneck of custom View

In Android applications, custom View is a very common requirement. Custom Views help you create unique UI elements to meet the specific needs of your application. However, custom Views can also cause performance issues, especially if your application needs to deal with a large number of custom Views.

In this article, we will explore some Android custom View performance optimization tips to ensure that your application remains efficient and stable when dealing with custom Views. We will discuss from the following aspects:

1. Use the correct layout

Proper layout is critical when creating custom Views. Using the correct layout can help you minimize layout hierarchies, which can improve your application's performance.

For example, if you need to create a custom View with multiple subviews, using ConstraintLayout instead of RelativeLayout and LinearLayout can simplify the layout and reduce nesting.

Here is a sample code:

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- 添加您的自定义视图组件和约束条件 -->

</androidx.constraintlayout.widget.ConstraintLayout>

Another important layout trick is to use ViewStub. A ViewStub is a lightweight view that can be used as a placeholder and not inflated until the real view is needed. This can greatly reduce layout hierarchies and improve performance.

2. Cache view

Caching views is another important performance optimization tip. When you use a custom View, you usually need to create multiple instances. If you don't cache these instances properly, your application can become very slow.

In order to cache views, you can use Android's ViewHolder pattern or use a custom cache object. The ViewHolder pattern is a technique widely used by Android developers to improve performance in list or grid views. Using a custom cache object allows for greater control over the view lifecycle and reduces view creation and destruction.

The following is a sample code for the ViewHolder pattern:

class CustomView(context: Context) : View(context) {
    
    
    private class ViewHolder {
    
    
        // 缓存视图
        var textView: TextView? = null
        var imageView: ImageView? = null
        // 添加其他视图组件
    }

    private var viewHolder: ViewHolder? = null

    init {
    
    
        // 初始化ViewHolder
        viewHolder = ViewHolder()
        // 查找视图并关联到ViewHolder
        viewHolder?.textView = findViewById(R.id.text_view)
        viewHolder?.imageView = findViewById(R.id.image_view)
        // 添加其他视图组件的查找和关联
    }

    override fun onDraw(canvas: Canvas) {
    
    
        super.onDraw(canvas)
        // 绘制视图
    }
}

3. Avoid excessive drawing operations

Drawing operations are one of the most important performance issues in custom Views. If your custom View requires a lot of drawing operations, your application may become very slow.

To avoid excessive drawing operations, you can use the View's setWillNotDraw method to disable unnecessary drawing. You can also use the Canvas' clipRect method to limit the area of ​​the drawing operation. Additionally, you can use hardware acceleration to speed up drawing operations.

Here is a sample code:

class CustomView(context: Context) : View(context) {
    
    
    init {
    
    
        setWillNotDraw(true) // 禁用绘制
    }

    override fun onDraw(canvas: Canvas) {
    
    
        super.onDraw(canvas)
        // 绘制操作
        canvas.clipRect(0, 0, width, height) // 限制绘制区域
        // 添加其他绘制操作
    }
}

4. Using asynchronous tasks

If your custom View needs to perform time-consuming operations, such as loading images from the network or processing large amounts of data, then you should use asynchronous tasks to perform these operations. This ensures that your application remains responsive and does not block the UI while performing these operations.

Here is a sample code that loads an image using an asynchronous task:

class CustomView(context: Context) : View(context) {
    
    
    private var image: Bitmap? = null

    fun loadImageAsync(imageUrl: String) {
    
    
        val asyncTask = object : AsyncTask<Void, Void, Bitmap>() {
    
    
            override fun doInBackground(vararg params: Void?): Bitmap {
    
    
                // 执行耗时操作,如从网络加载图像
                return loadImageFromUrl(imageUrl)
            }

            override fun onPostExecute(result: Bitmap) {
    
    
                super.onPostExecute(result)
                // 在主线程更新UI
                image = result
                invalidate() // 刷新视图
            }
        }

        asyncTask.execute()
    }

    override fun onDraw(canvas: Canvas) {
    
    
        super.onDraw(canvas)
        // 绘制图像
        image?.let {
    
    
            canvas.drawBitmap(it, 0f, 0f, null)
        }
        // 添加其他绘制操作
    }
}

5. Use appropriate data structures

In custom Views, using proper data structures can greatly improve performance. For example, if you need to draw a large number of points or lines, then using a FloatBuffer or ByteBuffer can improve performance. If you need to process large amounts of image data, using BitmapFactory.Options can reduce memory usage.

The following is a sample code for drawing points using FloatBuffer:

class CustomView(context: Context) : View(context) {
    
    
    private var pointBuffer: FloatBuffer? = null

    init {
    
    
        // 初始化点的数据
        val points = floatArrayOf(0f, 0f, 100f, 100f, 200f, 200f)
        pointBuffer = ByteBuffer.allocateDirect(points.size * 4)
            .order(ByteOrder.nativeOrder())
            .asFloatBuffer()
        pointBuffer?.put(points)
        pointBuffer?.position(0)
    }

    override fun onDraw(canvas: Canvas) {
    
    
        super.onDraw(canvas)
        // 绘制点
        pointBuffer?.let {
    
    
            canvas.drawPoints(it, paint)
        }
        // 添加其他绘制操作
    }
}

in conclusion

In this article, we explored some Android custom View performance optimization techniques. By using proper layout, caching views, avoiding excessive drawing operations, using asynchronous tasks, and proper data structures, you can ensure that your application remains efficient and stable when dealing with custom Views.

Remember that optimizing the performance of your custom View is an ongoing process. You should review your application frequently and use the latest technologies and best practices to improve performance.

at last

If you want to become an architect or want to break through the 20-30K salary range, then don't be limited to coding and business, but you must be able to select models, expand, and improve programming thinking. In addition, a good career plan is also very important, and the habit of learning is very important, but the most important thing is to be able to persevere. Any plan that cannot be implemented consistently is empty talk.

If you have no direction, here I would like to share with you a set of "Advanced Notes on the Eight Major Modules of Android" written by the senior architect of Ali, to help you organize the messy, scattered and fragmented knowledge systematically, so that you can systematically and efficiently Master the various knowledge points of Android development.
insert image description here
Compared with the fragmented content we usually read, the knowledge points of this note are more systematic, easier to understand and remember, and are arranged strictly according to the knowledge system.

Full set of video materials:

1. Interview collection

insert image description here
2. Source code analysis collection
insert image description here

3. The collection of open source frameworks
insert image description here
welcomes everyone to support with one click and three links. If you need the information in the article, directly scan the CSDN official certification WeChat card at the end of the article to get it for free↓↓↓

PS: There is also a ChatGPT robot in the group, which can answer your work or technical questions

Guess you like

Origin blog.csdn.net/weixin_43440181/article/details/131089695