I have a problem with a custom dialog implemented as below:
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Title");
dialogBuilder.setMessage("Message");
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
// Set an EditText view to get user input
EditText input = new EditText(this);
input.setHeight(LayoutParams.WRAP_CONTENT);
input.setWidth(LayoutParams.MATCH_PARENT);
layout.addView(input);
TextView text = new TextView(this);
text.setText("show some text here");
text.setHeight(LayoutParams.WRAP_CONTENT);
text.setWidth(LayoutParams.MATCH_PARENT);
//text.setHeight(50);
//text.setWidth(150);
text.setVisibility(TextView.VISIBLE);
layout.addView(text);
Button btn = new Button(this);
btn.setText("Button");
btn.setHeight(LayoutParams.WRAP_CONTENT);
btn.setWidth(LayoutParams.WRAP_CONTENT);
layout.addView(btn);
dialogBuilder.setView(layout);
dialogBuilder.setPositiveButton("Ok", null);
AlertDialog myDialog = dialogBuilder.create();
myDialog.show();
The problem is that the TextView text doesn’t show up in the dialog if I set its width and height as in the code above. It only appears if I hard code the properties (the two commented lines), but that’s not the desired behavior.
Also, although the Button has the width set as WRAP_CONTENT, it is as big as the screen.
Could someone please point out what I’m doing wrong here?
You should use setLayoutParams() and not setHeight() and setWidth()
Replace
With this
EDIT:
About the Button use :
It works to me…
EDIT 2:
If you use
text.setHeight(LayoutParams.WRAP_CONTENT);it is equal totext.setHeight(-2);so yourtextViewwill be -2 pixel height and won’t be visible… on the other handsButtonsand other that uses a ninepatch image won’t get smaller than the ninepatch itself.