Android 自定義文本 選擇器 PickerView

自定義文本選擇器
PickerView.png
調(diào)用showPopupWindow 傳入有一個View 上下文Context轻庆,文本字符串String[]

<code>

        String[] strings=new String[new Random().nextInt(50)+10];
        for (int i = 0; i <strings.length; i++) {
            strings[i]="元素"+i;
        }
        pickerViewPop.showPopupWindow(statistics_element, BaseApplication.getInstance().getContext(),strings
        ).setOnPickerViewListen(new PickerViewPop.OnPickerViewListen() {
            @Override
            public void OnConfirm(int index, String text) {
                statistics_element.setText(text+"");
            }
        });

</code>

PopupWindow 顯示

<code>

    import android.content.Context;
    import android.graphics.drawable.BitmapDrawable;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.MotionEvent;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.PopupWindow;
    import android.widget.Scroller;
    import android.widget.TextView;

    import com.app.framework.R;

    public class PickerViewPop {

        private PopupWindow popupWindow;


        public PickerViewPop showPopupWindow(View view, Context context, String[] str) {
            // 一個自定義的布局,作為顯示的內(nèi)容
            View contentView = LayoutInflater.from(context).inflate(
                    R.layout.picker_view, null);
            // 設(shè)置按鈕的點擊事件
            setContentView(contentView, str);

            popupWindow = new PopupWindow(contentView,
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

            popupWindow.setTouchable(true);

            popupWindow.setTouchInterceptor(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {

                    Log.i("mengdd", "onTouch : ");

                    return false;
                    // 這里如果返回true的話,touch事件將被攔截
                    // 攔截后 PopupWindow的onTouchEvent不被調(diào)用,這樣點擊外部區(qū)域無法dismiss
                }
            });

            // 如果不設(shè)置PopupWindow的背景呼畸,無論是點擊外部區(qū)域還是Back鍵都無法dismiss彈框
            popupWindow.setBackgroundDrawable(new BitmapDrawable());

            // 設(shè)置好參數(shù)之后再show
            popupWindow.showAsDropDown(view);

    
            return this;
        }
        public interface OnPickerViewListen {
            void OnConfirm(int index, String text);
        }

        private OnPickerViewListen onPickerViewListen;

        public void setOnPickerViewListen(OnPickerViewListen onPickerViewListen) {
            this.onPickerViewListen = onPickerViewListen;
        }

        public void setContentView(View contentView, final String[] str) {
            final PickerView pickerView = (PickerView) contentView.findViewById(R.id.picker_view);
            TextView confirm = (TextView) contentView.findViewById(R.id.confirm);
            confirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(onPickerViewListen!=null){
                        int index=pickerView.getSelectedTextIndex();
                        onPickerViewListen.OnConfirm(index,str[index]);
                        popupWindow.dismiss();
                    }
                }
            });
            pickerView.setTextString(str);
        }
    }

</code>

自定義的文本選擇器

<code>

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.app.framework.utils.DipToPx;

import java.math.BigDecimal;


/**
 * 滾動選擇器
 * 布局設(shè)置的高度必須能被weight 整除里初, 否則會有偏差
 */
public class PickerView extends View {
    private String TAG = "PickerView";
    /**
     * 數(shù)據(jù)
     */
    private String[] strings = new String[]{};
    /**
     * 控件寬度
     */
    private int mViewWidth;

    /**
     * 控件高度
     */
    private int mViewHeight;

    /**
     * 文本畫筆
     */
    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    /**
     * 中間線畫筆
     */
    private Paint mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    /**
     * 中間線邊距
     */
    private int linePading = 10;

    /**
     * 繪制文字大小
     */
    private int textSezi = 14;
    /**
     * 中間線的厚度
     */
    private float lineWidth = 1;
    /**
     * 選中的顏色
     */
    private int checkedColor = 0xFFFF0000;
    /**
     * 未選中的顏色
     */
    private int notCheckedColor = 0xFF000000;

    /**
     * 看見的條目數(shù)量,必須奇數(shù)
     */
    private int weight = 5;

    private int itemHeight;
    /**
     * 當(dāng)前的位置
     */
    private int index;

    /**
     * 默認(rèn)選中中間位置
     */
    private int defaultIndex = -1;


    private int checkedIndex = (weight - 1) / 2;
    private float mMoveLen;

    public PickerView(Context context) {
        super(context);
        init();
    }

    /**
     * 設(shè)置默認(rèn)選中位置
     */
    public void setDefaultIndex(int defaultIndex) {
        this.defaultIndex = defaultIndex;
    }

