how to make custom layout for alertdialog wrap content - android

I have created a custom layout with 3 buttons for alertdialog which is working fine. I am trying to make the layout so that width and height layout will be only wrap its content i.e. no extra width/height but I am unable to do so. Can you help me on this please?
Here is my custom layout for alertdialog:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#00ffffff"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#drawable/rectangle_menu"
>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/wowButtonId"
android:layout_marginLeft="5dp"
android:src="#drawable/love_icon"
android:background="#drawable/round_button_for_round_menu_like_button"
android:layout_gravity="center"
/>
<ImageButton
android:layout_width="40dp"
android:layout_height="35dp"
android:id="#+id/blehButtonId"
android:layout_marginLeft="5dp"
android:src="#drawable/bleh"
android:background="#drawable/round_button_for_round_menu_like_button"
android:layout_gravity="center"
/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/dislikeButtonId"
android:layout_marginLeft="5dp"
android:src="#drawable/dislike_icon"
android:background="#drawable/round_button_for_round_menu_like_button"
android:layout_gravity="center"
/>
</LinearLayout>
</LinearLayout>
alertDialog implement in adapter code:
AlertDialog.Builder builder=new AlertDialog.Builder(context);
AlertDialog alertDialog=builder.create();
View view1=LayoutInflater.from(context).inflate(R.layout.layout_for_long_like_button_option,null);
ImageButton wow=(ImageButton) view1.findViewById(R.id.wowButtonId);
ImageButton disLike=(ImageButton) view1.findViewById(R.id.dislikeButtonId);
ImageButton bleh=(ImageButton) view1.findViewById(R.id.blehButtonId);
wow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context,"wow",Toast.LENGTH_SHORT).show();
}
});
disLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context,"dislike",Toast.LENGTH_SHORT).show();
}
});
bleh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context,"bleh",Toast.LENGTH_SHORT).show();
}
});
alertDialog.setView(view1);
alertDialog.show();

try this on your class file where you inflate your alert dialog...
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
Window window = alertDialog.getWindow();
lp.copyFrom(window.getAttributes());
//This makes the dialog take up the full width
lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
window.setAttributes(lp);

Summary: Use RelativeLayout tag at the root in your custom layout
I had two alert dialogs in the application I was writing. One of them did not wrap content, while the other did. The one with the LinearLayout tag at its root, was expanding a tad more in height, than the space its contents really occupied.
I tried setting the width and height properties to wrap_content on the LinearLayout but to no avail.
The one with the RelativeLayout tightly wrapped its contents. The code structure to achieve this would look like:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<!-- More widgets -->
</LinearLayout>
</RelativeLayout>
Although care must be taken, that the inner LinearLayout should still specify wrap_content. You can of course specify match_parent if your intention is to present an elongated dialog, the intentions for doing so, which I would leave it to the developer.
Android Studio still warns me that The LinearLayout layout or its RelativeLayout parent is useless. I do not consider this a solution to the problem, rather it's just a fix. And, I should mention that I've always had these layout problems working with Android. This, I feel, is a more saner approach as it keeps the code modifications down to the layout.

You can use below code for set layout and show dialog
public void showDialog() {
LayoutInflater li = LayoutInflater.from(MainActivity.this);
View promptsView = li.inflate(R.layout.layout_for_long_like_button_option, null);
final TextView txtOk = (TextView) promptsView.findViewById(R.id.txtOk);
final TextView txtCancel = (TextView) promptsView.findViewById(R.id.txtCancel);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(BaseActivity.this);
alertDialogBuilder.setView(promptsView);
final AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
txtOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
txtCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertDialog.dismiss();
}
});
alertDialog.show();
}

You can try setting the width of the inflated view directly when the dialog is shown and therefore has a window
val dialog = AlertDialog.Builder(context)
.setView(myView)
.create()
dialog.setOnShowListener {
dialog.window?.setLayout(
myView.width,
ViewGroup.LayoutParams.WRAP_CONTENT
)
}

Related

DialogFragment: constant height of the central view

