1. 程式人生 > >Android使用wheelView實現簡單類似ios PickerView選擇器效果

Android使用wheelView實現簡單類似ios PickerView選擇器效果

在專案中匯入wheelView檔案

佈局檔案:wheel_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
    <com.example.secretwang.myapplication.WheelView
android:id="@+id/wheel_view_wv" android:layout_width="150dp" android:layout_height="200dp" /> <com.example.secretwang.myapplication.WheelView android:id="@+id/wheel_view_wv2" android:layout_width="150dp" android:layout_height="200dp" /> </LinearLayout>
在activity中呼叫
private static final String TAG 
= MainActivity.class.getSimpleName(); private static final String[] shoushu = new String[]{"1手", "2手", "3手", "4手", "5手","6手","7手","8手","9手","10手","11手","12手","13手","14手","15手","16手","17手","18手","19手","20手" }; private static final String[] xiangmu = new String[] {"美原油","恆生指數"};
private WheelView wv
; private WheelView wv2; private int number; private int category;
//    跳轉設定介面
setBtn.setOnClickListener(new View.OnClickListener() {
           @Override
public void onClick(View v) {
               View outerView = LayoutInflater.from(MainActivity.this).inflate(R.layout.wheel_view, null);
               wv = (WheelView) outerView.findViewById(R.id.wheel_view_wv);
               wv.setOffset(2);
               wv.setItems(Arrays.asList(shoushu));
//     儲存上次選擇的手數
wv.setSeletion(number);
               wv.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
                   @Override
public void onSelected(int selectedIndex, String item) {
                       Log.d(TAG, "[Dialog]selectedIndex: " + selectedIndex + ", item: " + item);
                       shouTxt.setText(item);
                       number=selectedIndex-2;
                   }
               });
               wv2 = (WheelView) outerView.findViewById(R.id.wheel_view_wv2);
               wv2.setOffset(2);
               wv2.setItems(Arrays.asList(xiangmu));
               wv2.setSeletion(category);
               wv2.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
                   @Override
public void onSelected(int selectedIndex, String item1) {
                       Log.d(TAG, "[Dialog]selectedIndex: " + selectedIndex + ", item: " + item1);
                       nametextView.setText(item1);
                       category=selectedIndex-2;
                   }
               });
               new AlertDialog.Builder(MainActivity.this)
                       .setTitle("設定您委託的產品型別和手數")
                       .setView(outerView)
                       .setPositiveButton("確定", null)
                       .show();
           }
       });
效果圖: