Explanation of Android Programming Custom AlertDialog Style Method

  • 2021-08-17 01:06:46
  • OfStack

In this paper, an example is given to describe the method of customizing AlertDialog style by Android programming. Share it for your reference, as follows:

When developing, we usually need to customize AlertDialog to meet our functional requirements:

For example, you can enter information in the pop-up dialog box, or a list of selected functions to be displayed, or you want to implement a specific UI style. Then we can do it in the following ways.

Method 1: Completely customize layout of AlertDialog. For example, we want to implement AlertDialog layout with input boxes custom_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="wrap_content"
  android:background="@drawable/dialog_bg"
  android:orientation="vertical">
  <TextView
    android:id="@+id/title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#00ffff"
    android:gravity="center"
    android:padding="10dp"
    android:text="Dialog Title "
    android:textSize="18sp" />
  <EditText
    android:id="@+id/dialog_edit"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint=" Please enter content "
    android:minLines="2"
    android:textScaleX="16sp" />
  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:orientation="horizontal">
    <Button
      android:id="@+id/btn_cancel"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_weight="1"
      android:background="#00ffff"
      android:text=" Cancel " />
    <View
      android:layout_width="1dp"
      android:layout_height="40dp"
      android:background="#D1D1D1"></View>
    <Button
      android:id="@+id/btn_comfirm"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_weight="1"
      android:background="#00ffff"
      android:text=" Determine " />
  </LinearLayout>
</LinearLayout>

Originally used in code:


AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
View view = View
    .inflate(getActivity(), R.layout.custom_dialog, null);
builder.setView(view);
builder.setCancelable(true);
TextView title= (TextView) view
    .findViewById(R.id.title);// Set the title 
EditText input_edt= (EditText) view
    .findViewById(R.id.dialog_edit);// Input content 
Button btn_cancel=(Button)view
.findViewById(R.id.btn_cancel);// Cancel button 
 Button btn_comfirm=(Button)view
.findViewById(R.id.btn_comfirm);// OK button 
// Cancel or confirm button listening event handling 
AlertDialog dialog = builder.create();
dialog.show();

In this way, we can pop up a custom Dialog. One drawback of this method is:

If there are multiple UI and different AlertDialog in the project, we have to write multiple layout pages. Of course, we can extract the general layout and then process it in various ways.

Method 2: Modify the controls in the native AlertDialog of the Android system to achieve the desired effect.

For example, if we want to realize a specific style dialog box, we can write a public method to achieve the desired effect by modifying the controls in the native AlertDialog of Android system. The simple code is as follows:


public static void setCustomDialogStyle(AlertDialog dialog){
final Resources res = dialog.getContext().getResources();
    int topPanelId = res.getIdentifier("topPanel", "id", "android");// Get top 
    LinearLayout topPanel = (LinearLayout) getDialog().findViewById(topPanelId);
    topPanel.setBackgroundResource(R.drawable.dialog_top_bg);// Set the top background 
    LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, // Set top height 
        dp2px(getDialog().getContext(), 50));
    topPanel.setLayoutParams(params);
    int dividerId = res.getIdentifier("titleDivider", "id", "android");// Set the divider line 
    View divider = getDialog().findViewById(dividerId);
    divider.setVisibility(View.GONE);
    int titleId = res.getIdentifier("alertTitle", "id", "android");// Get title title
    TextView title = (TextView) getDialog().findViewById(titleId);// Set the title 
    title.setTextColor(Color.WHITE);// Title text color 
    title.setTextSize(18);// Text size 
    title.setGravity(Gravity.CENTER);// Text position 
    int customPanelId = res.getIdentifier("customPanel", "id", "android");// Setting content 
    FrameLayout customPanel = (FrameLayout) getDialog().findViewById(customPanelId);
    customPanel.setBackgroundColor(Color.TRANSPARENT);// Background transparency 
    customPanel.getChildAt(0).setBackgroundColor(Color.WHITE);
    customPanel.setPadding(dp2px(getContext(), 8), 0, ViewUtils.dp2px(getContext(), 8), 0);// Settings padding
    int buttonPanelId = res.getIdentifier("buttonPanel", "id", "android");// Get bottom 
    LinearLayout buttonPanel = (LinearLayout) getDialog().findViewById(buttonPanelId);
    buttonPanel.setBackgroundResource(R.drawable.dialog_bottom_bg);// Set the bottom background 
    buttonPanel.setPadding(dp2px(getContext(), 8), 1, dp2px(getContext(), 8), 0);
    Button button1 = (Button) getDialog().findViewById(android.R.id.button1);// Set bottom Button
    button1.setTextColor(Color.WHITE);// Text color 
    button1.setTextSize(18);// Text size 
    button1.setBackgroundResource(R.drawable.bg_right_round);//Button Circular Background Box 
    Button button2 = (Button) getDialog().findViewById(android.R.id.button2);
    button2.setTextColor(Color.WHITE);
    button2.setTextSize(18);
    button2.setBackgroundResource(R.drawable.bg_left_round);
}