    public PickerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();

    }

    public PickerView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mViewHeight = getMeasuredHeight();
        mViewWidth = getMeasuredWidth();
        itemHeight = mViewHeight / weight;


        if (defaultIndex == -1) {
            /**設(shè)置默認(rèn)中間位置*/
            defaultIndex = strings.length / 2;
        }

        mMoveLen = -itemHeight * (defaultIndex - (weight - 1) / 2);
        this.index = defaultIndex;
    }

    /**
     * 設(shè)置整個控件可視條目數(shù)量
     */
    public void setWeight(int weight) {
        this.weight = weight;
    }

    /**
     * 獲取選中的位置
     */
    public int getSelectedTextIndex() {
        return index;
    }

    /**
     * 設(shè)置text文本數(shù)組
     */
    public void setTextString(String[] strings) {
        this.strings = strings;
    }

    private void setSelectedText(int index) {
        this.index = index;
    }

    /**
     * 設(shè)置繪制文字大小
     */
    public void setTextSezi(int textSezi) {
        this.textSezi = textSezi;
    }

    /**
     * 設(shè)置繪制中間線邊距
     */
    public void setLinePading(int linePading) {
        this.linePading = linePading;
    }


    /**
     * 設(shè)置中間線的厚度
     */
    public void setLineWidth(float lineWidth) {
        this.lineWidth = lineWidth;
    }

    /**
     * 設(shè)置選中時的文本顏色
     */
    public void setCheckedColor(int checkedColor) {
        this.checkedColor = checkedColor;
    }

    /***設(shè)置未選中時的文本顏色*/
    public void setNotCheckedColor(int notCheckedColor) {
        this.notCheckedColor = notCheckedColor;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        /**繪制文字*/
        drwaText(canvas);
        /**繪制中間線*/
        drwaLine(canvas);

    }

    /**
     * 繪制文字
     *
     * @param canvas
     */
    private void drwaText(Canvas canvas) {
        for (int i = 0; i < strings.length; i++) {
            /**繪制可視范圍文本*/
            if (i + weight -1 > index && i - weight+1 < index) {

                if (i == index) {
                    mPaint.setColor(checkedColor);
               
                } else {
                    mPaint.setColor(notCheckedColor);
                }

                Paint.FontMetrics metrics = mPaint.getFontMetrics();
                float textHeight = metrics.descent; //文字高度
                canvas.drawText(strings[i], mViewWidth / 2, itemHeight * (i + 1) - itemHeight / 2 + mMoveLen + textHeight, mPaint);
            }
        }
    }

    /**
     * 繪制中間線
     */
    private void drwaLine(Canvas canvas) {
        int pading = DipToPx.dip2px(linePading);
        canvas.drawLine(pading, itemHeight * checkedIndex, getRight() - pading, itemHeight * checkedIndex, mLinePaint);
        canvas.drawLine(pading, itemHeight * (checkedIndex + 1), getRight() - pading, itemHeight * (checkedIndex + 1), mLinePaint);
    }


    /**
     * 初始化畫筆
     */
    private void init() {
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setTextAlign(Paint.Align.CENTER);//繪制文本橫向居中
        mPaint.setTextSize(DipToPx.dip2px(textSezi));


        mLinePaint.setStyle(Paint.Style.FILL);
        mLinePaint.setTextAlign(Paint.Align.CENTER);
        mLinePaint.setStrokeWidth(lineWidth);

    }

    /**
     * 更新畫筆參數(shù)
     */
    public void updatePaint() {
        init();
        invalidate();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                doDown(event);
                break;
            case MotionEvent.ACTION_MOVE:
                doMove(event);
                break;
            case MotionEvent.ACTION_UP:
                doUp(event);
                break;
        }
        return true;
    }

    private void doUp(MotionEvent event) {
        float indexes = mMoveLen / itemHeight;

        /**四舍五入 來判定離哪個位置較近*/
        BigDecimal dex = new BigDecimal(indexes).setScale(0, BigDecimal.ROUND_HALF_UP);
        float newIndex = dex.floatValue();
        mMoveLen = newIndex * itemHeight;
        int location;
          /*限制角標(biāo)0的移動范圍*/
        if (newIndex >= checkedIndex + 1) {
            mMoveLen = checkedIndex * itemHeight;

        }
        /*限制最后一個單位的移動  移動范圍*/
        if (newIndex <= -(strings.length - checkedIndex - 1)) {
            mMoveLen = -((strings.length - checkedIndex - 1) * itemHeight);
        }
        //  Log.i("newIndex",newIndex+"");
        /**防止選中角標(biāo)越界*/
        if (newIndex >= 0) {
            location = (int) (checkedIndex - newIndex);
            if (newIndex >= checkedIndex + 1) {
                location = 0;
            }
        } else {
            location = (int) (Math.abs(newIndex) + checkedIndex);
            if (location > strings.length - 1) {
                location = strings.length - 1;
            }
        }
        /**滑動停止的時候設(shè)置當(dāng)前選中的 是第幾個*/
        setSelectedText(location);
        invalidate();
    }


    private void doMove(MotionEvent event) {

        int location;
        mMoveLen += (event.getY() - mLastDownY);
        mLastDownY = event.getY();
        float indexes = mMoveLen / itemHeight;
        /**四舍五入 來判定離哪個位置較近*/
        BigDecimal dex = new BigDecimal(indexes).setScale(0, BigDecimal.ROUND_HALF_UP);
        float newIndex = dex.floatValue();


        /**防止選中角標(biāo)越界*/
        if (newIndex >= 0) {
            location = (int) (checkedIndex - newIndex);
            if (newIndex >= checkedIndex + 1) {
                location = 0;
            }
        } else {
            location = (int) (Math.abs(newIndex) + checkedIndex);
            if (location > strings.length - 1) {
                location = strings.length - 1;
            }
        }
        setSelectedText(location);
        invalidate();
    }

    private float mLastDownY;

    private void doDown(MotionEvent event) {
        mLastDownY = event.getY();
    }

}

