adapter edittext

本文详细介绍Android中自定义Adapter的实现方式,并介绍如何限制EditText输入及字数。此外,还探讨了设置EditText仅接收数字输入的方法,以及移动光标等实用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、Costom adapter
一、Costom adapter to adatper your class data.
继承 BaseAdapter   定义一个list 保存 自定义的数据  
实现下列方法
@Override
    public int getCount() {
        return 0;    //返回list 的size
    }
    @Override
    public Object getItem(int position) {
        return null; // 得到position位置的 数据 return list.get(postion)
    }
    @Override
    public long getItemId(int position) {
        return 0;  //返回postion指定的position
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return null; // 返回一个view布局装载了自定义的数据
    }


二、EditText
一、让你的EditText只接受数字输入的四种方法
    方法一、
    <EditText
    android:id="@+id/editText_inputType2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:numeric="integer|signed|decimal"   // 带负号和小数点
/>
方法二
    <EditText
    android:id="@+id/editText_inputType3"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="number"
/>



方法三、
DigitsKeyListener numericOnlyListener = new DigitsKeyListener();
// 有两种构造方法  () 不是所有的监听事件都是interface
this.editText_inputType.setKeyListener(numericOnlyListener);
方法四、
this.editText_word_Num =(EditText)findViewById(R.id.editText_word_Num);
二、限制EditText的字数的两种方法
方法一、
this.editText_word_Num.addTextChangedListener(new TextWatcher(){
        private CharSequence temp;
    @Override
    public void afterTextChanged(Editable s) {
        temp = s;
        if(temp.length()>5){
            temp = s.delete(5, temp.length());
            editText_word_Num.setText(temp);
            editText_word_Num.setSelection(5);
        }
    }
public void beforeTextChanged(CharSequence s, int start, int count,int after) {}
public void onTextChanged(CharSequence s, int start, int before,int count) {}
});

方法二、
this.editText_word_Num2.setFilters(new InputFilter[] {new InputFilter.LengthFilter(10)});

三、移动EditText的光标
editText_word_Num.setSelection(5);
public void setSelection (int index)    // Move the cursor to offset index.Convenience for setSelection(Spannable, int)
[Selection. setSelection(Spannable text, int index)   Move the cursor to offset index.]


三、public interface Editable的方法
This is the interface for text whose content and markup can be changed (as opposed to immutable text like Strings).

一、    Editable的 delete(int start, int end)  // 删除起点下标为start,重点终点下标为end
 
四、TextUtils
一、public static boolean isEmpty (CharSequence str)
Returns true if the string is null or 0-length.
Parameters
str    the string to be examined
Returns
true if str is null or zero length
五、AlertDialog and AlertDilog.builder



WRITE_SECURE_SETTINGS


六、Preference

WRITE_SECURE_SETTINGS



public Preference findPreference (CharSequence key)  // PreferenceGroup  的方法
Finds a Preference based on its key. If two Preference share the same key (not recommended), the first to appear will be returned (to retrieve the other preference with the same key, call this method on the first preference). If this preference has the key, it will not be returned.
This will recursively search for the preference into children that are also PreferenceGroups.
Parameters
key    The key of the preference to retrieve.
Returns
The Preference with the key, or null.
   
public boolean removePreference (Preference preference) // PreferenceGroup  的方法移除无用的preference
Removes a Preference from this group.
Parameters
preference    The preference to remove.
Returns
Whether the preference was found and removed.


public Intent getIntent ()    // Preference of method
Return the Intent associated with this Preference.
Returns
The Intent last set via setIntent(Intent) or XML.


七、PackageManager
Class for retrieving various kinds of information related to the application packages that are currently installed on the device. You can find this class through getPackageManager().  如PackageManager pm = context.getPackageManager();
如下图:这样的布局
 
布局方法多种,可以完全代码布局,或用xml布局,常用listActivitiy来布局这样界面,
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <TextView android:id="@+id/locale"
    />
    <RadioButton
    />
</RelativeLayout>
用RadioButton 提示当前选中项如果只是让我们去选择哪一项,很容易的可以实现。
实现方法:
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
        for(int i=0; i<l.getCount(); i++){       //
            View view = l.getChildAt(i);
            RadioButton radiaoButton = (RadioButton)view.findViewById(R.id.radio);
            radiaoButton.setChecked(false);
        }
        RadioButton radiaoButton = (RadioButton)v.findViewById(R.id.radio);
        radiaoButton.setChecked(true);
}

但是如果在程序运行的时候就标出系统的语言设置次方法就不通。
Settings语言设置的方法:
   @Override
   protected void onListItemClick(ListView l, View v, int position, long id) {   
       try {
           Loc loc = mLocales[position];
           IActivityManager am = ActivityManagerNative.getDefault();
           Configuration config = am.getConfiguration();
           config.locale = loc.locale;
           config.userSetLocale = true;

           am.updateConfiguration(config);
           BackupManager.dataChanged("com.android.providers.settings");
       } catch (RemoteException e) {
       }
   }
因为在这个方法里面刷新了整个系统,刚刚选中的项,又被刷成未被选中的。
要想标志出系统默认的语言,必须在刷新的时候标志出,然而ListActivity 并没提供访问它ListView的完整方法,它提供getListView().getChildAt(i)只返回了一个null 没有得到预期的view,所有没法访问到RadioButton。

方案一、开始的时候我首选了放弃RadioButton的法案更改为ImageView
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <TextView android:id="@+id/locale"
    />
    <ImageView
    />
</RelativeLayout>
原程序的adapter
int layoutId = R.layout.locale_picker_item;
int fieldId = R.id.locale;
ArrayAdapter<Loc> adapter =
         new ArrayAdapter<Loc>(this, layoutId, fieldId, mLocales);
getListView().setAdapter(adapter);

改用ImageView后的adapter  判断当前的语言设置不通的图片

SimpleAdapter adapter = new SimpleAdapter(
               this,
               this.getData(),
               R.layout.locale_picker_item,
               new String[]{"local", "radio"},
               new int[]{R.id.locale, R.id.radio}
               );
 getListView().setAdapter(adapter);

private List<Map<String,Object>> getData(){
       this.list = new ArrayList<Map<String,Object>>();
       Map<String, Object> map = new HashMap<String, Object>();
       for(int i = 0; i<this.mLocales.length; i++){
           try {
               if(config.locale.equals(loc.locale)){
                   map = new HashMap<String, Object>();
                   map.put("local", this.mLocales[i]);
                   map.put("radio",R.drawable.radio_check);
                   list.add(map);
               }else{
                   map = new HashMap<String, Object>();
                   map.put("local", this.mLocales[i]);
                   map.put("radio",R.drawable.radio_uncheck);
                   list.add(map);
               }
           } catch (RemoteException e) {
           }
       }
       return list;
   }

方案二、自定义MyAdapter extends BaseAdapter

ArrayList<LoaclLanguage> loaclLanguageList = new ArrayList<LoaclLanguage>();
       LoaclLanguage localLanguage = null;
       for(int i=0; i<this.mLocales.length; i++){
           try {
               Loc loc = mLocales[i];
               IActivityManager am = ActivityManagerNative.getDefault();
               Configuration config = am.getConfiguration();
               if(config.locale.equals(loc.locale)){
                   localLanguage = new LoaclLanguage(this.mLocales[i].toString(),true);
               }else{
                   localLanguage = new LoaclLanguage(this.mLocales[i].toString(),false);
               }
               loaclLanguageList.add(localLanguage);
           } catch (RemoteException e) {
           }
       }
       LanguageAdapter adapter = new LanguageAdapter( this,R.layout.locale_picker_item,loaclLanguageList );
setListAdapter( adapter );

class LanguageAdapter extends BaseAdapter {
       private Context context;
       private List<LoaclLanguage> loaclLanguageList;
       private int rowResID;
       public LanguageAdapter(Context context, int rowResID,List<LoaclLanguage> loaclLanguageList ) {
           this.context = context;
           this.rowResID = rowResID;
           this.loaclLanguageList = loaclLanguageList;
       }
       public int getCount() {                        
           return loaclLanguageList.size();
       }
       public Object getItem(int position) {     
           return loaclLanguageList.get(position);
       }
       public long getItemId(int position) {  
           return position;
       }
       public View getView(int position, View convertView, ViewGroup parent) {
           LoaclLanguage loaclLanguage = loaclLanguageList.get(position);
           LayoutInflater inflate = LayoutInflater.from( context );
           View view = inflate.inflate( rowResID, parent, false);
           TextView textView = (TextView)view.findViewById( R.id.locale );
           if( textView != null )
               textView.setText( loaclLanguage.getCity() );
           RadioButton radioButton = (RadioButton)view.findViewById( R.id.radioButton );
           if( radioButton != null )
               radioButton.setChecked(loaclLanguage.getCheck());
           return view;
       }
   }
   class LoaclLanguage {
       private String city = null;
       private boolean checked =false;
       public LoaclLanguage( String city,  boolean checked) {
           this.city = city;
           this.checked = checked;
       }
       public String getCity() {
           return this.city;
       }
       public boolean getCheck() {
           return this.checked;
       }
   }

方案三、自定义MyAdapter extends ArrayAdapter

try {
           IActivityManager am = ActivityManagerNative.getDefault();
           Configuration config = am.getConfiguration();
           defaultLabel = toTitleCase(config.locale.getDisplayLanguage(config.locale));
} catch (RemoteException e) {
            e.printStackTrace();
}
       int layoutId = R.layout.locale_picker_item;
       MyAdapter adapter = new MyAdapter(this, layoutId,mLocales);
       getListView().setAdapter(adapter);

private class MyAdapter extends ArrayAdapter{
        int resource;
        Loc[] list;
        LayoutInflater li;
        
        public MyAdapter(Context context, int textViewResourceId, Loc[] mLocales) {
            super(context, textViewResourceId, mLocales);
            resource = textViewResourceId;
            list = mLocales;
            li = LayoutInflater.from(context);
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
              convertView = li.inflate(resource, null);
              holder = new ViewHolder();
              holder.language = (TextView)convertView.findViewById(R.id.locale);
              holder.defaultButton = (RadioButton)convertView.findViewById(R.id.local_radio_button);
              convertView.setTag(holder);
            }else{
                holder = (ViewHolder)convertView.getTag();
            }
            String label = list[position].toString();
            holder.language.setText(label);
            holder.defaultButton.setChecked(label.equals(defaultLabel));
            return convertView;
        }
   }
   class ViewHolder{
       TextView language;
       RadioButton defaultButton;
   }





Settings里面的 IconPreferenceScreen的构造方法,开始感觉很奇怪 如下
public IconPreferenceScreen(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setLayoutResource(R.layout.preference_icon2);
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.IconPreferenceScreen, defStyle, 0); //奇怪的地方1
        mIcon = a.getDrawable(R.styleable.IconPreferenceScreen_icon);// 奇怪的地方2
 
 }

一直以为是系统自带的 ,后来才发现这奇怪的东西来自于
<resources>
    <declare-styleable name="WifiEncryptionState">
        <attr name="state_encrypted" format="boolean" />
    </declare-styleable>
    
    <declare-styleable name="IconPreferenceScreen">
        <attr name="icon" format="reference" />
    </declare-styleable>
</resources>
完全是自定义的attr 这种自定义的可以用在xml布局中,实现多样化布局

如小例子:
第一部分、
<resources>
    <declare-styleable name="MyView">
        <attr name="textColor" format="color" />
        <attr name="textSize" format="dimension" />
        <attr name="icon" format="reference" />
    </declare-styleable>
</resources>
第二部分、
<LinearLayout
<com.misoo.attr_xml_TypedArray.MyView  
    android:layout_width="fill_parent"   
    android:layout_height="fill_parent"   
    test:textSize="40px"  
    test:textColor="#fff"  
    test:icon="@drawable/icon"
/>  

</LinearLayout>










用到的核心技术:Activitiy 、 MediaPlayer 、Service、SerfaceView、resource资源和AndroidMainfest.xml的配置
Activity和Service是android的
Android应用程序使用Java做为开发语言。aapt工具把编译后的Java代码连同其它应用程序需要的数据和资源文件一起打包到一个Android包文件中,这个文件使用.apk做为扩展名,它是分发应用程序并安装到移动设备的媒介,用户只需下载并安装此文件到他们的设备。单一.apk文件中的所有代码被认为是一个应用程序。
Activity
Activity是为用户操作而展示的可视化用户界面。比如说,一个activity可以展示一个菜单项列表供用户选择,或者显示一些包含说明的照片。一个短消息应用程序可以包括一个用于显示做为发送对象的联系人的列表的activity,一个给选定的联系人写短信的activity以及翻阅以前的短信和改变设置的activity。尽管它们一起组成了一个内聚的用户界面,但其中每个activity都与其它的保持独立。每个都是以Activity类为基类的子类实现。

服务和MediaPlayer
服务没有可视化的用户界面,而是在一段时间内在后台运行。比如说,一个服务可以在用户做其它事情的时候在后台播放背景音乐、从网络上获取一些数据或者计算一些东西并提供给需要这个运算结果的activity使用。每个服务都继承自Service基类。
一个媒体播放器播放播放列表中的曲目是一个不错的例子。播放器应用程序可能有一个或多个activity来给用户选择歌曲并进行播放。然而,音乐播放这个任务本身不应该为任何activity所处理,因为用户期望在他们离开播放器应用程序而开始做别的事情时,音乐仍在继续播放。为达到这个目的,媒体播放器activity应该启用一个运行于后台的服务。而系统将在这个activity不再显示于屏幕之后,仍维持音乐播放服务的运行。
你可以连接至(绑定)一个正在运行的服务(如果服务没有运行,则启动之)。连接之后,你可以通过那个服务暴露出来的接口与服务进行通讯。对于音乐服务来说,这个接口可以允许用户暂停、回退、停止以及重新开始播放。
如同activity和其它组件一样,服务运行于应用程序进程的主线程内。所以它不会对其它组件或用户界面有任何干扰,它们一般会派生一个新线程来进行一些耗时任务(比如音乐回放)。参见下述 进程和线程 。
SerfaceView

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值