How to create a Custom Dialog box in android?

后端 未结 22 2759
囚心锁ツ
囚心锁ツ 2020-11-21 07:06

I want to create a custom dialog box like below

\"enter

I have tried the foll

22条回答
  •  清酒与你
    2020-11-21 07:41

    Full Screen Custom Alert Dialog Class in Kotlin

    1. Create XML file, same as you would an activity

    2. Create AlertDialog custom class

      class Your_Class(context:Context) : AlertDialog(context){
      
       init {
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        setCancelable(false)
       }
      
       override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.your_Layout)
        val window = this.window
        window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                           WindowManager.LayoutParams.MATCH_PARENT)
      
        //continue custom code here
        //call dismiss() to close
       }
      }
      
    3. Call the dialog within the activity

      val dialog = Your_Class(this)
      //can set some dialog options here
      dialog.show()
      

    Note**: If you do not want your dialog to be full screen, delete the following lines

          val window = this.window
          window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                             WindowManager.LayoutParams.MATCH_PARENT)
    

    Then edit the layout_width & layout_height of your top layout within your XML file to be either wrap_content or a fixed DP value.

    I generally do not recommend using fixed DP as you would likely want your app to be adaptable to multiple screen sizes, however if you keep your size values small enough you should be fine

提交回复
热议问题