I have a DialogFragment which consists of three parts, from up to down: the title, the central view which displays all the contents, and the bottom pane which holds the PositiveButton "OK":
public Dialog onCreateDialog(Bundle savedInstanceState)
{
FragmentActivity act = getActivity();
LayoutInflater inflater = act.getLayoutInflater();
AlertDialog.Builder builder = new AlertDialog.Builder(act);
// TITLE:
TextView title = (TextView) inflater.inflate(R.layout.dialog_title, null);
title.setText(R.string.updates);
builder.setCustomTitle(title);
// CENTRAL VIEW:
View view = inflater.inflate(R.layout.dialog_updates, null);
// ... customize it ...
builder.setView(view);
// POSITIVE BUTTON:
builder.setPositiveButton( R.string.ok, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
// something
}
});
}
The stuff that's shown by the central view is downloaded from the web. Initially, when a user pops up the dialog, the View shows just the "Downloading..." message:
When we get an answer, we create a ScrollView and keep adding vertically scrollable Panes to it like so:
(image above shows three such panes added so far)
The result is that the height of the dialog keeps changing, which is visually unpleasant.
So I really want to keep the height of the whole Dialog constant, let's say pinned to 3/4 of the height of the screen. Let's do it then:
public void onResume()
{
super.onResume();
Window window = getDialog().getWindow();
Context context = getContext();
if( window!=null && context!=null )
{
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
final float height= metrics.heightPixels;
WindowManager.LayoutParams params = window.getAttributes();
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.height = (int)(0.75f*height);
window.setAttributes(params);
}
}
Result:
This does kind of work, as you can see though - it works by enlarging the lower pane with the 'OK' button, rather than the central View.
How to fix this?
EDIT: here's my dialog_title.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="20sp"
android:gravity="center"
android:padding="10dp"/>
One workaround for this issue is to use ConstrainedLayout for your whole dialog like this:
fragment_dialog layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:text="Updates"
android:textSize="20sp"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/central_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="Downloading"
app:layout_constrainedHeight="true"
app:layout_constraintBottom_toTopOf="#id/positive_action"
app:layout_constraintHeight_percent="0.8"
app:layout_constraintTop_toBottomOf="#id/title" />
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/positive_action"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_margin="8dp"
android:text="OK"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
You can change the percentage of your central view with app:layout_constraintHeight_percent="0.8"
DialogFragment class:
public class LoadingDialog extends DialogFragment {
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
FragmentActivity act = getActivity();
LayoutInflater inflater = act.getLayoutInflater();
View view = inflater.inflate(R.layout.fragment_dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(act).setView(view);
// POSITIVE BUTTON:
view.findViewById(R.id.positive_action).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//something
}
});
return builder.create();
}
#Override
public void onResume() {
super.onResume();
getDialog().getWindow().setLayout(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
}
}
And you will get this result:

Cannot change the width of AlertDialog with custom view in Android

I am absolute beginner to Android. Now I am having a problem with setting the width of default AlertDialog with custom view in Android. It is not resizing the width of the alert dialog. What is wrong with my code ?
This is the view layout of my alert dialog
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<android.support.v7.widget.AppCompatButton
xmlns:app="http://schemas.android.com/apk/res-auto"
android:textColor="#color/white"
app:backgroundTint="#color/green"
android:layout_gravity="center_horizontal"
android:id="#+id/btn_row_option_done"
android:text="Done"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<android.support.v7.widget.AppCompatButton
android:textColor="#color/white"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:backgroundTint="#color/lightBlue"
android:layout_gravity="center_horizontal"
android:text="Edit"
android:id="#+id/btn_row_option_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<android.support.v7.widget.AppCompatButton
android:textColor="#color/white"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:backgroundTint="#color/red"
android:layout_gravity="center_horizontal"
android:text="Delete"
android:id="#+id/btn_row_option_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<android.support.v7.widget.AppCompatButton
xmlns:app="http://schemas.android.com/apk/res-auto"
app:backgroundTint="#color/white"
android:layout_gravity="center_horizontal"
android:text="Cancel"
android:id="#+id/btn_row_option_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
As you can see, I set the width of the linearLayout to wrap_content.
This is how I am opening the alert dialog in my Java code
public void showOptionDialog(final int id)
{
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.row_option_dialog, null);
final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
Boolean isTaskDone = dbHelper.isTaskDone(id);
Button doneBtn = (Button)view.findViewById(R.id.btn_row_option_done);
if(isTaskDone==false)
{
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.markAsDone(id);
refreshListView();
alertDialog.cancel();
Toast.makeText(getActivity().getBaseContext(),"Marked as done",Toast.LENGTH_SHORT).show();
}
});
}
else{
ViewGroup viewGroup = (ViewGroup)doneBtn.getParent();
viewGroup.removeView(doneBtn);
}
Button editBtn = (Button)view.findViewById(R.id.btn_row_option_edit);
if(isTaskDone==false)
{
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity activity = (MainActivity) getActivity();
activity.replaceEditTaskFragment(id);
alertDialog.cancel();
}
});
}
else{
ViewGroup viewGroup = (ViewGroup)editBtn.getParent();
viewGroup.removeView(editBtn);
}
Button deleteBtn = (Button)view.findViewById(R.id.btn_row_option_delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.deleteTask(id);
items.remove(optionFocusedItemIndex);
adapter.notifyDataSetChanged();
Toast.makeText(getActivity().getBaseContext(),"Task deleted",Toast.LENGTH_SHORT).show();
alertDialog.cancel();
updateListEmptyText();
}
});
Button cancelBtn = (Button)view.findViewById(R.id.btn_row_option_cancel);
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.cancel();
}
});
alertDialog.setView(view);
alertDialog.show();
}
But when the alert dialog is opened, its width is not resized and still showing the default size like in screenshot.
This is the screenshot.
As you can see, width is nearly full of screen even I did set to wrap_content. I also set something like 300px. It is not working. How can I achieve this?
First make other layout for container and inside it make this linear layout with wrap content. After that you can make your alpha background of the container almost to 0 to be transparent. The dialog inside with the buttons is on the inner layout. For custom dialog you cant use this AlertDialog, make your own activity which behavior is like a dialog.
set required size here
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="300px"
android:layout_height="match_parent">......</LinearLayout>
or
alertDialog.show();
alertDialog.getWindow().setLayout(300, 300);
Change this line
alertDialog.setView(view);
To
alertDialog.setContentView(view);
Here view is the instance of your custom layout.

Dialog custom layout not stretching properly

Im creating a custom Dialog.
But it is showing extra space around.
Code:
private void showPushAlert(Context context, String message, int layoutID) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(layoutID);
TextView tvPushMessage = (TextView) dialog.findViewById(R.id.tvAlertMessage);
tvPushMessage.setText(message);
Button btnPushOk = (Button) dialog.findViewById(R.id.btnAlertOk);
btnPushOk.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
}
Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="275dp"
android:layout_height="wrap_content"
android:background="#drawable/background_round_rectangle"
android:orientation="vertical"
android:padding="#dimen/activity_vertical_margin">
<TextView
android:id="#+id/tvAlertMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Message"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/black" />;
<Button
android:id="#+id/btnAlertOk"
android:layout_width="65dp"
android:layout_height="30dp"
android:layout_below="#id/tvAlertMessage"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:background="#drawable/btn_use"
android:text="#string/ok"
android:textColor="#color/white" />
</RelativeLayout>
I also tried inflater:
final Dialog dialog = new Dialog(context);
View view = getLayoutInflater().inflate(layoutID, null);
dialog.setContentView(view);
But not the perfect result. Jut the width stretched.
I wanted to keep simple, so used just Dialog, instead of AlertDialog, or Dialog fragment.
Not sure why that was happening..
Used https://stackoverflow.com/a/6922903/4510869
to do this after dialog.show()
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = 500;
dialog.getWindow().setAttributes(lp);
This showed the custom width, but the top space was still visible.
Had to change to AlertDialog.Builder + the above snippet (AlertDialog also showed top space) to finally get the result.

Set height and width in an Dialog Box?

