Android组合控件EditText

来源:互联网 发布:mac上如何查找app路径 编辑:程序博客网 时间:2024/05/21 02:37

1,控件为EditText中加入一个清除内容按钮,当输入类容后显示图片,没有内容则不显示。

效果图


2,组合控件的布局文件

<merge xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="60dp"     >    <EditText        android:id="@+id/edittext"        android:layout_width="fill_parent"        android:layout_height="60dp"        android:layout_gravity="center_vertical"        android:singleLine="true"         />    <ImageButton        android:id="@+id/imageview"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:background="@drawable/cancel_nomal"        android:layout_gravity="right|center_vertical"        android:visibility="gone"         /></merge>
3,自定义控件

package com.exmple.custonbutton;import android.content.Context;import android.text.Editable;import android.text.TextUtils;import android.text.TextWatcher;import android.util.AttributeSet;import android.view.LayoutInflater;import android.view.View;import android.widget.EditText;import android.widget.FrameLayout;import android.widget.ImageButton;/** * 带取消按钮的输入框 *  * @author dell *  */public class ImgEditText extends FrameLayout {private EditText editText;private ImageButton imgButton;public ImgEditText(Context context) {super(context);// TODO Auto-generated constructor stub}public ImgEditText(Context context, AttributeSet attrs) {super(context, attrs);// TODO Auto-generated constructor stubLayoutInflater.from(context).inflate(R.layout.img_edittext, this, true);this.editText = (EditText)findViewById(R.id.edittext);this.imgButton = (ImageButton)findViewById(R.id.imageview);this.editText.addTextChangedListener(new TextWatcher() {@Overridepublic void onTextChanged(CharSequence s, int start, int before, int count) {// TODO Auto-generated method stubif(!TextUtils.isEmpty(s)){imgButton.setVisibility(View.VISIBLE);}else{imgButton.setVisibility(View.GONE);}}@Overridepublic void beforeTextChanged(CharSequence s, int start, int count,int after) {// TODO Auto-generated method stub}@Overridepublic void afterTextChanged(Editable s) {// TODO Auto-generated method stub}});//按钮的点击事件 清除输入框的所有内容this.imgButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubeditText.setText(null);imgButton.setVisibility(View.GONE);}});}//获取输入的内容public String getContent(){return editText.getText().toString();}},
4,布局文件中引用
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"     >    <com.exmple.custonbutton.ImgEditText        android:layout_width="match_parent"        android:layout_height="wrap_content" /></LinearLayout>