Android Studio App自定义控件中视图的构造和测量方法讲解及实战(附源码 实现下拉刷新功能 超详细必看)

简介: Android Studio App自定义控件中视图的构造和测量方法讲解及实战(附源码 实现下拉刷新功能 超详细必看)

需要全部源码或者图片集请点赞关注收藏后评论区留言~~~

一、视图的构造方法

Android自带的控件往往外观欠佳,开发者常常需要修改某些属性,比如按钮控件Button就有好几个问题,其一字号太小,其二文字颜色太浅,其三字母默认大写。于是XML文件中的每个Button节点就得添加textSize,textColor,textAllCaps三个属性,以便定制按钮的字号,文字颜色和大小写开关。

为了避免每个按钮都去修改,我们一般采用定义一个style.xml文件来定义格式,然后需要的时候引用它即可 效果如下

然而这样仍有不足之处,因为只有Button节点添加了style属性才奏效,要是忘了添加style属性就不管用了,而且样式引用只能修改已有的属性,不能添加新属性,也不能添加新方法,如果想更灵活的定制控件外观,就要通过自定义控件实现了。

自定义控件本质上都是一个Java类,也拥有自身的构造方法 它有四个构造方法如下

1:带一个参数的构造方法 public View()

2:带两个参数的构造方法 public View()

3:带三个参数的构造方法 public View()

4:带四个参数的构造方法 public View()

上述四种方法,前两种必须实现,否则不能在代码中创建视图对象,要么不能在XML文件中添加视图节点

进行自定义控件操作后效果如下 可以看见第三个按钮也就是自定义的按钮控件字号变大,文字变黑,同时按钮的默认背景不见了,文字也不居中对齐了

代码如下

Java类

package com.example.chapter10;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class CustomButtonActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_button);
    }
}

XML文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="这是系统默认的Button"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="这是来自style的Button"
        style="@style/CommonButton"/>
    <!-- 注意自定义控件需要指定该控件的完整路径 -->
    <com.example.chapter10.widget.CustomButton
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="这是自定义的Button"
        android:background="#ffff00"/>
</LinearLayout>

二、视图的测量方法

构造方法只是自定义控件的第一步,自定义控件的第二步时测量尺寸,也就是重写onMeasure方法,要想把自定义的控件画到界面上,首先得先直到这个控件的宽高尺寸

1:文本尺寸测量

文本尺寸分为文本的宽度和高度,需要根据文本大小分别计算,其中文本宽度用Paint类的measureText方法测量,至于文本高度的计算则用到了FontMetrics类, 效果如下

放大后效果如下

代码如下

Java类

package com.example.chapter10;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.chapter10.util.MeasureUtil;
@SuppressLint("DefaultLocale")
public class MeasureTextActivity extends AppCompatActivity {
    private TextView tv_desc, tv_text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_measure_text);
        tv_desc = findViewById(R.id.tv_desc);
        tv_text = findViewById(R.id.tv_text);
        initSizeSpinner(); // 初始化文字大小的下拉框
    }
    // 初始化文字大小的下拉框
    private void initSizeSpinner() {
        ArrayAdapter<String> sizeAdapter = new ArrayAdapter<String>(this,
                R.layout.item_select, descArray);
        Spinner sp_size = findViewById(R.id.sp_size);
        sp_size.setPrompt("请选择文字大小");
        sp_size.setAdapter(sizeAdapter);
        sp_size.setOnItemSelectedListener(new SizeSelectedListener());
        sp_size.setSelection(0);
    }
    private String[] descArray = {"12sp", "15sp", "17sp", "20sp", "22sp", "25sp", "27sp", "30sp"};
    private int[] sizeArray = {12, 15, 17, 20, 22, 25, 27, 30};
    class SizeSelectedListener implements OnItemSelectedListener {
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            String text = tv_text.getText().toString();
            int textSize = sizeArray[arg2];
            tv_text.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
            // 计算获取指定文本的宽度(其实就是长度)
            int width = (int) MeasureUtil.getTextWidth(text, textSize);
            // 计算获取指定文本的高度
            int height = (int) MeasureUtil.getTextHeight(text, textSize);
            String desc = String.format("下面文字的宽度是%d,高度是%d", width, height);
            tv_desc.setText(desc);
        }
        public void onNothingSelected(AdapterView<?> arg0) {}
    }
}

