[android textview]android如何自定义TextView详解

更新时间:2019-12-02    来源:按钮特效    手机版     字体:

【www.bbyears.com--按钮特效】

Android控件中的TextView控件只有一个输入框,但是为了用于的操作方便我们应该实现一些功能:

1. 可以直接将内容删除的功能按钮

2. 可以记录用户以前输入的数据,同时能够将数据通过下拉显示,点击的时候实现输入

先上图:

01.jpeg


02.jpeg


下拉的图片没有做,所以和删除的图片使用同一个了,同志们可以直接在xml文件中更换就行了


分析:

肯定要使用自定义view来实现的,我们知道自定义view大概可以分为三类:自绘控件,组合控件,继承控件,我们这里是要进行增强的textView的功能,所以我这里使用的

是组合控件的方式来进行实现

既然使用组合控件,那么我们就来看看到底要使用什么控件来组合呢:

1.  其中一个必须是textView了

2. 下拉的那两个按钮是什么,当然是imageView了

3. 还有一个下拉列表,。。。。那就使用popwindow了

思路:

1. 如何实现直接删除用户的输入

使用addTextChangedListener监听textView内容的变化的时间根据内容的变化进行确定是否显示删除按钮,同时绑定删除按钮的点击事件

2.如何实现下拉显示用户输入过的数据,以及选中的时候实现输入

 我们通过下拉按钮的点击进行确定popwindow窗口的显示,在popwindow的界面有一个listview,在这个listview的adpater中进行绑定条目的点击事件

那么我们在adapter中绑定的事件,如何控制整个控件的功能输入呢,这里就是用handler了,在创建adapter的时候将handler传递过去,

然后当点击事件发生的时候我们使用handler进行send消息就行了,当然我们在send消息的时候将当前点击的数据传递过来就行了

上代码:

1. 控件主体代码

/** 
 * 自定义的控件,自带删除的按钮,下拉按钮 
 * @author zcs 
 * */  
public class EditTextClearSelect extends FrameLayout {  
      
    private EditText editText;  //显示的editText输入框  
    private ImageButton clearImageButton;  //显示的用于进行删除editText中内容的按钮  
    private ImageButton selectImageButton;  //显示的用于下拉editText中内容的按钮  
      
    //PopupWindow对象  ,用于已下拉形式显示数据  
    private PopupWindow selectPopupWindow= null;    
    //自定义Adapter    
    private ECS_OptionsAdapter optionsAdapter = null;    
    //下拉框选项数据源    
    private ArrayList datas = new ArrayList();     
    //下拉框依附组件   
    private LinearLayout parent;    
    //展示所有下拉选项的ListView    
    private ListView listView = null;     
    //用来处理选中或者删除下拉项消息    
    private Handler handler;    
      
    public EditTextClearSelect(Context context) {  
        super(context);  
    }  
    //用于对自定义的控件进行初始化  
    public EditTextClearSelect(Context context, AttributeSet attrs){  
        super(context, attrs);  
        //调用初始化自定义控件的方法  
        init(context,attrs);  
    }  
      
    /**   
     * 初始化下拉功能使用的组件   
     */    
    private void initWedget(Context context){    
        //初始化Handler,用来处理消息    
        handler = new Handler(){  
            public void handleMessage(Message msg) {  
                //当adapter中传递过来消息以后根据选中的id,将对应的值填写到EditText组件中  
                Bundle data = msg.getData();    
                //选中下拉项,下拉框消失    
                int selIndex = data.getInt("selIndex");    
                editText.setText(datas.get(selIndex));    
                dismiss();   
            }    
        };  
            
        //如果没有数据,则下拉菜单不显示  
        if( !(datas.size() > 0) ){  
            selectImageButton.setVisibility(View.GONE);  
        }  
          
        //设置点击下拉箭头图片事件,点击弹出PopupWindow浮动下拉框    
        selectImageButton.setOnClickListener(new View.OnClickListener() {    
            @Override    
            public void onClick(View v) {    
                 //获取下拉框依附的组件宽度,然后重新设置popWindow的宽度  
                selectPopupWindow.setWidth(parent.getWidth());  
                //显示PopupWindow窗口    
                popupWindwShowing();    
            }    
        });    
            
        //初始化PopupWindow    
        initPopuWindow(context);    
    }    
      
    /**   
     * 初始化PopupWindow   
     */     
    private void initPopuWindow(Context context){     
            
        //PopupWindow浮动下拉框布局    
        View loginwindow = LayoutInflater.from(context).inflate(R.layout.wecs_options, null);   
        listView = (ListView) loginwindow.findViewById(R.id.list);     
            
        //设置自定义Adapter    
        optionsAdapter = new ECS_OptionsAdapter(context,handler,datas);     
        listView.setAdapter(optionsAdapter);     
  
        selectPopupWindow = new PopupWindow(loginwindow, 0,LayoutParams.WRAP_CONTENT, true);     
        selectPopupWindow.setOutsideTouchable(true);     
        //实现当点击屏幕其他地方的时候将当前的pop关闭  
        selectPopupWindow.setBackgroundDrawable(new BitmapDrawable());      
    }    
      