</code>

布局文件 picker_view

<code>

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent">
        <com.app.framework.widget.pickerView.PickerView
            android:background="@color/white"
            android:id="@+id/picker_view"
            android:layout_width="100dp"
            android:layout_height="200dp" />
        <TextView
            android:textColor="#111111"
            android:id="@+id/confirm"
            android:gravity="center"
            android:text="確定"
            android:textSize="14sp"
            android:layout_width="100dp"
            android:layout_height="30dp" />
    </LinearLayout>

</code>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末锅睛,一起剝皮案震驚了整個濱河市疚膊,隨后出現(xiàn)的幾起案子义辕,更是在濱河造成了極大的恐慌,老刑警劉巖寓盗,帶你破解...
    沈念sama閱讀 221,273評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件灌砖,死亡現(xiàn)場離奇詭異,居然都是意外死亡傀蚌,警方通過查閱死者的電腦和手機(jī)基显,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,349評論 3 398
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來喳张,“玉大人续镇,你說我怎么就攤上這事∠浚” “怎么了?”我有些...
    開封第一講書人閱讀 167,709評論 0 360
  • 文/不壞的土叔 我叫張陵制跟,是天一觀的道長舅桩。 經(jīng)常有香客問我,道長雨膨,這世上最難降的妖魔是什么擂涛? 我笑而不...
    開封第一講書人閱讀 59,520評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮聊记,結(jié)果婚禮上撒妈,老公的妹妹穿的比我還像新娘。我一直安慰自己排监,他們只是感情好狰右,可當(dāng)我...
    茶點故事閱讀 68,515評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著舆床,像睡著了一般棋蚌。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上挨队,一...
    開封第一講書人閱讀 52,158評論 1 308
  • 那天谷暮,我揣著相機(jī)與錄音,去河邊找鬼盛垦。 笑死湿弦,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的腾夯。 我是一名探鬼主播颊埃,決...
    沈念sama閱讀 40,755評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼赌蔑,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了竟秫?” 一聲冷哼從身側(cè)響起娃惯,我...
    開封第一講書人閱讀 39,660評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎肥败,沒想到半個月后趾浅,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,203評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡馒稍,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,287評論 3 340
  • 正文 我和宋清朗相戀三年皿哨,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片纽谒。...
    茶點故事閱讀 40,427評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡证膨,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出鼓黔,到底是詐尸還是另有隱情央勒,我是刑警寧澤,帶...
    沈念sama閱讀 36,122評論 5 349
  • 正文 年R本政府宣布澳化,位于F島的核電站崔步,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏缎谷。R本人自食惡果不足惜井濒,卻給世界環(huán)境...
    茶點故事閱讀 41,801評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望列林。 院中可真熱鬧瑞你,春花似錦、人聲如沸希痴。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,272評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽润梯。三九已至过牙,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間纺铭,已是汗流浹背寇钉。 一陣腳步聲響...
    開封第一講書人閱讀 33,393評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留舶赔,地道東北人扫倡。 一個月前我還...
    沈念sama閱讀 48,808評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親撵溃。 傳聞我的和親對象是個殘疾皇子疚鲤,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,440評論 2 359

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,264評論 25 707
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn)缘挑,斷路器集歇,智...
    卡卡羅2017閱讀 134,693評論 18 139
  • 內(nèi)容抽屜菜單ListViewWebViewSwitchButton按鈕點贊按鈕進(jìn)度條TabLayout圖標(biāo)下拉刷新...
    皇小弟閱讀 46,784評論 22 665
  • ¥開啟¥ 【iAPP實現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程,因...
    小菜c閱讀 6,440評論 0 17
  • S 先生语淘、P先生诲宇、Q先生他們知道桌子的抽屜里有16張撲克牌:紅桃A、Q惶翻、4 黑桃J姑蓝、8、4吕粗、2纺荧、7、3 草花K颅筋、Q...
    博格體閱讀 1,280評論 0 0