这一次,我倾尽所有,换你一世陪伴。
这一篇列出几种常用EditText和它的一些属性,其中后面还有自定义EditText和自定义AutoCompleteTextView,其他属性还有ExtractEditText请读者自行去深究。
直接上代码了,不做过多的解释,自定义AdvancedAutoCompleteTextView可详细看底部链接里面的。
- MainActivity.java
package com.im.wu.edittextpractice;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private AdvancedAutoCompleteTextView tv;
private AutoCompleteAdapter adapter;
private ArrayList<String> mOriginalValues=new ArrayList<String>();
private AutoCompleteTextView autoTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autoTv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
initAutoComplete("history", autoTv);
Button search = (Button) findViewById(R.id.button1);
search.setOnClickListener(this);
mOriginalValues.add("1234561");
mOriginalValues.add("1234562");
mOriginalValues.add("2234563");
mOriginalValues.add("2234564");
mOriginalValues.add("3234561111");
mOriginalValues.add("32345622222");
mOriginalValues.add("323456333333");
mOriginalValues.add("3234564444");
mOriginalValues.add("3234565555");
mOriginalValues.add("32345666666");
mOriginalValues.add("32345777777");
tv = (AdvancedAutoCompleteTextView) findViewById(R.id.tv);
tv.setThreshold(0);
adapter = new AutoCompleteAdapter(this, mOriginalValues, 10);
tv.setAdapter(adapter);
}
@Override
public void onClick(View v) {
// 这里可以设定:当搜索成功时,才执行保存操作
saveHistory("history", autoTv);
}
private void initAutoComplete(String field,AutoCompleteTextView auto) {
SharedPreferences sp = getSharedPreferences("network_url", 0);
String longhistory = sp.getString("history", "nothing");
String[] hisArrays = longhistory.split(",");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, hisArrays);
//只保留最近的50条的记录
if(hisArrays.length > 50){
String[] newArrays = new String[50];
System.arraycopy(hisArrays, 0, newArrays, 0, 50);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, newArrays);
}
auto.setAdapter(adapter);
auto.setDropDownHeight(350);
auto.setThreshold(1);
auto.setCompletionHint("最近的5条记录");
auto.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
AutoCompleteTextView view = (AutoCompleteTextView) v;
if (hasFocus) {
view.showDropDown();
}
}
});
}
/**
* 把指定AutoCompleteTextView中内容保存到sharedPreference中指定的字符段
* @param field 保存在sharedPreference中的字段名
* @param auto 要操作的AutoCompleteTextView
*/
private void saveHistory(String field,AutoCompleteTextView auto) {
String text = auto.getText().toString();
SharedPreferences sp = getSharedPreferences("network_url", 0);
String longhistory = sp.getString(field, "nothing");
if (!longhistory.contains(text + ",")) {
StringBuilder sb = new StringBuilder(longhistory);
sb.insert(0, text + ",");
sp.edit().putString("history", sb.toString()).commit();
}
}
}
- EditTextWithDel.java
package com.im.wu.edittextpractice;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.EditText;
/**
* @author sunday
* 2013-12-04
*/
public class EditTextWithDel extends EditText {
private final static String TAG = "EditTextWithDel";
private Drawable imgInable;
private Drawable imgAble;
private Context mContext;
public EditTextWithDel(Context context) {
super(context);
mContext = context;
init();
}
public EditTextWithDel(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
init();
}
public EditTextWithDel(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
init();
}
private void init() {
imgInable = mContext.getResources().getDrawable(R.drawable.delete_gray);
imgAble = mContext.getResources().getDrawable(R.drawable.delete);
addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void afterTextChanged(Editable s) {
setDrawable();
}
});
setDrawable();
}
private void setDrawable() {
if(length() < 1)
setCompoundDrawablesWithIntrinsicBounds(null, null, imgInable, null);
else
setCompoundDrawablesWithIntrinsicBounds(null, null, imgAble, null);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (imgAble != null && event.getAction() == MotionEvent.ACTION_UP) {
int eventX = (int) event.getRawX();
int eventY = (int) event.getRawY();
Log.e(TAG, "eventX = " + eventX + "; eventY = " + eventY);
Rect rect = new Rect();
getGlobalVisibleRect(rect);
rect.left = rect.right - 50;
if(rect.contains(eventX, eventY))
setText("");
}
return super.onTouchEvent(event);
}
@Override
protected void finalize() throws Throwable {
super.finalize();
}
}
- AutoCompleteAdapter.java
package com.im.wu.edittextpractice;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by wu on 2016/3/15.
*/
public class AutoCompleteAdapter extends BaseAdapter implements Filterable{
private Context context;
private ArrayFilter mFilter;
private ArrayList<String> mOriginalValues;//所有的Item
private List<String> mObjects;//过滤后的item
private final Object mLock = new Object();
private int maxMatch=10;//最多显示多少个选项,负数表示全部
public AutoCompleteAdapter(Context context,ArrayList<String> mOriginalValues,int maxMatch){
this.context=context;
this.mOriginalValues=mOriginalValues;
this.maxMatch=maxMatch;
}
@Override
public Filter getFilter() {
// TODO Auto-generated method stub
if (mFilter == null) {
mFilter = new ArrayFilter();
}
return mFilter;
}
private class ArrayFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence prefix) {
// TODO Auto-generated method stub
FilterResults results = new FilterResults();
// if (mOriginalValues == null) {
// synchronized (mLock) {
// mOriginalValues = new ArrayList<String>(mObjects);//
// }
// }
if (prefix == null || prefix.length() == 0) {
synchronized (mLock) {
Log.i("tag", "mOriginalValues.size=" + mOriginalValues.size());
ArrayList<String> list = new ArrayList<String>(mOriginalValues);
results.values = list;
results.count = list.size();
return results;
}
} else {
String prefixString = prefix.toString().toLowerCase();
final int count = mOriginalValues.size();
final ArrayList<String> newValues = new ArrayList<String>(count);
for (int i = 0; i < count; i++) {
final String value = mOriginalValues.get(i);
final String valueText = value.toLowerCase();
// if(valueText.contains(prefixString)){//匹配所有
//
// }
// First match against the whole, non-splitted value
if (valueText.startsWith(prefixString)) { //源码 ,匹配开头
newValues.add(value);
}
// else {
// final String[] words = valueText.split(" ");//分隔符匹配,效率低
// final int wordCount = words.length;
//
// for (int k = 0; k < wordCount; k++) {
// if (words[k].startsWith(prefixString)) {
// newValues.add(value);
// break;
// }
// }
// }
if(maxMatch>0){//有数量限制
if(newValues.size()>maxMatch-1){//不要太多
break;
}
}
}
results.values = newValues;
results.count = newValues.size();
}
return results;
}
@Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
// TODO Auto-generated method stub
mObjects = (List<String>) results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mObjects.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
//此方法有误,尽量不要使用
return mObjects.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = null;
if(convertView==null){
holder=new ViewHolder();
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.simple_list_item_for_autocomplete, null);
holder.tv=(TextView)convertView.findViewById(R.id.simple_item_0);
holder.iv=(ImageView)convertView.findViewById(R.id.simple_item_1);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.tv.setText(mObjects.get(position));
holder.iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String obj=mObjects.remove(position);
mOriginalValues.remove(obj);
notifyDataSetChanged();
}
});
return convertView;
}
class ViewHolder {
TextView tv;
ImageView iv;
}
public ArrayList<String> getAllItems(){
return mOriginalValues;
}
}
- AdvancedAutoCompleteTextView.java
package com.im.wu.edittextpractice;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
/**
* Created by wu on 2016/3/15.
*/
public class AdvancedAutoCompleteTextView extends RelativeLayout{
private Context context;
private AutoCompleteTextView tv;
public AdvancedAutoCompleteTextView(Context context) {
super(context);
// TODO Auto-generated constructor stub
this.context=context;
}
public AdvancedAutoCompleteTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
this.context=context;
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
initViews();
}
private void initViews() {
RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
tv=new AutoCompleteTextView(context);
tv.setLayoutParams(params);
tv.setPadding(10, 0, 40, 0);
// tv.setSingleLine(true);
RelativeLayout.LayoutParams p=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
p.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
p.addRule(RelativeLayout.CENTER_VERTICAL);
p.rightMargin=10;
ImageView iv=new ImageView(context);
iv.setLayoutParams(p);
iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
iv.setImageResource(R.drawable.delete);
iv.setClickable(true);
iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
tv.setText("");
}
});
this.addView(tv);
this.addView(iv);
}
public void setAdapter(AutoCompleteAdapter adapter){
tv.setAdapter(adapter);
}
public void setThreshold(int threshold){
tv.setThreshold(threshold);
}
public AutoCompleteTextView getAutoCompleteTextView(){
return tv;
}
}
- activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="5"
android:orientation="horizontal">
<TextView android:text="默认"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:layout_weight="4" />
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="5"
android:orientation="horizontal">
<TextView android:text="maxLength40"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:layout_weight="4" />
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:maxLength="40"
android:hint="请输入用户名..."/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="5"
android:orientation="horizontal">
<TextView android:text="textColorHint"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:layout_weight="4" />
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:maxLength="40"
android:hint="请输入用户名..."
android:textColorHint="#238745"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="5"
android:orientation="horizontal">
<TextView android:text="password"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:layout_weight="4" />
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:password="true"
android:hint="密码"
android:maxLength="11"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="5"
android:orientation="horizontal">
<TextView android:text="phoneNumber"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:layout_weight="4" />
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:phoneNumber="true"
android:hint="phoneNumber"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="5"
android:orientation="horizontal">
<TextView android:text="inputType"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:layout_weight="4" />
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:inputType="date"
android:hint="inputType:date"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="5"
android:orientation="horizontal">
<TextView android:text="inputType"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:layout_weight="4" />
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:imeOptions="actionSearch"
android:hint="imeOptions:actionSearch"/>
</LinearLayout>
<com.im.wu.edittextpractice.EditTextWithDel
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:hint="输入"
android:padding="7dp"
android:singleLine="true"/>
<com.im.wu.edittextpractice.EditTextWithDel
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:hint="输入"
android:padding="7dp"
android:singleLine="true"/>
<AutoCompleteTextView
android:hint="请输入文字进行搜索"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/autoCompleteTextView1"/>
<Button android:text="搜索" android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
<com.im.wu.edittextpractice.AdvancedAutoCompleteTextView
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</com.im.wu.edittextpractice.AdvancedAutoCompleteTextView>
</LinearLayout>
</ScrollView>
- simple_list_item_for_autocomplete.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:orientation="horizontal"
android:paddingTop="5dip"
android:paddingBottom="5dip"
>
<TextView android:id="@+id/simple_item_0"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingLeft="5dip"
android:textColor="@android:color/black"
/>
<ImageView android:id="@+id/simple_item_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:src="@drawable/delete"
android:layout_centerVertical="true"
android:layout_marginRight="5dip"
/>
</LinearLayout>
部分内容摘自(http://blog.csdn.net/ff20081528/article/details/17121911
http://blog.csdn.net/i_lovefish/article/details/17337999)。
- 可关注微信公众号(zhudekoudai 、smart_android)
- QQ群号: 413589216
- 专注Android分享:http://www.codernote.top/