本文共 3342 字,大约阅读时间需要 11 分钟。
自定义对话框AlertDialog
效果预览:
xml布局文件
Java代码:
private void alertDialog(String message) { final AlertDialog dialog = new AlertDialog.Builder(this).create(); dialog.show(); //注意:必须在window.setContentView之前show Window window = dialog.getWindow(); window.setContentView(R.layout.alert_dialog); TextView dialogMessage = (TextView) window.findViewById(R.id.tv_alert_dialog_message); dialogMessage.setText(message); TextView yesButton = (TextView) window.findViewById(R.id.tv_alert_dialog_yes); //点击确定按钮让对话框消失 yesButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } });}
需要注意的是 dialog.show() 必须在setContentView之前调用,否则会报错。
效果图
AlertDialog的总布局
alert dialog addbook.xml
ListView的条目布局
item listview categroy.xml
封装的工具类AlertDialogUtils
package com.cachecats.oldbook.utils;import android.app.AlertDialog;import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.ListAdapter;import android.widget.ListView;import android.widget.TextView;import com.cachecats.oldbook.R;import org.w3c.dom.Text;/** * Created by Administrator on 2016/8/5. */public class AlertDialogUtils { /** * 弹出自定义样式的AlertDialog * @param context 上下文 * @param title AlertDialog的标题 * @param tv 点击弹出框选择条目后,要改变文字的TextView * @param args 作为弹出框中item显示的字符串数组 */ public static void showAlertDialog(Context context,String title, final TextView tv, final String[] args){ AlertDialog.Builder builder = new AlertDialog.Builder(context); final AlertDialog dialog = builder.create(); dialog.show(); View view = LayoutInflater.from(context).inflate(R.layout.alert_dialog_addbook, null); TextView tvTitle = (TextView) view.findViewById(R.id.tv_title_alert_dialog_addbook); ListView list = (ListView)view.findViewById(R.id.lv_alert_dialog_addbook); tvTitle.setText(title); ListAdapter adpter = new ArrayAdapter(context,R.layout.item_listview_categroy,R.id.tv_item_listview_categroy,args); list.setAdapter(adpter); list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { tv.setText(args[position]); dialog.dismiss(); } }); dialog.getWindow().setContentView(view); }}
在activity或fragment中的调用
private final String[] Category = new String[]{ "文学艺术", "人文社科", "经济管理", "生活休闲" , "外语学习", "自然科学", "考试教育", "计算机软件", "医学"};AlertDialogUtils.showAlertDialog(getContext(),"书籍分类",tvSelectCategroy,Category);
AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setView(LayoutInflater.from(context).inflate(R.layout.select_birthday_item,null)); builder.setTitle("选择出生日期"); AlertDialog alertDialog = builder.create(); alertDialog.show(); WindowManager.LayoutParams lp= alertDialog.getWindow().getAttributes(); lp.width=350;//定义宽度 lp.height=300;//定义高度 alertDialog.getWindow().setAttributes(lp);
转载地址:http://vvvpi.baihongyu.com/