I am using a XML-layout which I am prompting as the dialog box.
Designing of XML-layout is well formatted with enough required height and width..
But when I open it as the dialog box its width is getting disturbed so how to set height and width of dialog box through coding.
I even had referred this previous STACK OVERFLOW QUESTION
Here is the code:
// Layout Inflater Code..
editDialog = new Dialog(this);
layoutEdit = LayoutInflater.from(this).inflate(R.layout.createlayout, null);
//layoutEdit.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
editDialog.setContentView(layoutEdit);
// Called the Dialogbox to inflate
updateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
editDialog.show();
}
});
// XML File Code:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bd"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="false"
android:text="Enter Name"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/whtie"
android:typeface="monospace" />
<EditText
android:id="#+id/txtname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" >
</EditText>
</LinearLayout>
</ScrollView>
Try this...
1.Dialog snippet:
private void CustomDialog(String msg) {
final Dialog dialog = new Dialog(YourActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
LinearLayout.LayoutParams dialogParams = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, 300);//set height(300) and width(match_parent) here, ie (width,height)
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dislogView = inflater
.inflate(R.layout.my_custom_popup, null);
dialog.setContentView(dislogView, dialogParams);
TextView popupMsg = (TextView) dialog.findViewById(R.id.popupMsg);
Button popupOk = (Button) dialog.findViewById(R.id.popupOk);
popupMsg.setText(msg);
popupOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
2.Then call CustomDialog(Str) where you want to prompt in your activity.
CustomDialog("This is customized popup dialog!");
You better use an activity that looks like a dialog (I feel it will be better in your case). Here is an example code:
public class DialogActivity extends Activity {
/**
* Initialization of the Activity after it is first created. Must at least
* call {#link android.app.Activity#setContentView setContentView()} to
* describe what is to be displayed in the screen.
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
// Be sure to call the super class.
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_LEFT_ICON);
// See assets/res/any/layout/dialog_activity.xml for this
// view layout definition, which is being set here as
// the content of our screen.
setContentView(R.layout.dialog_activity);
getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
android.R.drawable.ic_dialog_alert);
}
}
This code is from api demos
View layout = inflater.inflate(R.layout.view, NULL);
layout.setMinimumWidth(200);
layout.setMinimumHeight(200);
dialog.setContentView(layout);
Try
dialog.getWindow().setLayout(height, width);

Remove unnecessary margins from a custom dialog

I have a problem that I am designing a custom dialog for this. I am creating a xml for this as Framelayout is the root layout, and another framelayout with a gray background image is used for the contents, in which I have added a textview and two buttons Ok and Cancel and use all of this through dialog.setContentView(desired Xml Resource);
But when I generate that particular dialog then it shows extra spaces from each side, or we can say that extra margins are there but I don't know how it will removed? Please review the image attached with this question and suggest me the right solution.
Xml Layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_height="wrap_content" android:layout_width="wrap_content">
<FrameLayout android:id="#+id/rel"
android:layout_gravity="center_vertical" android:background="#drawable/dialog_box_bg" android:layout_width="wrap_content" android:layout_height="189dp">
<TextView android:id="#+id/tv_LogoutDialog_Text"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textColor="#424242"
android:text="Are you sure want to logout?" android:textSize="20dip" android:layout_gravity="center_vertical|center_horizontal"></TextView>
<Button android:id="#+id/btn_LogoutDialog_Cancel" android:background="#drawable/dialog_cancel_btn"
android:layout_marginLeft="20dip" android:layout_width="120dip" android:layout_height="42dip" android:layout_gravity="bottom|left" android:layout_marginBottom="15dip"></Button>
<Button android:id="#+id/btn_LogoutDialog_Ok"
android:background="#drawable/dialog_ok_btn_hover"
android:layout_width="120dip"
android:layout_height="42dip" android:layout_marginLeft="180dip" android:layout_gravity="bottom|right" android:layout_marginBottom="15dip" android:layout_marginRight="20dip"></Button>
</FrameLayout>
</FrameLayout>
Code:
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 0:
dialog = new Dialog(HomeScreenActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.logoutdialog);
btn_cancel = (Button)dialog.findViewById(R.id.btn_LogoutDialog_Cancel);
btn_ok = (Button)dialog.findViewById(R.id.btn_LogoutDialog_Ok);
btn_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dismissDialog(0);
}
});
btn_logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(HomeScreenActivity.this,LoginScreen.class);
startActivity(intent);
}
});
return dialog;
}
return null;
}
Thanks in advance.
Don't use
dialog.setContentView(R.layout.logoutdialog);
use
LayoutInflater class to set Dialog content view
Here is link (Check) you can get the idea May this helps you.
Change it by adding a parameter false like in the code below.
dialog.customView(R.layout.dialog_blueprint, false)
The second argument (false) is wrapTheDialogBoxInScrollView. If the content in the dialog box is small and does not require a ScrollView set it to false.

Categories

Resources