How to get the AlertDialog title?

后端 未结 5 831
無奈伤痛
無奈伤痛 2020-12-30 03:09

I tried to get the message and the following line of code works:

TextView dialogMessage = (TextView)dialogObject.findViewById(android.R.id.message);
<         


        
5条回答
  •  再見小時候
    2020-12-30 03:40

    You can implement it your self. Create your own class that extend android.app.AlertDialog.Builder. And then create a variable to store your value after using the method setTitle().


    import android.content.Context;
    import android.support.annotation.StringRes;
    
    public class AlertDialog extends android.app.AlertDialog.Builder {
    
        private Context context;
        private String title;
    
        public AlertDialog(Context context) {
            super(context);
            this.context = context;
        }
    
        public AlertDialog(Context context, int themeResId) {
            super(context, themeResId);
            this.context = context;
        }
    
        /**
         * Set title using string
         */
        @Override
        public AlertDialog setTitle(CharSequence title) {
    
            // set the title
            this.title = title.toString();
    
            super.setTitle(title);
            return this;
        }
    
        /**
         * Set title using resource string
         */
        @Override
        public AlertDialog setTitle(@StringRes int titleId) {
    
            this.title = this.context.getText(titleId).toString();
    
            super.setTitle(titleId);
            return this;
        }
    
        // create public method
        public String getTitle(){
            return this.title;
        }
    }
    

    And then use you can use it as ordinary AlertDialog, with implemented method which get its title. Then you can test it:

    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // Crete new alert dialog
            AlertDialog dialog = new AlertDialog(this);
            dialog.setMessage("Type some message here :D");
            dialog.setTitle(R.string.settings_title);           // string resource
            dialog.setTitle("Dialog1 title");                   // string
            dialog.show();
    
            // Crete secondary dialog with same title
            // using getTitle() method
            new AlertDialog(this)
                    .setTitle(dialog.getTitle())
                    .setMessage("Copy title from first dialog.")
                    .show();
    
        }
    }
    

提交回复
热议问题