xml文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp" >
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="40dp" >
        <TextView
            android:id="@+id/tv_size"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            android:gravity="center"
            android:text="字体大小:"
            android:textColor="@color/black"
            android:textSize="17sp" />
        <Spinner
            android:id="@+id/sp_size"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_toRightOf="@+id/tv_size"
            android:gravity="left|center"
            android:spinnerMode="dialog" />
    </RelativeLayout>
    <TextView
        android:id="@+id/tv_desc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="left"
        android:textColor="@color/black"
        android:textSize="17sp" />
    <TextView
        android:id="@+id/tv_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:gravity="center"
        android:text="每逢佳节倍思亲"
        android:textColor="@color/black" />
</LinearLayout>

2:图形尺寸测量

相对于文本尺寸,图形尺寸的计算反而简单一些,因为Android提供了现成的宽和高的获取方法,如果图形时Bitmap格式,就通过getWidth方法获取宽度 其他类似

3:布局尺寸测量

View类提供了一种测量整体布局的思路,下面通过实战讲解 实现了一个下拉刷新功能

代码如下

Java类

package com.example.chapter10;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.chapter10.util.MeasureUtil;
@SuppressLint("DefaultLocale")
public class MeasureLayoutActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_measure_layout);
        LinearLayout ll_header = findViewById(R.id.ll_header);
        TextView tv_desc = findViewById(R.id.tv_desc);
        // 计算获取线性布局的实际高度
        float height = MeasureUtil.getRealHeight(ll_header);
        String desc = String.format("上面下拉刷新头部的高度是%f", height);
        tv_desc.setText(desc);
    }
}

XML文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <include layout="@layout/drag_drop_header" />
    <TextView
        android:id="@+id/tv_desc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:gravity="left"
        android:textColor="@color/black"
        android:textSize="17sp" />
</LinearLayout>

创作不易 觉得有帮助请点赞关注收藏~~~

相关文章
|
4天前
|
测试技术 Android开发
Android App获取不到pkgInfo信息问题原因
Android App获取不到pkgInfo信息问题原因
14 0
|
1月前
|
开发框架 移动开发 JavaScript
SpringCloud微服务实战——搭建企业级开发框架(四十六):【移动开发】整合uni-app搭建移动端快速开发框架-环境搭建
正如优秀的软件设计一样,uni-app把一些移动端常用的功能做成了独立的服务或者插件,我们在使用的时候只需要选择使用即可。但是在使用这些服务或者插件时一定要区分其提供的各种服务和插件的使用场景,例如其提供的【uni-starter快速开发项目模版】几乎集成了移动端所需的所有基础功能,使用非常方便,但是其许可协议只允许对接其uniCloud的JS开发服务端,不允许对接自己的php、java等其他后台系统。
145 2
|
1月前
|
设计模式 测试技术 数据库
基于Android的食堂点餐APP的设计与实现(论文+源码)_kaic
基于Android的食堂点餐APP的设计与实现(论文+源码)_kaic
|
2月前
|
算法 Java Android开发
安卓逆向 -- 实战某峰窝APP(静态分析)
安卓逆向 -- 实战某峰窝APP(静态分析)
26 0
|
2月前
|
网络协议 算法 Android开发
安卓逆向 -- 实战某峰窝APP(动态分析)
安卓逆向 -- 实战某峰窝APP(动态分析)
32 4
|
2月前
|
安全 Java 数据挖掘
当 App 有了系统权限,真的可以为所欲为? Android Performance Systrace
当 App 有了系统权限,真的可以为所欲为? Android Performance Systrace 转载自: https://androidperformance.com/2023/05/14/bad-android-app-with-system-permissions/#/0-Dex-%E6%96%87%E4%BB%B6%E4%BF%A1%E6%81%AF
31 0
|
Shell Linux 测试技术
Android App性能评测分析-cpu占用篇
1、前言 很多时候在使用APP的时候,手机可能会发热发烫。这是因为CPU使用率过高,CPU过于繁忙,会使整个手机无法响应用户,整体性能降低,用户体验就会很差,也容易引起ANR等等一系列问题。
4955 0
|
缓存 开发工具 Android开发
Android App性能评测分析-启动时间篇
1、前言 随着项目版本的迭代,App的性能问题会逐渐暴露出来,而好的用户体验与性能表现紧密相关,性能问题从应用的启动优化开始,下面会根据实际app性能测试案例,进行app性能评测之启动时间的分析和总结。
4057 0
|
Java 测试技术 程序员
Android App性能评测分析-内存篇
1、内存了解 在Android App的性能优化的各个部分里,内存方面的知识较多且不易理解,内存的问题绝对是最令人头疼的一部分,需要对内存基础知识、内存分配、内存管理机制等非常熟悉,才能排查问题。
1968 0