public class MyDialog extends Dialog {
private ListAdapter listAdapter;
private ItemClickListener itemClickListener;
// style引用style样式
public MyDialog(Context context, int width, int height, int style, final ItemClickListener listener) {
super(context, style);
this.itemClickListener = listener;//暴露给外界的接口
View view = View.inflate(getContext(),R.layout.dialog_layout,null);
ListView listView = view.findViewById(R.id.list_view);
List list = new ArrayList<>();
list.add(“全部”);
list.add(“未分组”);
list.add(“生活”);
《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》
list.add(“学习”);
list.add(“工作”);
// 使用ArrayAdapter适配器
listAdapter = new ArrayAdapter<>(context,
android.R.layout.simple_list_item_1, android.R.id.text1, list);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String kind = (String) listAdapter.getItem(i);
if(itemClickListener != null){
itemClickListener.onClick(kind);
}
}
});
setContentView(view);
Window window = getWindow();
WindowManager.LayoutParams params = window.getAttributes();
params.gravity = Gravity.START;
params.width = 500;
window.setAttributes(params);//通过window来设置窗口的位置,Start就是屏幕左侧,设置宽度为500px
}
//自定义接口
interface ItemClickListener{
void onClick(String s);
}
}
布局文件代码如下:
<?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView xmlns:android=“http://schemas.android.com/apk/res/android”
android:layout_width=“160dp”
android:layout_height=“match_parent”
xmlns:app=“http://schemas.android.com/apk/res-auto”
app:cardCornerRadius=“10dp”
app:cardElevation=“0dp”
app:cardBackgroundColor="#ffffff">
<RelativeLayout
android:layout_width=“160dp”
android:layout_height=“match_parent”>
<TextView
android:id="@+id/title"
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:text=“便签分组”
android:textSize=“17sp”
android:layout_centerHorizontal=“true”
android:gravity=“center”
android:layout_marginTop=“20dp”
android:layout_marginBottom=“20dp”/>
<View
android:layout_width=“match_parent”
android:layout_height=“1dp”
android:layout_below="@+id/title"
android:background="#000000"/>
<ListView
android:id="@+id/list_view"
android:layout_width=“match_parent”
android:layout_height=“match_parent”
android:layout_below="@+id/title"/>
</androidx.cardview.widget.CardView>