    /**   
     * 显示PopupWindow窗口   
     * @param popupwindow   
     */     
    public void popupWindwShowing() {   
       //将pop窗口在自定义控件的底部显示  
       selectPopupWindow.showAsDropDown(parent);     
    }     
         
    /**   
     * PopupWindow消失   
     */     
    public void dismiss(){     
        selectPopupWindow.dismiss();     
    }    
      
     /** 
     * 初始化,包括增加删除按钮,下拉按钮 
     */  
    public void init(Context context,AttributeSet attrs){  
        //获取自定义控件的界面,相当于当前的自定义View就使用的View  
        View view = LayoutInflater.from(context).inflate(R.layout.weight_edit_clear_select, this, true);  
          
        parent =  (LinearLayout) view.findViewById(R.id.parent);  //当前的自定义控件  
        editText = (EditText) view.findViewById(R.id.et);  //输入框   
        clearImageButton = (ImageButton) view.findViewById(R.id.clear_ib); //删除按钮  
        selectImageButton = (ImageButton) view.findViewById(R.id.select_id); //下拉按钮  
          
        //当点击删除按钮的会后将输入框数据清空  
        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) {  
                    //输入框有内容,显示按钮  
                    editText.setSelection(s.length());  
                    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) {  
            }  
  
        });  
          
        //初始化pop组件,设置下拉按钮的功能  
        initWedget(context);    
          
        //将属性值设置到控件中  
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.EditTextClearSelect);  
        //输入框的默认的显示文本  
        CharSequence text = a.getText(R.styleable.EditTextClearSelect_textECS);  
        CharSequence hint = a.getText(R.styleable.EditTextClearSelect_hintECS);  
        CharSequence parent_width  = a.getText(R.styleable.EditTextClearSelect_layout_width);  
          
        if (text!=null&&!"".equals(text.toString().trim())) {  
            editText.setText(text);  
            //设置光标位置  
            editText.setSelection(text.length());  
            this.clearImageButton.setVisibility(View.VISIBLE);  
        }  
        if (hint!=null&&!"".equals(hint.toString().trim())) {  
            editText.setHint(hint);  
        }  
        if(parent_width!=null && !"".equals(parent_width.toString().trim()) ){  
            //设置当前控件的宽度,为屏幕的百度比有参数进行设置  
            LayoutParams parent_lp = (LayoutParams) parent.getLayoutParams();  
            parent_lp.width = (int) (AppUtil.getScreenDispaly(context)[0] * ( (Double)(Double.parseDouble(parent_width.toString()) / 100) ));  
            Log.i("控件宽度", parent_lp.width+"");  
            parent.setLayoutParams(parent_lp);  
        }  
        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;  
    }  
      
    //设置下拉列表中的选项值  
    public void setOptionsValue(ArrayList inDatas){  
        datas.clear();  
        if( (inDatas ==null) || !(inDatas.size() > 0) ){  
            selectImageButton.setVisibility(View.GONE);  
        }else{  
            selectImageButton.setVisibility(View.VISIBLE);  
            datas.addAll(inDatas);  
        }  
        optionsAdapter.notifyDataSetChanged();  
    }


2. popwindow里面listview的适配器

public class ECS_OptionsAdapter extends BaseAdapter {  
  
        private ArrayList list = new ArrayList();     
        private Context context = null;     
        //传递过来的hanler,用于进行通知操作(这里是通知自定义的view要继续修改editText中的数据)  
        private Handler handler;  
          
        public ECS_OptionsAdapter(Context context,Handler handler,ArrayList list){    
            this.context = context;    
            this.handler = handler;    
            this.list = list;    
        }    
            
        @Override    
        public int getCount() {    
            return list.size();    
        }    
        
        @Override    
        public Object getItem(int position) {    
            return list.get(position);    
        }    
        
        @Override    
        public long getItemId(int position) {    
            return position;    
        }    
        
