效果图如下:
添加依赖
implementation 'com.weigan:loopView:0.1.2'
新建一个WheelViewDialog类, 代码如下
public class WheelViewDialog extends Dialog{ private LoopView loopView; private Button btn_ok; private Button btn_cancle; private OnSelectedListener listener; private ArrayListstringArrayList = new ArrayList<>(); private int position = 0; public WheelViewDialog(Context context, ArrayList arrayList) { super(context,R.style.alert_dialog); stringArrayList = arrayList; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dialog_view); setCanceledOnTouchOutside(false);//设置显示dialog后,触屏屏幕不会使dialog消失 loopView = findViewById(R.id.loopView); btn_ok = findViewById(R.id.btn_ok); btn_cancle = findViewById(R.id.btn_cancle); // 设置原始数据 loopView.setItems(stringArrayList); loopView.setNotLoop(); // 滚动监听// loopView.setListener(new AdapterView.OnItemSelectedListener() {// @Override// public void onItemSelected(int index) {// if (!TextUtils.isEmpty( stringArrayList.get( index) ) ){// Toast.makeText(getContext() ,"选择了" + stringArrayList.get( index) , Toast.LENGTH_SHORT).show();// position = index;//存储选择的位序// }// }// }); loopView.setListener(new OnItemSelectedListener() { @Override public void onItemSelected(int i) { if (!TextUtils.isEmpty( stringArrayList.get( i) ) ){ Toast.makeText(getContext() ,"选择了" + stringArrayList.get( i) , Toast.LENGTH_SHORT).show(); position = i;//存储选择的位序 } } }); btn_ok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (listener!=null){ if (!TextUtils.isEmpty( stringArrayList.get( position) ) ){ listener.getData( stringArrayList.get( position) ); } } dismiss(); } }); btn_cancle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dismiss(); } }); } public interface OnSelectedListener{ void getData(String data); } public void setOnSelectedListener(OnSelectedListener listener){ this.listener = listener; }}
新建 dialog_view.xml文件, 代码如下:
背景图片是这个:
然后就可以在需要调用的地方调用了
比如点击一个按钮, 弹出dialog, 示例代码:
public class DialogActivity extends AppCompatActivity { private Button showDialogBtn; private ArrayListstringArrayList = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dialog); showDialogBtn = findViewById(R.id.act_show_dialog_btn); for (int i = 0; i < 15; i++) { stringArrayList.add("item " + i); } showDialogBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showDialog(); } }); } private void showDialog() { WheelViewDialog dialog = new WheelViewDialog( DialogActivity.this, stringArrayList ); dialog.setOnSelectedListener(new WheelViewDialog.OnSelectedListener() { @Override public void getData(String data) { Toast.makeText(DialogActivity.this, ""+data, Toast.LENGTH_SHORT).show(); } }); dialog.show(); }}
ok完成