效果如下所示
选择框布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ScrollView
android:background="@color/subjectBackGroundColoe"
android:layout_alignParentTop="true"
android:layout_width="match_parent"
android:layout_height="200dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="第1个"
android:gravity="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="第2个"
android:gravity="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="第3个"
android:gravity="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="第4个"
android:gravity="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="第5个"
android:gravity="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="第6个"
android:gravity="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="第7个"
android:gravity="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="第8个"
android:gravity="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="第9个"
android:gravity="center"/>
</LinearLayout>
</ScrollView>
</RelativeLayout>
布局分析
将最外层的布局,设置为充满整个屏幕,即
android:layout_width=”match_parent”
android:layout_height=”match_parent”
在代码中给最外层的布局,设置一个半透明的背景,以达到弹出选择框的时候,其他区域变暗的效果。
将ScrollView设置为
android:background=”@color/subjectBackGroundColoe”
android:layout_alignParentTop=”true”
android:layout_width=”match_parent”
android:layout_height=”200dp”
设置ScrollView位于弹出框的最顶部,高度为200dp,宽度为填满整个窗体,同时给其设置非透明的背景,这样就可以达到整个屏幕只有顶部部分,而底部半透明的效果,即底部变暗的效果。
代码
private void showSubjectPopupWindow(View view) {//想要选择框在哪个view下面,就把那个view作为参数传递进来
// 一个自定义的布局,作为显示的内容
View contentView = LayoutInflater.from(ctx).inflate(R.layout.subject_select_layout,null);
final PopupWindow popupWindow = new PopupWindow(contentView,
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
//实例化一个ColorDrawable颜色为半透明,已达到变暗的效果
ColorDrawable dw = new ColorDrawable(0xb0000000);
// 如果不设置PopupWindow的背景,无论是点击外部区域还是Back键都无法dismiss弹框
// 我觉得这里是API的一个bug
popupWindow.setBackgroundDrawable(dw);
// 设置好参数之后再show
popupWindow.showAsDropDown(view, 0, 0);
}
在想要显示选择框的地方,调用showSubjectPopupWindow方法即可。
背景变暗的参考链接 http://note.youdao.com/share/?id=e2b11e8a9741bc796b04c82b5267d3f3&type=note