Issue
I'm trying to generate a custom dialog in Android. I create my Dialog like this:
dialog = new Dialog(this);
dialog.setContentView(R.layout.my_dialog);
Everythings works fine except for the title of the Dialog. Even if I don't set the title of the dialog the dialog popup has a blank space at the position of the dialog.
Is there any way to hide this part of the Dialog?
I tried it with an AlertDialog but it seems the layout is not set properly:
LayoutInflater inflater =
(LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.map_dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(view);
// dialog = new Dialog(this);
// dialog.setContentView(R.layout.map_dialog);
dialog = builder.create();
((TextView) dialog.findViewById(R.id.nr)).setText(number);
If I use this code I get a null Pointer Exception in the last line. The dialog is not null so the TextView I try to retrieve does not exist.
If I uncomment the part where I use the Dialog Constructor everything works fine but for the title above my dialog layout.
Solution
You can hide the title of a dialog using:
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
Previous version of this answer, which is overcomplicated:
You need to use an AlertDialog
. There's a good explanation on the Android Developer's site about custom dialogs.
In very short summary, you do this with code like copied below from the official website. That takes a custom layot file, inflates it, gives it some basic text and icon, then creates it. You'd show it then with alertDialog.show()
.
AlertDialog.Builder builder;
AlertDialog alertDialog;
Context mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater)
mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog,
(ViewGroup) findViewById(R.id.layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.android);
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
alertDialog = builder.create();
In response to comment:
I assume that TextView with the id nr
is in the View you are inflating with View view = inflater....
. If so, then you need to change just one bit: instead of dialog.findView...
make it view.findView...
. Then once you've done that, remember to use dialog.show(), or even builder.show() without bothering to do builder.create().
Answered By - Steve Haley
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.