先看效果图
![这里写图片描述](https://img-blog.csdn.net/20170712105504004?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvQW5keV9sMQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
技术要点
- 自定义dialog布局
- ListView实现无限滑动
- 使listView可见条目的第二条保持选中状态
只是单纯的写一个demo,实现pickerView的效果,开始没想到用无限滑动来实现,想着滑动时默认是可见条目的第二条是选中的,这样的话滑动到底部选中状态条目的下面位置的条目是没办法选中的,想着再加一个条目点击事件不就可以了,但就是这么简单的需求出问题了 ,滑动选中我是在ListView的滚动监听实现的,但此时在设置条目点击事件无效,哪位大神解决好了,麻烦告知一下
核心代码
ListView lv
private void showDialog() {
final Dialog dialog = new Dialog(MainActivity.this)
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE)
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0))
dialog.setCancelable(true)
dialog.setCanceledOnTouchOutside(true)
dialog.setContentView(R.layout.dialog_contacts)
WindowManager.LayoutParams attributes = dialog.getWindow().getAttributes()
WindowManager windowManager = getWindowManager()
Display display = windowManager.getDefaultDisplay()
attributes.width = display.getWidth()
attributes.height = (int) (display.getHeight() * 0.4)
attributes.gravity = Gravity.BOTTOM
dialog.getWindow().setAttributes(attributes)
dialog.getWindow().setWindowAnimations(R.style.dialog_animation)
lv = (ListView) dialog.getWindow().findViewById(R.id.lv)
TextView tvSure = (TextView) dialog.getWindow().findViewById(R.id.tv_sure)
TextView tvCancle = (TextView) dialog.getWindow().findViewById(R.id.tv_cancel)
final DialogAdapter dialogAdapter = new DialogAdapter()
lv.setAdapter(dialogAdapter)
tvCancle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss()
}
})
tvSure.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
button.setText(contacts.get((int) dialogAdapter.getItemId(selectPos)))
button.setTextColor(getResources().getColor(R.color.colorAccent))
dialog.dismiss()
}
})
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
selectPos = firstVisibleItem + 1
dialogAdapter.notifyDataSetChanged()
}
})
//此方法和setOnScrollListener有冲突,有解决好的大神麻烦告知一下
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
})
//无限循环,默认位置是Integer.MAX_VALUE / 2 位置并位于contacts的第一个元素
lv.setSelection(Integer.MAX_VALUE / 2 - (Integer.MAX_VALUE / 2) % contacts.size())
dialog.show()
}
源码
github