在Dialog佈局中添加ListView

創建ListDialog

public class ListDialog {
    public static void createListDialog(Context context, List<String>list,String title){
        DisplayMetrics metrics=new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(metrics);
        //獲取屏幕寬度
        int width=metrics.widthPixels;
        //dp轉換爲px
        int margin= (int) (10*(context.getResources().getDisplayMetrics().density)+0.5f);
        AlertDialog dialog=new AlertDialog.Builder(context).create();
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        View view=View.inflate(context, R.layout.layout_list_dialog,null);
        TextView tv_title=view.findViewById(R.id.tv_title);
        ListView lv=view.findViewById(R.id.lv);
        tv_title.setText(title);
        ArrayAdapter<String> adapter=new ArrayAdapter<>(context,android.R.layout.simple_list_item_1,list);
        lv.setAdapter(adapter);
        dialog.show();
        dialog.setContentView(view);
        Window window=dialog.getWindow();
        if (window!=null){
            WindowManager.LayoutParams windowParams=window.getAttributes();
            //設置Dialog寬高
            windowParams.height= ViewGroup.LayoutParams.WRAP_CONTENT;
            windowParams.width=width-2*margin;
            window.setAttributes(windowParams);

        }
    }
}

Dialog佈局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <TextView
        android:id="@+id/tv_title"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="@string/app_name"
        android:background="#3399FF"
        android:textColor="#FFFFFF"
        android:gravity="center"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp" />
    <!--關鍵在於將ListView高度定死,雖然這樣寫適配效果很差,但是目前沒有想到更好的辦法了-->
    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="350dp"/>

</LinearLayout>

在Activity中調用

Button button=findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<String>list=new ArrayList<>();
                for (int i=0;i<20;i++){
                    list.add(String.valueOf(i));
                }
                ListDialog.createListDialog(MainActivity.this,list,"DataList");
            }
        });
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章