Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title")
.setMessage("Dialog content.")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
}
})
.show();
Dialog的作用是给用户一个提示信息,并让用户根据提示做出判断。而Dialog的特征就是,它会阻止你原本正在进行的操作,必须停止下来对Dialog进行处理。
Toast
Toast.makeText(context, "things happened", Toast.LENGTH_SHORT).show();
效果图就不上了,但是加一个小技巧,当用户多次点击一个按钮时,Toast长时间不消失的技巧
public class Util {
private static Toast toast;
public static void showToast(Context context,
String content) {
if (toast == null) {
toast = Toast.makeText(context,
content,
Toast.LENGTH_SHORT);
} else {
toast.setText(content);
}
toast.show();
}
}
因为是static类型,要谨防内存泄漏
Snackbar
在使用Snackbar之前,首先需要在app/build.gradle中添加相应的依赖:
compile 'com.android.support:design:23.4.0'
然后就可以使用Snackbar了:
LinearLayout view = (LinearLayout) findViewById(R.id.out_layout_id);
Snackbar.make(view, "data deleted",Snackbar.LENGTH_LONG)
.setAction("Undo", new View.OnClickListener(){
@Override
public void onClick(View v) {
}
})
.show();
make()方法的第一个参数需要传入一个view,只要是当前界面布局的任意一个view都可以,Snackbar会使用这个view来自动查找最外层的布局,用于展示Snackbar
以上转载自文章:郭神:Android提醒微技巧,你真的了解Dialog、Toast和Snackbar吗?
Dialog 拓展
① 列表Dialog
final String[] items = {"我是1", "我是2", "我是3", "我是4"};
AlertDialog.Builder listDialog = new AlertDialog.Builder(this);
listDialog.setTitle("我是一个列表Dialog")
.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// which 下标从0开始
Toast.makeText(MainActivity.this, "你点击了" + items[which], Toast.LENGTH_SHORT).show();
}
})
.show();
② 单选Dialog
int yourChoice;
private void showSingleChoiceDialog() {
final String[] items = {"我是1", "我是2", "我是3", "我是4"};
yourChoice = -1;
AlertDialog.Builder singleChoiceDialog = new AlertDialog.Builder(this);
singleChoiceDialog.setTitle("我是一个单选Dialog")
// 第二个参数是默认选项,此处设置为-1
.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
yourChoice = which;
}
})
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (yourChoice != -1) {
Toast.makeText(MainActivity.this, "你选择了" + items[yourChoice], Toast.LENGTH_SHORT).show();
}
}
})
.show();
}
拓展 :自定义单选Dialog
private void updateLessonWay() {
View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_update_lesson_way, null);
final RadioGroup lessonWayRadio = (RadioGroup) view.findViewById(R.id.lesson_way_group);
final TextView cancelTv = (TextView) view.findViewById(R.id.leave_cancel_btn);
TextView sureTv = (TextView) view.findViewById(R.id.leave_sure_btn);
for (int i = 0; i < mList.size(); i++) {
RadioButton tempButton = new RadioButton(mContext);
tempButton.setButtonDrawable(R.drawable.radio_style_update_lesson_way); // 设置按钮的样式
tempButton.setText(mSubInfo.getDictLessonWayList().get(i).getDictItemName());
tempButton.setTextColor(Color.parseColor("#333333"));
tempButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
tempButton.setPadding(DensityUtil.dip2px(mContext, 5), DensityUtil.dip2px(mContext, 10), 0, DensityUtil.dip2px(mContext, 10)); // 设置文字距离按钮四周的距离
lessonWayRadio.addView(tempButton, LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
}
final Dialog dialog = new Dialog(mContext);
dialog.setContentView(view);
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
lessonWayRadio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton checkButton = (RadioButton) lessonWayRadio.findViewById(checkedId);
String selectLessonWay = checkButton.getText().toString();
}
});
cancelTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
sureTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
dialog.show();
setDialogWindow(mContext, dialog);
}
xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/shape_lesson_history_bg"
android:orientation="vertical">
<RadioGroup
android:id="@+id/lesson_way_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_margin="30dp"></RadioGroup>
<View
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:background="#E6E6E6"></View>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<TextView
android:id="@+id/leave_cancel_btn"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="取消"
android:textColor="#333333"
android:textSize="15sp"/>
<View
android:layout_width="0.5dp"
android:layout_height="match_parent"
android:background="#E6E6E6"></View>
<TextView
android:id="@+id/leave_sure_btn"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="确定"
android:textColor="#e80316"
android:textSize="15sp"/>
</LinearLayout>
</LinearLayout>
单选自定义图标设置:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/icon_tick" android:state_checked="true" android:state_enabled="true"/>
<item android:drawable="@drawable/icon_tick_none" android:state_checked="false" android:state_enabled="true"/>
</selector>
③ 多选Dialog
ArrayList<Integer> yourChoices = new ArrayList<>();
private void showMultiChoiceDialog() {
final String[] items = {"我是1", "我是2", "我是3", "我是4"};
// 设置默认选中的选项,全为false默认均未选中
final boolean initChoiceSets[] = {false, false, false, false};
yourChoices.clear();
AlertDialog.Builder multiChoiceDialog = new AlertDialog.Builder(this);
multiChoiceDialog.setTitle("我是一个多选Dialog")
.setMultiChoiceItems(items, initChoiceSets, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
yourChoices.add(which);
} else {
yourChoices.remove(which);
}
}
})
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int size = yourChoices.size();
String str = "";
for (int i = 0; i < size; i++) {
str += items[yourChoices.get(i)] + " ";
}
Toast.makeText(MainActivity.this, "你选中了" + str, Toast.LENGTH_SHORT).show();
}
})
.show();
}
④ 自定义 Dialog
public static Dialog getChooseDialog(Context context, String msg, View.OnClickListener click) {
View view = LayoutInflater.from(context).inflate(R.layout.dialog_choose_view, null);
TextView text = (TextView) view.findViewById(R.id.leave_reason_tv);
TextView cancelTv = (TextView) view.findViewById(R.id.leave_cancel_btn);
TextView sureTv = (TextView) view.findViewById(R.id.leave_sure_btn);
text.setText(msg);
final Dialog dialog = new Dialog(context);
dialog.setContentView(view);
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
cancelTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
sureTv.setOnClickListener(click);
dialog.show();
setDialogWindow(context, dialog);
return dialog;
}
public static void setDialogWindow(Context context, Dialog dialog) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
int displayWidth = dm.widthPixels;
WindowManager.LayoutParams p = dialog.getWindow().getAttributes(); //获取对话框当前的参数值
p.width = (int) (displayWidth * 0.8); //宽度设置为屏幕的0.5
dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
dialog.getWindow().setAttributes(p); //设置生效
}
xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/shape_lesson_history_bg"
android:orientation="vertical">
<TextView
android:id="@+id/leave_reason_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:gravity="left"
android:padding="10dp"
android:textColor="#333333"
android:textSize="15sp"/>
<View
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:background="#E6E6E6"></View>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<TextView
android:id="@+id/leave_cancel_btn"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="取消"
android:textColor="#333333"
android:textSize="15sp"/>
<View
android:layout_width="0.5dp"
android:layout_height="match_parent"
android:background="#E6E6E6"></View>
<TextView
android:id="@+id/leave_sure_btn"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="确定"
android:textColor="#e80316"
android:textSize="15sp"/>
</LinearLayout>
</LinearLayout>
background : drawable
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#FFFFFF"/>
<corners android:bottomLeftRadius="4dp" android:bottomRightRadius="4dp"
android:topLeftRadius="8dp" android:topRightRadius="8dp"/>
<stroke android:width="0.5dp" android:color="#D9D9D9"/>
</shape>
</item>
</selector>
踩坑:
自定义Dialog View根部局设置圆角后,如布局中给某一控件设置颜色,圆角可能会被覆盖
最简单粗暴的解决方法:
给控件也设置圆角
以上Dialog皆为数据及界面比较简单的,如果需要处理比较复杂数据的Dialog,推荐使用DialogFragment
Demo:
public class DialogFragmentDemo extends DialogFragment {
private Dialog mDialog;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle bundle = getArguments();
if (bundle != null) {
String words = bundle.getString("words", "unKnown");
String explainWords = bundle.getString("explainWords", "unKnown");
}
mDialog = new Dialog(getActivity(), R.style.BottomTransparentDialog);
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialog.setContentView(R.layout.dialog_explain_words);
mDialog.setCanceledOnTouchOutside(true); // 外部点击消失
Window window = mDialog.getWindow();
window.setWindowAnimations(R.style.dialogstyle); // 添加动画
window.setBackgroundDrawableResource(android.R.color.transparent); //背景设为透明
WindowManager.LayoutParams lp = window.getAttributes();
lp.gravity = Gravity.BOTTOM;
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
// lp.width = DensityUtil.dip2px(getActivity(),350);
window.setAttributes(lp);
ButterKnife.bind(this, mDialog);
return mDialog;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (mDialog != null) {
mDialog.dismiss();
}
return true;
}
return false;
}
});
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
}
R.style.BottomTransparentDialog
<style name="BottomTransparentDialog" parent="@android:style/Theme.Holo.NoActionBar">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<!--设置为false,弹出后,activity颜色不变暗-->
<item name="android:backgroundDimEnabled">false</item>
</style>
R.style.dialogstyle
<style name="dialogstyle" parent="android:Animation">
<item name="@android:windowEnterAnimation">@anim/dialog_enter</item>
<item name="@android:windowExitAnimation">@anim/dialog_exit</item>
</style>
调用
FragmentManager fm = getActivity().getSupportFragmentManager();
DialogFragmentDemo dialogDemo = new DialogFragmentDemo();
Bundle bundle = new Bundle();
bundle.putString("words", (String) editText.getTag());
bundle.putString("explainWords", wordsMap.get((String) editText.getTag()));
dialogDemo .setArguments(bundle);
dialogDemo .show(fm, "fragment_bottom_dialog");
推荐链接地址: