android自己定義TextView

來源:互聯網
上載者:User

標籤:xtend   技術   pup   type   textview   sed   back   class   drawable   

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;@Overrideprotected 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.