Android 自定义控件

Stella981
• 阅读 493

用到的图片文件:Android 自定义控件

平时都是用简单的控件通过布局来组合一大堆控件,界面复杂起来的话,布局文件就很大,维护起来也很烦。就想把常用的控件组合写成自定义控件,这样维护起来也方便,代码也清爽,下面就以带消除按钮的EditText为例。平时,EditText删除输入的都是按好多下删除键的,看到很多应用的输入框,在输入内容后,会跳出一个清空按钮,点击一下,输入的都会清除,这个用户体验很好。自己尝试了一下,原先是用最简单的控件组合,发现代码量太大,重用性不高,所以想把这个封装成一个自定义控件,直接调用。直接上代码。

    EditTextWithClearButton.java

import xidian.wwf.temperature.R;
import xidian.wwf.temperature.util.StringUtil;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;

/**
 * 带清除按钮的输入框
 * @author WWF
 */
public class EditTextWithClearButton extends LinearLayout{
    
    private EditText editText;
    private ImageButton clearImageButton;

    public EditTextWithClearButton(Context context) {
        super(context);
    }
    
    public EditTextWithClearButton(Context context,AttributeSet attrs){
        super(context, attrs);
        init(context,attrs);
    }
    
    /**
     * 初始化
     */
    public void init(Context context,AttributeSet attrs){
        View view = LayoutInflater.from(context).inflate(R.layout.weight_edit_with_clear, this, true);
        editText = (EditText) view.findViewById(R.id.et);
        clearImageButton = (ImageButton) view.findViewById(R.id.clear_ib);
        clearImageButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                editText.setText("");
            }
        });
        editText.addTextChangedListener(new TextWatcher() {
            
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    clearImageButton.setVisibility(View.VISIBLE);
                } else {
                    clearImageButton.setVisibility(View.GONE);
                }
            }
            
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                
            }
            @Override
            public void afterTextChanged(Editable s) {
                
            }
        });
        //将属性值设置到控件中
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.EditWithClearText);
        CharSequence hint = a.getText(R.styleable.EditWithClearText_hint);
        CharSequence text = a.getText(R.styleable.EditWithClearText_text);
        if (text!=null&&!StringUtil.isEmpty(text.toString().trim())) {
            editText.setText(text);
            //设置光标位置
            editText.setSelection(text.length());
            this.clearImageButton.setVisibility(View.VISIBLE);
        }else {
            if (hint!=null&&!StringUtil.isEmpty(hint.toString().trim())) {
                editText.setHint(hint);
            }
        }
        a.recycle();
    }
    
    /**
     * 获得输入的值
     * @return
     */
    public String getText(){
        return this.editText.getText().toString();
    }
    
    /**
     * 设置值
     * @param text
     */
    public void setText(String text){
        this.editText.setText(text);
    }
    
    /**
     * 设置默认值
     * @param hint
     */
    public void setHint(String hint){
        this.editText.setHint(hint);
    }
    
    /**
     * 获得输入框控件
     * @return
     */
    public EditText getEditText(){
        return this.editText;
    }
    
    /**
     * 获得消除按钮
     * @return
     */
    public ImageButton getClearImageButton(){
        return this.clearImageButton;
    }
}

weight_edit_with_clear.xml 自定义控件布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@null"
    android:orientation="horizontal" >

    <EditText
        android:id="@+id/et"
        style="@style/text_normal"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@null"
        android:gravity="center_vertical"
        android:maxLength="20"
        android:paddingLeft="5dp"
        android:paddingRight="4dp"
        android:singleLine="true" />

    <ImageButton
        android:id="@+id/clear_ib"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@null"
        android:contentDescription="@string/image_content"
        android:src="@drawable/common_input_box_clear"
        android:visibility="gone" />

</LinearLayout>

这个布局文件就是自定义控件组合的布局文件,我采用线性布局,然后将EditText 和ImageButton 组合起来。

属性配置文件 attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="EditTextWithClearBitton">
        <attr name="text"  format="string"/>
        <attr name="hint"  format="string" />
    </declare-styleable>
</resources>

Activity 布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:wwf="http://schemas.android.com/apk/res/xidian.wwf.temperature"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white"
    android:orientation="vertical" >


    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/table_above_nor"
        android:gravity="center"
        android:orientation="horizontal"
        android:padding="10dp"
        android:layout_margin="10dp" >

        <TextView
            style="@style/text_normal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="10dp"
            android:singleLine="true"
            android:text="@string/account"
            android:textStyle="bold" />

        <xidian.wwf.temperature.weight.EditTextWithClearButton
            android:id="@+id/ssss"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical" 
            wwf:text="@string/system_error"
            >
        </xidian.wwf.temperature.weight.EditTextWithClearButton>
    </LinearLayout>

</LinearLayout>

引入我们自定义的属性,需在布局文件中加入上面的

xmlns:wwf="http://schemas.android.com/apk/res/项目包名"

在控件初始化中,获得属性值,赋给控件即可,赋值的代码

//将属性值设置到控件中
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.EditTextWithClearBitton);
CharSequence hint = a.getText(R.styleable.EditTextWithClearBitton_hint);
CharSequence text = a.getText(R.styleable.EditTextWithClearBitton_text);
if (text!=null&&!StringUtil.isEmpty(text.toString().trim())) {
    editText.setText(text);
    //设置光标位置
    editText.setSelection(text.length());
    this.clearImageButton.setVisibility(View.VISIBLE);
}else {
    if (hint!=null&&!StringUtil.isEmpty(hint.toString().trim())) {
        editText.setHint(hint);
    }
}
a.recycle();

然后就可以使用这个自定义控件了

下面是我运行的结果

Android 自定义控件

Android 自定义控件

Android 自定义控件

点赞
收藏
评论区
推荐文章
Stella981 Stella981
2年前
Android开源控件ViewPager Indicator的使用方法
AndroidViewpagerIndicator是Android开发中最常用的控件之一,几乎所有的新闻类APP中都有使用,下面介绍其基本使用方法。!(http://static.oschina.net/uploads/img/201403/14220432_afb0.png)1\.ViewPagerIndicator的Lib
Stella981 Stella981
2年前
Android控件在xml中初始化
一、写在前面界面控件的初始化一般通过findViewByid来查找绑定再强制转换,这项工作只是个纯体力活没有任何营养,一般常用的是使用匿名内部类的方式:首先需要获取到layout中布局页面的Button控件中指定的Id:android:id"";之后为这样按钮绑定监听器,使用匿名内部类的方式,代码如下:
Stella981 Stella981
2年前
Android开发问题汇总
1.ClassCastException异常是类型匹配出现的错误,xml布局文件中的控件id在Activity中匹配错误2.eclipse中遇到logcat无任何信息输出解决办法:windowshowview选择android下的devices,打开devices,点击右边的截屏图片。
Stella981 Stella981
2年前
Android 自定义组合控件 简单导航栏
最近在做项目的过程中,发现项目中好多界面的导航栏都很类似或者一样,但是每次都要重复写同样的代码,觉得很不爽,所以就简单地自定义了一下导航栏控件.先上图:!导航栏(http://static.oschina.net/uploads/img/201510/09104048_sODx.png)(https://www.oschina.net/
Wesley13 Wesley13
2年前
Android开发之列表控件
一、基础知识:ListView是一个经常用到的控件,ListView里面的每个子项Item可以使一个字符串,也可以是一个组合控件。先说说ListView的实现:1.准备ListView要显示的数据;2.使用一维或多维动态数组保存数据;3.构建适配器,简单地来说,适配器就是Item数组,动态数组有多少元素就生成多少个Item;4.把适配器添
Wesley13 Wesley13
2年前
IOS开发
有没有这种需求,自定一个panel,里面放了好几个控件,在多个页面用到这个panel。解决这个问题有三条思路:1.自己继承UIView写一个类,在这里面以代码的形式添加需要的控件,完成布局。2.使用XIB布局文件完成布局3.使用storyboard完成布局在这三中方式中,1显得高端大气上档次,哗啦哗啦敲半天。虽然我是技术控,但是也很反感这
Stella981 Stella981
2年前
Qt自定义控件大全+designer源码
抽空将自定义控件的主界面全部重写了一遍,采用左侧树状节点导航,看起来更精美高大上一点,后期准备单独做个工具专用每个控件的属性设计,其实qt自带的designer就具备这些功能,于是从qt4的源码中抽取出来,总共才1MB不到,不得不佩服Qt公司的程序员,写的很厉害。特意将自定义控件作为插件封装到了designer中,打开designer就从左侧控件栏中可以看到
Easter79 Easter79
2年前
TinyForm
TinyForm做一个用起来简单的表单工具库。先说说功能吧,这个工具提供了以下几个接口:通过任意DOM元素创建表单实例(TinyForm)可以自定义表单控件选择器获取表单控件获取(设置)DOM范围内所有(单个)表单控件的数据使用标签式设置验证规则以及提示消息获取(设置)DOM范围内所有(
Stella981 Stella981
2年前
Android自定义控件之圆形进度条
Android自定义控件之圆形进度条先上图:!填充的(https://static.oschina.net/uploads/img/201703/23151845_nnTV.gif"在这里输入图片标题")!环形的(https://static.oschina.net/uploads/img/201703/23151912_ewAq
Stella981 Stella981
2年前
Flutter 布局控件完结篇
本文对Flutter的29种布局控件进行了总结分类,讲解一些布局上的优化策略,以及面对具体的布局时,如何去选择控件。1\.系列文章1.Flutter布局详解(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fgithub.com%2Fyang72296