        @Override    
        public View getView(final int position, View convertView, ViewGroup parent) {    
                
            ViewHolder holder = null;     
            if (convertView == null) {     
                holder = new ViewHolder();     
                //下拉项布局    
                convertView = LayoutInflater.from(context).inflate(R.layout.wecs_option_item, null);     
                holder.textView = (TextView) convertView.findViewById(R.id.item_text);     
                convertView.setTag(holder);     
            } else {     
                holder = (ViewHolder) convertView.getTag();     
            }     
            holder.textView.setText(list.get(position));    
            //为下拉框选项文字部分设置事件,最终效果是点击将其文字填充到文本框    
            holder.textView.setOnClickListener(new View.OnClickListener() {    
                @Override    
                public void onClick(View v) {    
                    //当点击的时候进行发送消息,通知组件进行修改数据  
                    Message msg = new Message();    
                    //设置要传递的数据  
                    Bundle data = new Bundle();    
                    //设置选中索引    
                    data.putInt("selIndex", position);    
                    msg.setData(data);   
                    //发出消息    
                    handler.sendMessage(msg);  
                }    
            });    
            return convertView;     
        }    
        
    }    
  
    class ViewHolder {     
        TextView textView;     
    }


3. 使用

private EditTextClearSelect etcs;  
  
@Override  
protected void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  
    setContentView(R.layout.activity_main);  
    init();  
}  
  
//初始化  
private void init(){  
    String selectDatas = "admin,login,user";  
    etcs = (EditTextClearSelect) findViewById(R.id.username_edit);  
    //为控件设置下拉的数据  
    etcs.setOptionsValue( new ArrayList(Arrays.asList(selectDatas.split(","))) );  
      
}



Android中自定义textview可以进行自体设置

面是代码:

package com.windy.androidfont;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class FontTextView extends TextView {
    private Context mContext;
    private String TypefaceName = "";
    public String getTypefaceName() {
        return TypefaceName;
    }
    public void setTypefaceName(String typefaceName) {
        TypefaceName = typefaceName;
        Typeface typeface = Typeface.createFromAsset(mContext.getAssets(), "font/" + TypefaceName + ".ttf");
        this.setTypeface(typeface);
        System.gc();
    }
    public FontTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.mContext = context;
        int resouceId = attrs.getAttributeResourceValue(null, "typefaceName", 0);
        if (resouceId != 0) {
            TypefaceName = context.getResources().getString(resouceId);
        } else {
            TypefaceName = attrs.getAttributeValue(null, "typefaceName");
        }
        if (TypefaceName != null && !"".equals(TypefaceName)) {
            Typeface typeface = Typeface.createFromAsset(context.getAssets(), "font/" + TypefaceName + ".ttf");
            this.setTypeface(typeface);
        }
    }
    public FontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        // 先判断是否配置的资源文件
        int resouceId = attrs.getAttributeResourceValue(null, "typefaceName", 0);
        if (resouceId != 0) {
            TypefaceName = context.getResources().getString(resouceId);
        } else {
            TypefaceName = attrs.getAttributeValue(null, "typefaceName");
        }
        if (TypefaceName != null && !"".equals(TypefaceName)) {
            Typeface typeface = Typeface.createFromAsset(context.getAssets(), "font/" + TypefaceName + ".ttf");
            this.setTypeface(typeface);
        }
    }
    public FontTextView(Context context) {
        super(context);
        this.mContext = context;
        // TypefaceName = attrs.getAttributeValue(null, "TypefaceName");
        if (TypefaceName != null && !"".equals(TypefaceName)) {
            Typeface typeface = Typeface.createFromAsset(context.getAssets(), "font/" + TypefaceName + ".ttf");
            this.setTypeface(typeface);
        }
    }
}


下面是布局:



大字体是要设置的属性,pop是字体库的名字

注意:自体库文件我这里放到了assets中的font文件夹中给个截图吧:

strings.xml文件中的截图:可以把字体的配置放到字符串资源中,这样就能统一进行更改了,如果你的需要中要动态的进行配置的话,可以对FontTextView进行改写,我的想法是在将自体配置放进prefrence中进行配置,这样就可以直接在FontTextView中进行改写了,本来想把这个类写的完成呢,由于时间关系就没写,有需求的可以自己去实现。就说这么多吧。


Android自定义View的实现

 很多时候系统自带的View满足不了设计的要求,就需要自定义View控件。自定义View首先要实现一个继承自View的类。添加类的构造方法,override父类的方法,如onDraw,(onMeasure)等。如果自定义的View有自己的属性,需要在values下建立attrs.xml文件,在其中定义属性,同时代码也要做修改。

一个简单的例子:

・新建一个MyView类,继承自TextView,并添加构造方法:

package com.example.xhelloworld;
import android.content.Context;
import android.widget.TextView;
public class MyView extends TextView{
    public MyView(Context context) {
       super(context);
       // TODO Auto-generated constructor stub
    }
}


・再在主activity中调用。方法是setContentView(new MyView(this));这句

package com.example.xhelloworld;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
public class NewView extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_newview);
        setContentView(new MyView(this));
       
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_newview, menu);
        return true;
    }
}

运行后的结果为:

 


这样一个简单的自定义View就可以使用了。可以改变一下背景颜色,在MyView类中添加:

@Override
    protected void onDraw(Canvas canvas) {
       // TODO Auto-generated method stub
       super.onDraw(canvas);
       canvas.drawColor(Color.BLUE);
    }

即可完成。运行结果

 


上面的例子很简单,没有涉及到属性的添加。使用范围很小,不能在布局文件中使用。如果要在布局文件中用到,还需要添加一个构造方法:

public MyView(Context context,AttributeSet attrs){
       super(context, attrs);  
    }

当然,上面只是在code中做的修改,在xml文件(main.xml)中也需要进行如下操作:


至少在xml文件中写上上面的内容。其中com.example.xhelloworld.NewView这句是需要显示的控件所代表的类。Com.example.xhelloworld是类的包名,NewView是类名。这个类肯定是继承自View的自定义类(其实就是,使我们自己写的,这是废话了。。。),可以是在工程中直接源码添加xxxx.java的,也可以是在libs目录下自己新添加的jar包里面的。如果是jar包里面的一个类,则路径就是jar包里面,这个类的路径。

完成上面的两步之后就可以在代码中实例化这个布局文件了

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //setContentView(new MyView(this));


显示的效果同上图。

下面介绍如何实现自定义View的属性设置。实现自定义View的属性设置,需要:

・在values目录下建立attrs.xml文件,添加属性内容

・在布局文件中添加新的命名空间xmlns,然后可以使用命名空间给自定义的空间设置属性

・设置完属性之后,当然还要对其进行处理。在自定义View类中的构造方法中进行处理

根据这三步给一个例子进行说明一下

首先添加attrs.xml文件,在定义属性

 

 
     
     
     
    declare-styleable> 
resources>


然后在布局文件中完成:

xmlns:my=http://schemas.android.com/apk/res/com.example.xhelloworld


注:这步我在实现的时候出错,问题是显示找不到属性textColor和textSize,这奇怪的错误。解决方法是,在写my:textColor="#FFFFFFFF" 时,写到my之后,按alt+/,这是会自动添加一个xmlns,和my的路径是一样的,用生成的这个替换掉my就可以了。奇葩的问题就用奇葩的方法解决。起初我也不知道怎么弄,瞎搞出来的。

最后在MyView.java中添加另一个构造方法,并添加代码来处理从xml中获得的属性

public MyView(Context context,AttributeSet attrs){
       super(context, attrs);
         mPaint = new Paint();  
        //TypedArray是一个用来存放由context.obtainStyledAttributes获得的属性的数组  
        //在使用完成后,一定要调用recycle方法  
        //属性的名称是styleable中的名称+“_”+属性名称  
        //TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyView);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyView);
        int textColor = array.getColor(R.styleable.MyView_textColor, 0XFF00FF00); //提供默认值,放置未指定  
        float textSize = array.getDimension(R.styleable.MyView_textSize, 36);  
        mPaint.setColor(textColor);  
        mPaint.setTextSize(textSize);  
        array.recycle(); //一定要调用,否则这次的设定会对下次的使用造成影响  
      
    }


 完成之后就已经实现了自定视图的构造,自定义视图属性的添加很处理。现在完成的是一般的自定义视图,继承自TextView或者View等视图,也就是通过程序主UI线程完成更新的视图,如果是自定义SurfaceView,实现方法有所不同。

添加完之后肯定有很多疑问,自己去做可能还不能理解。这里再对上面操作进行解释说明。

背后的事

View类的构造方法:

・public view(Context context)       当在代码中创建对象时会被调用

・public View (Context context, AttributeSet attrs)

官方的文档是:

Constructor that is called when inflating a view from XML. This is called when a view is being constructed from an XML file, supplying attributes that were specified in the XML file. This version uses a default style of 0, so the only attribute values applied are those in the Context's Theme and the given AttributeSet

大致应该是这个方法是通过xml文件来创建一个view对象的时候调用。很显然xml文件一般是布局文件,就是现实控件的时候调用,而布局文件中免不了会有属性的设置,如android:layout_width等,对这些属性的设置对应的处理代码也在这个方法中完成。

两个参数

Context          The Context the view is running in, through which it can access the current theme, resources, etc.

Attrs              The attributes of the XML tag that is inflating the view

・public View (Context context, AttributeSet attrs,int defStyle)

Perform inflation from XML and apply a class-specific base style. This constructor of View allows subclasses to use their own base style when they are inflating. For example, a Button class's constructor would call this version of the super class constructor and supply R.attr.buttonStyle fordefStyle; this allows the theme's button style to modify all of the base view attributes (in particular its background) as well as the Button class's attributes.

看的不太懂,没用到,下放一下吧额

这就是为什么要添加上面的两个构造方法的原因。

本文来源:http://www.bbyears.com/wangyetexiao/81860.html

热门标签

更多>>

本类排行