Various colors and background pictures used in the code are defined according to the requirements. The dp and px conversion codes used are as follows:


public static int dp2px(Context context, float dp) {
    float density = context.getResources().getDisplayMetrics().density;
    return (int) (dp * density + 0.5f);
}

In this way, we have defined the whole world style of AlertDialog. When using it, we only need to define UI of the content part according to UI requirements.

Or the AlertDialog that can be entered above, our layout can only be written as the following, of course, the LinearLayout of the outer layer can also be removed.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_content"
  android:layout_height="wrap_content"
  android:orientation="vertical">
  <EditText
    android:id="@+id/input_edt"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:background="@drawable/input"
    android:hint=" Please enter content "
    android:maxLength="16"
    android:textColor="#333333"
    android:textSize="16sp" />
</LinearLayout>

Then use in the code:


AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(" Set the title ");
View view = View
    .inflate(getActivity(), R.layout.custom_dialog, null);
builder.setView(view);
builder.setCancelable(true);
EditText input_edt= (QRCodeEditText) view
    .findViewById(R.id.input_edt);
builder.setPositiveButton(android.R.string.ok,
    new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {
        // Click OK button to process 
          dialog.cancel();
        }
      }
    });
builder.setNegativeButton(android.R.string.cancel,
    new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {
      // Click the Cancel button to process 
        dialog.cancel();
      }
    });
final AlertDialog dialog = builder.create();
dialog.show();
setCustomDialogStyle(dialog);// Don't forget to call here setCustomDialogStyle Method 

This way is much more convenient than the first way. Of course, to achieve the background transparency of AlertDialog, we can also add the following code in res/value/style. xml:


<style name="dialog" parent="@android:style/Theme.Dialog">
     <item name="android:windowFrame">@null</item> //Dialog Adj. windowFrame Box is None 
     <item name="android:windowIsFloating">true</item> // Does it emerge in activity Above 
     <item name="android:windowIsTranslucent">true</item> // Is it translucent 
     <item name="android:windowNoTitle">true</item> // Whether to display title
     <item name="android:background">@android:color/transparent</item> // Settings dialog Background of 
     <item name="android:windowBackground">@android:color/transparent</item>
     <item name="android:backgroundDimAmount">0.7</item> // Is used to control the value of gray scale, when it is 1 When, the interface is in addition to our dialog The content is highlighted, dialog The area outside is black, and no other content can be seen at all 
     <item name="android:backgroundDimEnabled">true</item>
</style>

Add the following statement where you need to add alertDialog:


AlertDialog.Builder alertbBuilder=new AlertDialog.Builder(getActivity(),R.style.dialog);
// The next code .....

More readers interested in Android can check out the topics on this site: "Introduction and Advanced Tutorial of Android Development", "Summary of Android Debugging Skills and Common Problem Solutions", "Summary of Android Basic Component Usage", "Summary of Android View View Skills", "Summary of Android Layout layout Skills" and "Summary of Android Control Usage"

I hope this article is helpful to everyone's Android programming.


Related articles: