自定义带点击事件spiner控件

一.自定义可点击spiner控件的源码:

package com.myprojrect.android.widget;

import android.content.Context;
import android.content.DialogInterface;
import android.util.AttributeSet;
import android.widget.Spinner;

public class ClickControlledSpinner extends Spinner{
 
 public ClickControlledSpinner(Context context) {   
  super(context);  
 } 
 
 public ClickControlledSpinner(Context context, AttributeSet attrs, int defStyle) { 
        super(context, attrs, defStyle);  
 } 
 
 public ClickControlledSpinner(Context context, AttributeSet attrs) { 
  super(context, attrs);  
 }

  
 /**
  * 实现点击方法
  * */
 private void onClick() {
  if (onClickMyListener != null && isEnabled()) {
   onClickMyListener.onClick();
  }
 }
 
 private OnClickMyListener onClickMyListener; 
     
 /**
 * 注册自定义的点击事件监听
 * Register the click event self-fulfilling listener.
 * @param onClickMyListener
 */ 
 public void setOnClickMyListener(OnClickMyListener onClickMyListener) { 
     this.onClickMyListener = onClickMyListener; 
 }
 
 /**
  * 自定义点击事件监听. Click event self-fulfilling listener.
  */
 public interface OnClickMyListener {
  /**
   * 点击时触发 警告:该方法在非UI线程中执行
   *
   * Triggers when click event occurs. Warning: this method does not run
   * in UI thread.
   */
  public void onClick();
 }
}

二.相关布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">
     <LinearLayout
     android:orientation="horizontal"
     android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center">
    <TextView
     android:id="@+id/user_login_title_tv"
     android:text="@string/recommend_tag"
     android:textSize="@dimen/font_size_4"
   android:textColor="@color/text_channel_item"
   android:textStyle="bold"
   android:paddingLeft="10dip"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"/>
    </LinearLayout>
    <View
     android:layout_marginTop="10dip"
  android:layout_width="fill_parent"
    android:layout_height="2dip"
    android:background="@color/line_color"/>
   <LinearLayout
     android:id="@+id/login_content_view"
     android:orientation="vertical"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:paddingLeft="60dip"
     android:paddingRight="60dip">
   <LinearLayout
       android:orientation="horizontal"
       android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:gravity="center"
      android:paddingTop="15dip">
      <TextView
       android:text="@string/recommend_mobile_phone_tag"
       android:textSize="@dimen/font_size_3"
     android:textColor="@color/text_channel_item"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"/>
      <EditText
       android:id="@+id/recommend_mobile_phone_et"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:singleLine="true"
       android:layout_marginLeft="5dip" 
       android:layout_weight="1"
       android:digits="0123456789+*#"
       android:maxLength="20"
       android:hint="@string/recommend_mobile_phone_hint_tag"
       android:textSize="@dimen/font_size_2"
     android:textColor="@color/text_channel_item"
     android:textCursorDrawable="@null"
       android:background="@drawable/edit_bg"/>
      <ImageView
       android:id="@+id/recommend_add_contact_but"
       android:src="@drawable/btn_add_contact_bg"
       android:layout_marginLeft="5dip"  
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:clickable="true"/>
      </LinearLayout>
      <LinearLayout
       android:orientation="horizontal"
       android:layout_width="fill_parent"
      android:layout_height="wrap_content">
      <TextView
       android:text="@string/recommend_mobile_phone_tag"
       android:textSize="@dimen/font_size_3"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:visibility="invisible"/>
      <TextView
       android:text="@string/recommend_mobile_phone_tip_tag"
       android:textSize="@dimen/font_size_1"
     android:textColor="@color/text_channel_item"
     android:layout_marginLeft="5dip"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"/>
      </LinearLayout>
      <LinearLayout
          android:id="@+id/recommend_message_lay"
       android:orientation="horizontal"
       android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:gravity="center"
      android:paddingTop="15dip">
      <TextView
       android:text="@string/recommend_message_tag"
       android:textSize="@dimen/font_size_3"
      android:textColor="@color/text_channel_item"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"/>


      <com.myprojrect..android.widget.ClickControlledSpinner
       android:id="@+id/recommend_message_spinner_sp"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_weight="1"
       android:spinnerMode="dropdown"
       android:layout_marginLeft="5dip"  
       android:layout_marginTop="5dip"      
       android:popupBackground="@drawable/drop_down"
       android:background="@drawable/spinner_bg"/>


      </LinearLayout>
       <LinearLayout
     android:orientation="horizontal"
     android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_marginTop="15dip"
      android:gravity="center"
      android:weightSum="10">
    <Button
       android:id="@+id/recommend_send_submit_but"
      android:text="@string/recommend_send_tag"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
     android:textSize="@dimen/font_size_3"
     android:layout_gravity="center"
       style="@style/CustomButton"/>
      <View
       android:layout_width="0dip"
       android:layout_height="0dip"
       android:layout_weight="1"/>
      <Button
       android:id="@+id/recommend_cancel_but"
      android:text="@string/recommend_cancel_tag"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
     android:textSize="@dimen/font_size_3"
     android:layout_gravity="center"
       style="@style/CustomButton"/>
     </LinearLayout>
 </LinearLayout>
</LinearLayout>

 

三.调用的对话框

 /**
  * 显示下拉列表的对话框
  *
  */
 public static void showReCommendDailog(final Activity context, final String contentID, final String contentName) {
  final Dialog dialog = createLoginDialog(context,R.layout.recommend_layout);
  final EditText mobile_phone_et = (EditText) dialog.findViewById(R.id.recommend_mobile_phone_et);
  final ClickControlledSpinner recommend_message_spinner_sp = (ClickControlledSpinner) dialog.findViewById(R.id.recommend_message_spinner_sp);
  final View recommend_add_contact_but = dialog.findViewById(R.id.recommend_add_contact_but);
   final Button recommend_send_submit_but = (Button) dialog.findViewById(R.id.recommend_send_submit_but);
  final Button recommend_cancel_but = (Button) dialog.findViewById(R.id.recommend_cancel_but);
  final String [] recommendDataStrings = context.getResources().getStringArray(R.array.recommended_items);
  recommend_message_spinner_sp.setAdapter(new ArrayAdapter<String>(context,  R.layout.setting_spinner_item,recommendDataStrings));
 

   recommend_message_spinner_sp.setOnClickMyListener(new OnClickMyListener() {
   
   @Override
   public void onClick() {
    //关闭输入法
    InputMethodManager imm = ((InputMethodManager)context.getSystemService(context.INPUT_METHOD_SERVICE));
     imm.hideSoftInputFromWindow(mobile_phone_et.getWindowToken(), 0);
   }
  });
    
  recommend_message_spinner_sp.setOnItemSelectedListener(new OnItemSelectedListener() {

   @Override
   public void onItemSelected(AdapterView<?> parent, View view,
     int position, long id) {
     
    //关闭输入法
    InputMethodManager imm = ((InputMethodManager)context.getSystemService(context.INPUT_METHOD_SERVICE));
     imm.hideSoftInputFromWindow(mobile_phone_et.getWindowToken(), 0);
     
    }
   
   @Override
   public void onNothingSelected(AdapterView<?> parent) {
    //关闭输入法
    InputMethodManager imm = ((InputMethodManager)context.getSystemService(context.INPUT_METHOD_SERVICE));
     imm.hideSoftInputFromWindow(mobile_phone_et.getWindowToken(), 0);
   }
  });
  
  onGetContactReturn = new MyRunnable(){
   @Override
   public void run(String data) {
    if(data == null)return;
    mobile_phone_et.setText(data);
   }
  };
  recommend_add_contact_but.setOnClickListener(
    new OnClickListener() {
     @Override
     public void onClick(View v) {
      Intent intent = new Intent(Intent.ACTION_PICK);
      intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
      context.startActivityForResult(intent, PICK_CONTACT);
     }
    });
  dialog.setOnDismissListener(new OnDismissListener() {
   @Override
   public void onDismiss(DialogInterface dialog) {
    onGetContactReturn = null;
   }
  });
  
  recommend_send_submit_but.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    final String phoneStr = mobile_phone_et.getText().toString().trim();
    String contentTemp = recommend_message_spinner_sp.getSelectedItem().toString();
    if (contentTemp.equals(recommendDataStrings[1])) {
     contentTemp = recommend_self_message_et.getText().toString().trim();
    }
    final String contenStr = contentTemp;
    if (TextUtils.isEmpty(phoneStr)) {
     ToastUtil.showToast(context, R.string.dialog_recommend_empty_tip);
    } else if (TextUtils.isEmpty(contenStr)) {
     ToastUtil.showToast(context, R.string.dialog_recommend_content_empty_tip);
    } else {
     if (!isChinaTelecomNumber(phoneStr)) {
      ToastUtil.showToast(context, context.getString(R.string.dialog_recommend_phone_err, phoneStr));
      return;
     }
     final Dialog waittingDialog = DialogUtil.getNetDialog(context,false);
     waittingDialog.show();
     new Thread() {
      @Override
      public void run() {
       final boolean isSuccess = DataSaxParser
         .getInstance(context).recommendedContent(
           contentID, null, phoneStr,
           contenStr);
       context.runOnUiThread(new Runnable() {
        
        @Override
        public void run() {
         if (waittingDialog != null) {
          waittingDialog.dismiss();
         }
         if (isSuccess) {
          ToastUtil.showToast(context,
            R.string.recommeded_success);
          dialog.dismiss();
         } else {
          ToastUtil.showToast(context,   R.string.recommend_failure);
          }
        }
       });
      }

     }.start();
    }
   }

  });
  recommend_cancel_but.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    dialog.dismiss();
   }
  });
  dialog.show();
 }

四.总结:

1.在自定义ClickControlledSpinner里面声明一个接口

 /**
  * 自定义点击事件监听. Click event self-fulfilling listener.
  */
 public interface OnClickMyListener {
  /**
   * 点击时触发 警告:该方法在非UI线程中执行
   *
   * Triggers when click event occurs. Warning: this method does not run
   * in UI thread.
   */
  public void onClick();
 }

2.在自定义ClickControlledSpinner里面定义注册一个自定义的点击事件监听事件(使用一个回调函数):

 private OnClickMyListener onClickMyListener; 
     
 /**
 * 注册自定义的点击事件监听
 * Register the click event self-fulfilling listener.
 * @param onClickMyListener
 */ 
 public void setOnClickMyListener(OnClickMyListener onClickMyListener) { 
     this.onClickMyListener = onClickMyListener; 
 }

3.在自定义ClickControlledSpinner里面实现接口OnClickMyListener里面的 onClick()方法:

 /**
  * 实现点击方法
  * */
 private void onClick() {
  if (onClickMyListener != null && isEnabled()) {
   onClickMyListener.onClick();
  }
 }

4.在xml文件中引入自定义spinner控件:

      <com.myprojrect..android.widget.ClickControlledSpinner 
       android:id="@+id/recommend_message_spinner_sp"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_weight="1"
       android:spinnerMode="dropdown"
       android:layout_marginLeft="5dip"  
       android:layout_marginTop="5dip"      
       android:popupBackground="@drawable/drop_down"
       android:background="@drawable/spinner_bg"/>

5.在代码中引用自定义spinner控件:

final ClickControlledSpinner recommend_message_spinner_sp = (ClickControlledSpinner) dialog.findViewById(R.id.recommend_message_spinner_sp);

6.在代码中调用自定义spinner控件的自定义点击事件:

   recommend_message_spinner_sp.setOnClickMyListener(new OnClickMyListener() {
   
   @Override
   public void onClick() {
    //可以根据需要实现相关操作

    //关闭输入法
    InputMethodManager imm = ((InputMethodManager)context.getSystemService(context.INPUT_METHOD_SERVICE));
     imm.hideSoftInputFromWindow(mobile_phone_et.getWindowToken(), 0);

   }
  });

经过以上六个步骤就可以自定义一个点击事件了。
Spinner(下拉列表)是Android中常用的用户界面控件,用于显示一个可选择的列表,用户可以通过点击下拉箭头来展开选择项。下面是Spinner的详细用法: 1. 在XML布局文件中添加Spinner控件: ```xml <Spinner android:id="@+id/spinner" android:layout_width="match_parent" android:layout_height="wrap_content" /> ``` 2. 在Activity或Fragment中找到Spinner控件,并为其设置适配器(Adapter): ```java Spinner spinner = findViewById(R.id.spinner); // 创建一个适配器 ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, data); // 设置下拉列表的样式 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // 将适配器设置给Spinner spinner.setAdapter(adapter); ``` 在上述代码中,我们首先获取到Spinner控件的实例。然后,创建一个适配器(这里使用了ArrayAdapter),并传入上下文、下拉列表的样式和数据源(data)。接下来,我们设置下拉列表的样式为`android.R.layout.simple_spinner_dropdown_item`,这是一个系统提供的默认下拉列表布局。最后,将适配器设置给Spinner。 3. 处理Spinner的选择事件: ```java spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // 处理选择项的事件 String selectedItem = parent.getItemAtPosition(position).toString(); Toast.makeText(MainActivity.this, "Selected: " + selectedItem, Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { // 当没有选择项时的处理 } }); ``` 在上述代码中,我们使用`setOnItemSelectedListener()`方法为Spinner设置一个选择事件监听器。当用户选择一个选项时,会触发`onItemSelected()`方法,我们可以在该方法中处理选择项的事件。如果没有选择项(例如初次加载Spinner时),则会触发`onNothingSelected()`方法。 以上就是Spinner的基本用法。你可以根据自己的需求自定义适配器和下拉列表的样式,以及添加更多的事件处理逻辑。 希望对你有所帮助!如果还有其他问题,请随时问我。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值