编程知识 cdmana.com

Android universal dialogfragment

Preface

In the development process , We often use dialog boxes , To improve development efficiency , So I use DialogFragment Encapsulates a dialog box through .

Why use DialogFragment

First of all, use DialogFragment Before , We usually create dialog boxes with Dialog In the form of , And from a coding point of view ,Dialog It's easy to use , but Android Official recommendation DialogFragment Instead of Dialog.
DialogFragment with Dialog The features that are not available in the phone configuration change , Lead to Activity When you need to recreate , For example, rotating the screen , be based on DialogFragment The dialog box will be created by FragmentManager Automatic reconstruction , However, based on Dialog The implemented dialog box does not have this capability ), It can make it more reusable ( To reduce the coupling ) And better convenience .

 Insert picture description here  Insert picture description here

Universal DialogFragment Code :

class CommonDialog: DialogFragment() {
    
    private var mLayoutResId = 0
    private var mDimAmount = 0.5f // Background dimness 
    private var mShowBottomEnable= false // Whether the bottom shows 
    private var mMargin = 0 // Left and right margins 
    private var mAnimStyle = 0 // Enter exit animation 
    private var mOutCancel = true // Click external to cancel 
    var mContext: Context? = null
    private var mWidth = 0
    private var mHeight = 0
    private var convertListener:ViewConvertListener?=null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mContext = context
    }

    override fun onCreate(@Nullable savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, setDialogStyle())
    }

    @Nullable
    override fun onCreateView(inflater: LayoutInflater, @Nullable container: ViewGroup?, @Nullable savedInstanceState: Bundle?): View? {
        if (mLayoutResId>0){
            val view: View = inflater.inflate(mLayoutResId, container, false)
            convertListener?.convertView(DialogViewHolder.create(view), this)
            return view
        }
        return null
    }

    override fun onStart() {
        super.onStart()
        initParams()
    }

    private fun initParams() {
        val window: Window? = dialog!!.window
        if (window != null) {
            val params: WindowManager.LayoutParams = window.attributes
            params.dimAmount = mDimAmount

            // Set up dialog Display position 
            if (mShowBottomEnable) {
                params.gravity = Gravity.BOTTOM
            }

            // Set up dialog Wide and high 
            params.width=if(mWidth==0) getScreenWidth(context!!) - 2 * dp2px(context!!, mMargin.toFloat()) else dp2px(context!!, mWidth.toFloat())
            params.height=if(mHeight == 0) WindowManager.LayoutParams.WRAP_CONTENT else dp2px(context!!, mHeight.toFloat())

            // Set up dialog Animation 
            if (mAnimStyle != 0) {
                window.setWindowAnimations(mAnimStyle)
            }
            window.attributes = params
        }
        //isCancelable = mOutCancel // Invalid settings 
        dialog?.setCancelable(mOutCancel)
        dialog?.setCanceledOnTouchOutside(mOutCancel)
    }

    /**
     *  Set background dimness 
     *
     * @param dimAmount
     * @return
     */
    fun setDimAmount(@FloatRange(from = 0.0, to = 1.0) dimAmount: Float): CommonDialog? {
        mDimAmount = dimAmount
        return this
    }

    /**
     *  Whether to show the bottom 
     *
     * @param showBottom
     * @return
     */
    fun setShowBottom(showBottom: Boolean): CommonDialog? {
        mShowBottomEnable = showBottom
        return this
    }

    /**
     *  Set width and height 
     *
     * @param width
     * @param height
     * @return
     */
    fun setDialogSize(width: Int, height: Int): CommonDialog? {
        mWidth = width
        mHeight = height
        return this
    }

    /**
     *  Set left and right margin
     *
     * @param margin
     * @return
     */
    fun setDialogMargin(margin: Int): CommonDialog? {
        mMargin = margin
        return this
    }

    /**
     *  Set the entry and exit animation 
     *
     * @param animStyle
     * @return
     */
    fun setAnimStyle(@StyleRes animStyle: Int): CommonDialog? {
        mAnimStyle = animStyle
        return this
    }

    /**
     *  Set whether to click external cancel 
     *
     * @param outCancel
     * @return
     */
    fun setOutCancel(outCancel: Boolean): CommonDialog? {
        mOutCancel = outCancel
        return this
    }

    fun show(manager: FragmentManager): CommonDialog? {
        super.show(manager, System.currentTimeMillis().toString())
        return this
    }

    /**
     *  Set up dialog Layout 
     *
     * @return
     */
    fun setDialogLayoutId(layoutId: Int=0){
        mLayoutResId=layoutId
    }

    /**
     *  Set up dialog style 
     *
     * @return
     */
    fun setDialogStyle(style:Int=R.style.fullScreenDialog): Int{
        return style
    }

    fun setConvertListener(convertListener: ViewConvertListener): CommonDialog? {
        this.convertListener = convertListener
        return this
    }

    /**
     *  Get screen width 
     *
     * @param context
     * @return
     */
    fun getScreenWidth(context: Context): Int {
        val displayMetrics: DisplayMetrics = context.resources.displayMetrics
        return displayMetrics.widthPixels
    }

    fun dp2px(context: Context, dipValue: Float): Int {
        val scale: Float = context.resources.displayMetrics.density
        return (dipValue * scale + 0.5f).toInt()
    }

    interface ViewConvertListener{
        fun convertView(holder: DialogViewHolder, dialog: CommonDialog)
    }

}

DialogViewHolder

class DialogViewHolder(view: View) {

    private var views: SparseArray<View>? = null
    private var convertView: View? = null

    init {
        convertView = view
        views = SparseArray()
    }

    companion object{
        fun create(view: View): DialogViewHolder {
            return DialogViewHolder(view)
        }
    }

    /**
     *  obtain View
     * @param viewId
     * @param <T>
     * */
    fun <T : View> getView(@IdRes viewId: Int): T {
        var view: View? = views!![viewId]
        if (view == null) {
            view = convertView?.findViewById(viewId)
            views!!.put(viewId, view)
        }
        return view as T
    }

    /**
     *  Set text 
     *
     * @param viewId
     * @param text
     */
    fun setText(viewId: Int, text: String?) {
        val textView: TextView = getView(viewId)
        textView.text = text
    }

    /**
     *  Set font color 
     *
     * @param viewId
     * @param colorId
     */
    fun setTextColor(viewId: Int, colorId: Int) {
        val textView: TextView = getView(viewId)
        textView.setTextColor(colorId)
    }

    /**
     *  Set the background image 
     *
     * @param viewId
     * @param resId
     */
    fun setBackgroundResource(viewId: Int, resId: Int) {
        val view: View = getView(viewId)
        view.setBackgroundResource(resId)
    }

    /**
     *  Set the background color 
     *
     * @param viewId
     * @param colorId
     */
    fun setBackgroundColor(viewId: Int, colorId: Int) {
        val view: View = getView(viewId)
        view.setBackgroundColor(colorId)
    }

    /**
     *  Set click event 
     *
     * @param viewId
     * @param listener
     */
    fun setOnClickListener(viewId: Int, callback: () -> Unit) {
        val view: View = getView(viewId)
        view.setOnClickListener {
            callback()
        }
    }

    /**
     *  Show hidden View
     * @param viewId
     * @param visibility
     */
    fun setVisibility(@IdRes viewId: Int, visibility: Int){
        val view: View = getView(viewId)
        if (visibility!=view.visibility){
            view.visibility = visibility
        }
    }
}

Use CommonDialog

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        tv_sure.setOnClickListener {
          confirm()
        }
        tv_comment.setOnClickListener {
           comment()
        }
    }

    private fun confirm(){
        CommonDialog().run {
            setDialogLayoutId(R.layout.layout_dialog_confirm)
            setOutCancel(false)
            setDialogMargin(30)
            setConvertListener(object :CommonDialog.ViewConvertListener{
                override fun convertView(holder: DialogViewHolder, dialog: CommonDialog) {
                    holder.setOnClickListener(R.id.tv_confirm) {
                        dialog.dismissAllowingStateLoss()
                    }
                    holder.setOnClickListener(R.id.tv_cancel) {
                        dialog.dismissAllowingStateLoss()
                    }
                }
            })
            show(supportFragmentManager)
        }
    }

    private fun comment(){
        CommonDialog().run {
            setDialogLayoutId(R.layout.layout_dialog_comment)
            setOutCancel(false)
            setConvertListener(object :CommonDialog.ViewConvertListener{
                override fun convertView(holder: DialogViewHolder, dialog: CommonDialog) {
                    val tvPublish=holder.getView<TextView>(R.id.tv_publish)
                    val etComment=holder.getView<EditText>(R.id.et_comment)
                    tvPublish.setOnClickListener {
                        val content=etComment.text.toString()
                        if (TextUtils.isEmpty(content)){
                            Toast.makeText(mContext," Comment content cannot be empty ",Toast.LENGTH_SHORT).show()
                        }else{
                            Toast.makeText(mContext,content,Toast.LENGTH_SHORT).show()
                            dialog.dismissAllowingStateLoss()
                        }
                    }
                }
            })
            show(supportFragmentManager)
        }
    }
}

Github Code address .

版权声明
本文为[osc_ chra83mb]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224102147107K.html

Scroll to Top