1. 程式人生 > >android自己定義TextView

android自己定義TextView

position 發生 () ava save set data this 是否

Android控件中的TextView控件僅僅有一個輸入框。可是為了用於的操作方便我們應該實現一些功能:

1. 能夠直接將內容刪除的功能button

2. 可以記錄用戶曾經輸入的數據,同一時候可以將數據通過下拉顯示,點擊的時候實現輸入

先上圖:

下拉的圖片沒有做。所以和刪除的圖片使用同一個了,同誌們能夠直接在xml文件裏更換即可了

技術分享技術分享

分析:

肯定要使用自己定義view來實現的。我們知道自己定義view大概能夠分為三類:自繪控件,組合控件,繼承控件,我們這裏是要進行增強的textView的功能。所以我這裏使用的

是組合控件的方式來進行實現

既然使用組合控件,那麽我們就來看看究竟要使用什麽控件來組合呢:

1. 當中一個必須是textView了

2. 下拉的那兩個button是什麽。當然是imageView了

3. 另一個下拉列表,。

。。。那就使用popwindow了

思路:

1. 怎樣實現直接刪除用戶的輸入

使用addTextChangedListener監聽textView內容的變化的時間依據內容的變化進行確定是否顯示刪除button,同一時候綁定刪除button的點擊事件

2.怎樣實現下拉顯示用戶輸入過的數據,以及選中的時候實現輸入

我們通過下拉button的點擊進行確定popwindow窗體的顯示,在popwindow的界面有一個listview,在這個listview的adpater中進行綁定條目的點擊事件

那麽我們在adapter中綁定的事件,怎樣控制整個控件的功能輸入呢,這裏就是用handler了,在創建adapter的時候將handler傳遞過去,

然後當點擊事件發生的時候我們使用handler進行send消息即可了,當然我們在send消息的時候將當前點擊的數據傳遞過來即可了

上代碼:

1. 控件主體代碼

/**
 * 自己定義的控件,自帶刪除的button,下拉button
 * @author zcs
 * */
public class EditTextClearSelect extends FrameLayout {
	
	private EditText editText;  //顯示的editText輸入框
    private ImageButton clearImageButton;  //顯示的用於進行刪除editText中內容的button
    private ImageButton selectImageButton;  //顯示的用於下拉editText中內容的button
	
    //PopupWindow對象  ,用於已下拉形式顯示數據
    private PopupWindow selectPopupWindow= null;  
    //自己定義Adapter  
    private ECS_OptionsAdapter optionsAdapter = null;  
    //下拉框選項數據源  
    private ArrayList<String> datas = new ArrayList<String>();   
    //下拉框依附組件 
    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();   
    }  
    
	 /**
     * 初始化,包含添加刪除button。下拉button
     */
    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); //刪除button
        selectImageButton = (ImageButton) view.findViewById(R.id.select_id); //下拉button
        
        //當點擊刪除button的會後將輸入框數據清空
        clearImageButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                editText.setText("");
            }
        });
        //依據輸入框中的內容。決定是否顯示刪除button
        editText.addTextChangedListener(new TextWatcher(){
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                	//輸入框有內容,顯示button
                	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組件,設置下拉button的功能
        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;
    }
     
    /**
     * 獲得消除button
     * @return
     */
    public ImageButton getClearImageButton(){
        return this.clearImageButton;
    }
	
    //設置下拉列表中的選項值
    public void setOptionsValue(ArrayList<String> 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<String> list = new ArrayList<String>();   
	    private Context context = null;   
	    //傳遞過來的hanler,用於進行通知操作(這裏是通知自己定義的view要繼續改動editText中的數據)
	    private Handler handler;
	    
	    public ECS_OptionsAdapter(Context context,Handler handler,ArrayList<String> 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<String>(Arrays.asList(selectDatas.split(","))) );
		
	}

ok搞定

源代碼下載


android自己定義TextView