How to set max width for BottomSheetDialogFragment - android

Question
I'm using the BottomSheetDialogFragment for my modal bottom sheet and would like to set a maximum width so that on tablets/large screens the BottomSheet doesn't occupy the entire width of the screen. How do I approach solving this? Thanks!
Relevant code & resources
fragment_bottomsheet.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
style="#style/BottomSheetStyle">
<GridLayout
android:id="#+id/bottom_sheet"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:alignmentMode="alignBounds"
android:columnOrderPreserved="false"
android:columnCount="3"
android:paddingTop="16dp"
android:paddingBottom="8dp"
android:paddingRight="8dp"
android:paddingLeft="8dp"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="#drawable/image1"
android:text="Open"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="#drawable/image2"
android:text="Save"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="#drawable/image3"
android:text="Send"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="#drawable/image4"
android:text="Upload"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="#drawable/image5"
android:text="Share"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="#drawable/iamge6"
android:text="More"/>
</GridLayout>
</android.support.design.widget.CoordinatorLayout>
res/values/styles.xml:
<style name="BottomSheetStyle">
<item name="android:layout_height">match_parent</item>
<item name="android:layout_width">match_parent</item>
<item name="android:layout_gravity">center_horizontal</item>
</style>
res/values-w600dp/styles.xml:
<style name="BottomSheetStyle">
<item name="android:layout_height">match_parent</item>
<item name="android:layout_width">640dp</item>
<item name="android:layout_gravity">center_horizontal</item>
</style>

I found a solution which works for me:
#Override
public void onResume() {
super.onResume();
// Resize bottom sheet dialog so it doesn't span the entire width past a particular measurement
WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
int width = metrics.widthPixels < 1280 ? metrics.widthPixels : 1280;
int height = -1; // MATCH_PARENT
getDialog().getWindow().setLayout(width, height);
}
Essentially this allows me to dynamically specify dimensions for my BottomSheet based on display.

A variation of the OP's answer that takes into consideration device's pixel density and orientation:
public final class MyBottomSheetDialogFragment extends BottomSheetDialogFragment {
...
private static int dpToPx(int dp) {
// https://developer.android.com/guide/practices/screens_support.html#dips-pels
float density = Resources.getSystem().getDisplayMetrics().density;
return (int) ((dp * density) + 0.5f);
}
#Override
public void onResume() {
super.onResume();
Configuration configuration = getActivity().getResources().getConfiguration();
if (configuration.orientation == Configuration.ORIENTATION_LANDSCAPE &&
configuration.screenWidthDp > 450) {
// you can go more fancy and vary the bottom sheet width depending on the screen width
// see recommendations on https://material.io/components/sheets-bottom#specs
getDialog().getWindow().setLayout(ViewUtils.dpToPx(450), -1);
}
}
}

As you mention, BottomSheetDialogFragment does not seem to respect "wrap_content" (it always matches parent on width, even if all the views it contains have a width of "wrap_content"). I found that the best workaround for me was to utilize OnGlobalLayoutListener to listen for the appropriate time to adjust the width. Example:
#Override
public void setupDialog(final Dialog dialog, int style) {
super.setupDialog(dialog, style);
View v = View.inflate(getActivity(), R.layout.my_bottom_sheet, null);
View viewWithGreatestWidth = v.findViewById(R.id.my_super_wide_view);
// Your view setup code goes here ....
if(getResources().getBoolean(R.bool.isTablet)) {
v.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
v.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
v.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
// Can also just use your own preset "max width" value here;
// This code just lets you fake "wrap_content" value
getDialog().getWindow().setLayout(viewWithGreatestWidth.getMeasuredWidth(), WindowManager.LayoutParams.WRAP_CONTENT);
}
});
}
dialog.setContentView(v);
}

If you want to do it purely in xml, you can set a style and use android:maxWidth
For example:
<LinearLayout
android:id="#+id/bottom_sheet"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#color/white"
app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior"
style="#style/styleWithFixedWidth"
>
and in styles.xml
<style name="styleWithFixedWidth">
<item name="android:maxWidth">550dp</item>
</style>

Related

Android: how to configure sizing of a custom layout

I've been trying to create a custom horizontal layout with the goal to have a TextView to the left of an ImageView, containing a icon which depicts a certain status. The ImageView is to kept in a square dimension, with it's height and width equal to the height of the text in the TextView. Issues continue to persist, however, such as the text height not being set as specified in the layout xml file and an unknown padding existing after the ImageView. These problem can be seen in this image, with the red indicating the unknown padding and the blue indicating the text size inconsistency where both where set to 12sp. The font sizing and padding issues need to be fixed so the layout can be properly added to a grid layout, which will contain a grid of these custom layouts.
StatusIcon.java
//This is part of the java class that extends ImageView to resize the Icon
#Override
protected void onMeasure(int width, int height) {
super.onMeasure(width, height);
int measuredHeight = getMeasuredHeight();
setMeasuredDimension(measuredHeight, measuredHeight);
}
StatusIndicator.java
//This is the java class for the custom layout.
public class StatusIndicator extends LinearLayout {
private TextView label;
private StatusIcon statusLed;
private CharSequence labelText;
private float labelTextSize;
public enum Status {
GOOD,
WARNING,
CRITICAL
}
/*
* Removed the basic required class constructors to save space.
*/
private void getAttributes(Context context, AttributeSet attrs){
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.StatusIndicator);
labelText = typedArray.getString(R.styleable.StatusIndicator_label);
labelTextSize = typedArray.getDimensionPixelSize(R.styleable.StatusIndicator_labelSize, 0);
typedArray.recycle();
}
private void initializeViews(Context context){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.view_status_indicator, this);
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
//Setup UI elements in layout
label = (TextView) findViewById(R.id.textView_statusIndicatorLabel);
statusLed = (StatusIcon) findViewById(R.id.imageView_statusIndicatorLed);
label.setText(labelText);
if(labelTextSize > 0){
label.setTextSize(TypedValue.COMPLEX_UNIT_SP, labelTextSize);
}
}
public void setStatus(StatusIndicator.Status status){
switch (status){
case GOOD:
statusLed.setImageResource(R.mipmap.ic_status_panel_good);
break;
case WARNING:
statusLed.setImageResource(R.mipmap.ic_status_panel_warning);
break;
case CRITICAL:
statusLed.setImageResource(R.mipmap.ic_status_panel_critical);
break;
}
}
}
view_status_indicator.xml
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:parentTag="LinearLayout"
tools:orientation="horizontal">
<TextView
android:id="#+id/textView_statusIndicatorLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical|start"
android:layout_marginEnd="2dp"
android:text="#string/default_title"
android:textAppearance="#style/TextAppearance.AppCompat.Title"
android:textSize="12sp"/>
<com.css_design.android_quickbridge.ui.home.status_panel.StatusIcon
android:id="#+id/imageView_statusIndicatorLed"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_vertical|end"
app:srcCompat="#mipmap/ic_status_panel_critical"/>
</merge>
I would solve this problem by using ConstraintLayout instead of creating a custom view implementation.
ConstraintLayout allows you to specify an aspect ratio for its children, which takes care of wanting to make sure your ImageView is always exactly square. ConstraintLayout also allows you to specify height or width based on sibling views (by combining a dimension of 0dp with top and bottom (or left and right) constraints).
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ccf">
<ImageView
android:id="#+id/image"
android:layout_width="0dp"
android:layout_height="0dp"
android:src="#drawable/circle"
app:layout_constraintTop_toTopOf="#+id/text"
app:layout_constraintLeft_toRightOf="#+id/text"
app:layout_constraintBottom_toBottomOf="#+id/text"
app:layout_constraintDimensionRatio="1"/>
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40sp"
android:text="hello world"/>
</android.support.constraint.ConstraintLayout>
(Background color added to the ConstraintLayout to show that it's not any larger than its contents).

How to change ExpandableListView group indicator position?

I want to change the ExpandableListView group indicator to right with padding.
I used custom adapter to load data to ExpandableListView.
This is my ExpandableListView xml.
<ExpandableListView
android:id="#+id/Ex_offers"
android:layout_width="250dp"
android:layout_height="400dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:childDivider="#00000000"
android:groupIndicator="#drawable/settings_selector"
android:listSelector="#android:color/transparent">
</ExpandableListView>
This is GroupView xml
<TextView
android:id="#+id/lblListHeadertwo"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#drawable/transperant_bar"
android:fontFamily="Lato"
android:paddingLeft="15dp"
android:textColor="#daac56"
android:textStyle="bold"
android:textSize="17sp"
android:paddingTop="8dp" />
This is ChildView xml
<TextView
android:id="#+id/text_offers"
android:layout_width="300dp"
android:layout_height="20dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#drawable/transperant_bar"
android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft"
android:textColor="#daac56"
android:textSize="14sp"/>
<ImageView
android:id="#+id/img"
android:layout_width="15dp"
android:layout_height="15dp"
android:layout_marginLeft="12dp"/>
This is the output image, I want to set margin to this indicator.
setIndicatorBounds(int, int) does not work properly for Android 4.3.
They introduced a new method setIndicatorBoundsRelative(int, int) which works ok for 4.3.
public int GetPixelFromDips(float pixels) {
// Get the screen's density scale
final float scale = getResources().getDisplayMetrics().density;
// Convert the dps to pixels, based on density scale
return (int) (pixels * scale + 0.5f);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int width = metrics.widthPixels;
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
explvList.setIndicatorBounds(width-GetPixelFromDips(35), width-GetPixelFromDips(5));
} else {
explvList.setIndicatorBoundsRelative(width-GetPixelFromDips(35), width-GetPixelFromDips(5));
}
}
private void setGroupIndicatorToRight() {
/* Get the screen width */
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
expandableList.setIndicatorBounds(width - getDipsFromPixel(35), width - getDipsFromPixel(5));
}
// Convert pixel to dip
public int getDipsFromPixel(float pixels) {
// Get the screen's density scale
final float scale = getResources().getDisplayMetrics().density;
// Convert the dps to pixels, based on density scale
return (int) (pixels * scale + 250.5f);
}
If you want to move indicator to right Just create a dimen in res folder. It will be like that:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="my_value">350dp</dimen>
</resources>
Then in the <ExpandableListView/> add like that:
<ExpandableListView
...
android:indicatorLeft="#dimen/my_value"
.../>
You can change the dp according to device settings

remove padding around action bar left icon on Android 4.0+

I want to remove the padding around the icon on the left in the standard android 4.0+ action bar. I'm setting the icon with:
getActionBar().setIcon(getResources().getDrawable(R.drawable.ic_action_myapp));
And I would like the icon to fill vertically the space, touching both top and bottom, similar to what soundcloud app does:
Digging into AOSP sources, it seems the code involved is in com.android.internal.widget.ActionBarView.java. In particular the relevant part is the onLayout() method of the inner class ActionBarView$HomeView, partially reported below (lines 1433-1478):
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
...
final LayoutParams iconLp = (LayoutParams) mIconView.getLayoutParams();
final int iconHeight = mIconView.getMeasuredHeight();
final int iconWidth = mIconView.getMeasuredWidth();
final int hCenter = (r - l) / 2;
final int iconTop = Math.max(iconLp.topMargin, vCenter - iconHeight / 2);
final int iconBottom = iconTop + iconHeight;
final int iconLeft;
final int iconRight;
int marginStart = iconLp.getMarginStart();
final int delta = Math.max(marginStart, hCenter - iconWidth / 2);
if (isLayoutRtl) {
iconRight = width - upOffset - delta;
iconLeft = iconRight - iconWidth;
} else {
iconLeft = upOffset + delta;
iconRight = iconLeft + iconWidth;
}
mIconView.layout(iconLeft, iconTop, iconRight, iconBottom);
}
the same widget use this layout, defined in res/layout/action_bar_home.xml:
<view xmlns:android="http://schemas.android.com/apk/res/android"
class="com.android.internal.widget.ActionBarView$HomeView"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<ImageView android:id="#android:id/up"
android:src="?android:attr/homeAsUpIndicator"
android:layout_gravity="center_vertical|start"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="-8dip" />
<ImageView android:id="#android:id/home"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dip"
android:layout_marginTop="#android:dimen/action_bar_icon_vertical_padding"
android:layout_marginBottom="#android:dimen/action_bar_icon_vertical_padding"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:scaleType="fitCenter" />
</view>
According to sources the icon is shown in the Imageview with id=android.R.id.home. The onLayout() method reported above takes account of the ImageView margins defined in the layout, which can't be set via theme/style override because they use the value #android:dimen/action_bar_icon_vertical_padding.
All you can do is to get rid of those values at runtime, and set them according your needs:
simply retrieve the ImageView and set its top and bottom margins to 0. Something like this:
ImageView icon = (ImageView) findViewById(android.R.id.home);
FrameLayout.LayoutParams iconLp = (FrameLayout.LayoutParams) icon.getLayoutParams();
iconLp.topMargin = iconLp.bottomMargin = 0;
icon.setLayoutParams( iconLp );
EDIT: I've just realized I didn't cover how to get rid of left padding. Solution below.
Left padding on actionbar is affected by the Navigating Up behavior of actionbar icon. When that is disabled (via ActionBar.setDisplayHomeAsUpEnabled(false)) the left/up indicator is gone, but a left padding is used as well. A simple solution:
enable the actionbar up navigation using ActionBar.setDisplayHomeAsUpEnabled(true) in order to consider the indicator view in the layout process
force the drawable used as up indicator in your res/values-v14/styles.xml to null
eg:
<style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<!-- API 14 theme customizations can go here. -->
<item name="android:homeAsUpIndicator">#null</item>
</style>
I found an other resolution (reference appcompat-v7 ) that change the toolbarStyle ,following code:
<item name="toolbarStyle">#style/Widget.Toolbar</item>
<style name="Widget.Toolbar" parent="#style/Widget.AppCompat.Toolbar">
<item name="contentInsetStart">0dp</item>
</style>
use custom layout for ActionBar
public class TestActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActionBar actionBar = getActionBar();
actionBar.setCustomView(R.layout.actionbar_custom_view_home);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
setContentView(R.layout.main);
}
public void Click(View v) {
if (v.getId() == R.id.imageIcon) {
Log.e("click on--> ", "Action icon");
}
}
}
actionbar_custom_view_home.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center" >
<ImageView
android:id="#+id/imageIcon"
android:onClick="Click"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Large Icon With Title"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Enhanced parrzhang reply in remove padding around action bar left icon on Android 4.0+
private void adjustHomeButtonLayout(){
ImageView view = (ImageView)findViewById(android.R.id.home);
if(view.getParent() instanceof ViewGroup){
ViewGroup viewGroup = (ViewGroup)view.getParent();
View upView = viewGroup.getChildAt(0);
if(upView != null && upView.getLayoutParams() instanceof FrameLayout.LayoutParams){
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) upView.getLayoutParams();
layoutParams.width = 20;// **can give your own width**
upView.setLayoutParams(layoutParams);
}
}
}
To set the height of ActionBar you can create new Theme like this one:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.BarSize" parent="Theme.Sherlock.Light.DarkActionBar">
<item name="actionBarSize">48dip</item>
<item name="android:actionBarSize">48dip</item>
</style>
</resources>
and set this Theme to your Activity:
android:theme="#style/Theme.BarSize"
Now, set the height of the icons to "match_parent".
That would remove the top and bottom padding.
Now, the arrow at the left is inbuilt into the framework, so you have two options for a workaround:
Use ActionBarSherlock. It uses it's own drwables and resources, so you can modify the arrow icon to an emty png, so that your up icon would move to extreme left.
The up/back icon arises from:
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
}
So, instead of using this option for up button, you can make another actionbar option, which has an intent for the previous activity, and then place that icon on your action bar.
It will be a bigger workaround though.
Hope that helps.. :)
you can find homeview in actionbarview define like this:
<view xmlns:android="http://schemas.android.com/apk/res/android"
class="com.android.internal.widget.ActionBarView$HomeView"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<ImageView android:id="#android:id/up"
android:src="?android:attr/homeAsUpIndicator"
android:layout_gravity="center_vertical|start"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="-8dip" />
<ImageView android:id="#android:id/home"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dip"
android:layout_marginTop="#android:dimen/action_bar_icon_vertical_padding"
android:layout_marginBottom="#android:dimen/action_bar_icon_vertical_padding"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:scaleType="fitCenter" />
but you cannot get upView by findViewById(android.R.id.up).
so you can get homeView and get its parent view ,set upview width 0
ImageView view = (ImageView)findViewById(android.R.id.home);
if(view.getParent() instanceof ViewGroup){
ViewGroup viewGroup = (ViewGroup)view.getParent();
View upView = viewGroup.getChildAt(0);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) upView.getLayoutParams();
layoutParams.width = 0;
upView.setLayoutParams(layoutParams);
}

wrap_content height, but limited to half of parent

What I want is to have a layout with 2 views arranged vertically. Let's call the top view A and the bottom one B. I want the amount of height given to B to be its normal height (i.e. wrap content) except that I don't want it to be given more than half of the available space. A gets what is left.
Another way to word it is that A should always get at least 50% of the available height and B should get at most 50%.
I can't seem to find an easy way to achieve that. I can set both layout heights to 0 and give them equal weights which makes them both 50% always, but if B is smaller than 50% it should be given only what it needs.
The only way I can see to do it is use a custom class for A or B and override onMeasure to constrain the height to 50% of the parent, but it seems there should be an easier way.
Ok, I got it now. If I understood correctly you want to have it like this:
if A > B -> do nothing
if B > A & B > parent layout -> 50% to both of them
if B > A & B < parent layout -> A = parent layout - B
I had to do it all in onWindowFocusChanged because otherwise in onCreate the height of the Views would return 0. I did it with 2 LinearLayouts as child layouts, but you can take what ever you want.
My XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/parent_lay"
android:orientation="vertical"
android:layout_height="match_parent" >
//Layout A:
<LinearLayout
android:id="#+id/lay_1"
android:layout_width="match_parent"
android:background="#android:color/background_dark"
android:layout_height="10dp" >
</LinearLayout>
//Layout B:
<LinearLayout
android:id="#+id/lay_2"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#123456" >
</LinearLayout>
</LinearLayout>
MainActivity:
public class MainActivity extends Activity {
LinearLayout parent_lay;
LinearLayout lay_1;
LinearLayout lay_2;
int parent_height;
int lay_1_height;
int lay_2_heigth;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
parent_lay = (LinearLayout) findViewById(R.id.parent_lay);
lay_1 = (LinearLayout) findViewById(R.id.lay_1);
lay_2 = (LinearLayout) findViewById(R.id.lay_2);
lay_1_height = lay_1.getHeight();
lay_2_heigth = lay_2.getHeight();
parent_height = parent_lay.getHeight();
if (lay_2.getHeight() > lay_1.getHeight()
&& lay_2.getHeight() > (parent_lay.getHeight() / 2)) {
lay_1.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, 0, 1));
lay_2.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, 0, 1));
} else if (lay_2.getHeight() < (parent_lay.getHeight() / 2)) {
lay_1.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, (parent_height - lay_2_heigth)));
}
}
}
Example:
If A is 60dp and B is 40dp:
If A is 60dp and B is 400dp:
You must write your own component to achieve this.
For example, if you use LinearLayout here, you can extends a LinearLayout with overdid onMeasure method. You can implement onMeasure like this:
#Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int width = getMeasuredWidth();
final int height = getMeasuredHeight();
setMeasuredDimension(width, height / 2);
}
This code is not elegant enough. If you really want to do it well, copy the original onMeasure method from Android source code (http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/1.5_r4/android/widget/LinearLayout.java#LinearLayout.onMeasure%28int%2Cint%29), and in measureVertical(int widthMeasureSpec, int heightMeasureSpec), set mTotalLength = mTotalLength / 2.
For detailed information of onMeasure, visit http://developer.android.com/guide/topics/ui/custom-components.html and http://developer.android.com/reference/android/view/View.html#onMeasure(int, int).
Now the desired effect can be achieved with the ConstraintLayout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="match_parent">
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/containerFrameLayout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<android.support.constraint.Guideline
android:id="#+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5"/>
<FrameLayout
android:id="#+id/containerFrameLayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constrainedHeight="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/guideline"
app:layout_constraintVertical_bias="1">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</FrameLayout>
</android.support.constraint.ConstraintLayout>
Create a linear layout with two inner frames, each with .5 weight. Inside those frames, place your views, setting them to wrap_content or match_parent as appropriate.

How to make an alert dialog fill 90% of screen size?

I can create and display a custom alert dialog just fine but even so I have android:layout_width/height="fill_parent" in the dialog xml it is only as big as the contents.
What I want is dialog that fills the entire screen except maybe a padding of 20 pixel.
Then the image that is part of the dialog would automatically stretch to the full dialog size with fill_parent.
According to Android platform developer Dianne Hackborn in this discussion group post, Dialogs set their Window's top level layout width and height to WRAP_CONTENT. To make the Dialog bigger, you can set those parameters to MATCH_PARENT.
Demo code:
AlertDialog.Builder adb = new AlertDialog.Builder(this);
Dialog d = adb.setView(new View(this)).create();
// (That new View is just there to have something inside the dialog that can grow big enough to cover the whole screen.)
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(d.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.MATCH_PARENT;
d.show();
d.getWindow().setAttributes(lp);
Note that the attributes are set after the Dialog is shown. The system is finicky about when they are set. (I guess that the layout engine must set them the first time the dialog is shown, or something.)
It would be better to do this by extending Theme.Dialog, then you wouldn't have to play a guessing game about when to call setAttributes. (Although it's a bit more work to have the dialog automatically adopt an appropriate light or dark theme, or the Honeycomb Holo theme. That can be done according to http://developer.android.com/guide/topics/ui/themes.html#SelectATheme )
Try wrapping your custom dialog layout into RelativeLayout instead of LinearLayout. That worked for me.
Even simpler just do this:
int width = (int)(getResources().getDisplayMetrics().widthPixels*0.90);
int height = (int)(getResources().getDisplayMetrics().heightPixels*0.90);
alertDialog.getWindow().setLayout(width, height);
Specifying FILL_PARENT on the dialog window, like others suggested, did not work for me (on Android 4.0.4), because it just stretched the black dialog background to fill the whole screen.
What works fine is using the minimum display value, but specifying it within the code, so that the dialog takes 90% of the screen.
So:
Activity activity = ...;
AlertDialog dialog = ...;
// retrieve display dimensions
Rect displayRectangle = new Rect();
Window window = activity.getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
// inflate and adjust layout
LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.your_dialog_layout, null);
layout.setMinimumWidth((int)(displayRectangle.width() * 0.9f));
layout.setMinimumHeight((int)(displayRectangle.height() * 0.9f));
dialog.setView(layout);
In general only adjusting the width should be sufficient in most cases.
Set android:minWidth and android:minHeight in your custom view xml. These can force the alert not to just wrap content size.
Using a view like this should do it:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minWidth="300dp"
android:minHeight="400dp">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/icon"/>
</LinearLayout>
dialog.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
The following worked fine for me:
<style name="MyAlertDialogTheme" parent="Base.Theme.AppCompat.Light.Dialog.Alert">
<item name="windowFixedWidthMajor">90%</item>
<item name="windowFixedWidthMinor">90%</item>
</style>
(note: windowMinWidthMajor/Minor as suggested in previous answers didn't do the trick. My dialogs kept changing sizes depending on the content)
and then:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.MyAlertDialogTheme);
All of the other answers here makes sense, but it did not meet what Fabian needs. Here is a solution of mine. It may not be the perfect solution but it works for me. It shows a dialog which is on fullscreen but you can specify a padding on top, bottom, left or right.
First put this in your res/values/styles.xml :
<style name="CustomDialog" parent="#android:style/Theme.Dialog">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">#color/Black0Percent</item>
<item name="android:paddingTop">20dp</item>
<item name="android:windowContentOverlay">#null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:backgroundDimEnabled">false</item>
<item name="android:windowIsFloating">false</item>
</style>
As you can see I have there android:paddingTop= 20dp is basically what you need. The android:windowBackground = #color/Black0Percent is just a color code declared on my color.xml
res/values/color.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="Black0Percent">#00000000</color>
</resources>
That Color code just serves as a dummy to replace the default window background of the Dialog with a 0% transparency color.
Next build the custom dialog layout res/layout/dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/dialoglayout"
android:layout_width="match_parent"
android:background="#drawable/DesiredImageBackground"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/edittext1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:textSize="18dp" />
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Dummy Button"
android:textSize="18dp" />
</LinearLayout>
Finally here is our dialog that set custom view which uses our dialog.xml:
Dialog customDialog;
LayoutInflater inflater = (LayoutInflater) getLayoutInflater();
View customView = inflater.inflate(R.layout.dialog, null);
// Build the dialog
customDialog = new Dialog(this, R.style.CustomDialog);
customDialog.setContentView(customView);
customDialog.show();
Conclusion: I tried to override the dialog's theme in the styles.xml named CustomDialog. It overrides the Dialog window layout and gives me the chance to set a padding and change the opacity of the background. It may not be the perfect solution but I hope it helps you..:)
You can use percentage for (JUST) windows dialog width.
Look into this example from Holo Theme:
<style name="Theme.Holo.Dialog.NoActionBar.MinWidth">
<item name="android:windowMinWidthMajor">#android:dimen/dialog_min_width_major</item>
<item name="android:windowMinWidthMinor">#android:dimen/dialog_min_width_minor</item>
</style>
<!-- The platform's desired minimum size for a dialog's width when it
is along the major axis (that is the screen is landscape). This may
be either a fraction or a dimension. -->
<item type="dimen" name="dialog_min_width_major">65%</item>
All you need to do is extend this theme and change the values for "Major" and "Minor" to 90% instead 65%.
Regards.
Solution with actual 90% calculation:
#Override public void onStart() {
Dialog dialog = getDialog();
if (dialog != null) {
dialog.getWindow()
.setLayout((int) (getScreenWidth(getActivity()) * .9), ViewGroup.LayoutParams.MATCH_PARENT);
}
}
where getScreenWidth(Activity activity) is defined the following (best put in a Utils class):
public static int getScreenWidth(Activity activity) {
Point size = new Point();
activity.getWindowManager().getDefaultDisplay().getSize(size);
return size.x;
}
Get the device width:
public static int getWidth(Context context) {
DisplayMetrics displayMetrics = new DisplayMetrics();
WindowManager windowmanager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
windowmanager.getDefaultDisplay().getMetrics(displayMetrics);
return displayMetrics.widthPixels;
}
then use that for making dialog 90% of device,
Dialog filterDialog = new Dialog(context, R.style.searchsdk_FilterDialog);
filterDialog.setContentView(R.layout.searchsdk_filter_popup);
initFilterDialog(filterDialog);
filterDialog.setCancelable(true);
filterDialog.getWindow().setLayout(((getWidth(context) / 100) * 90), LinearLayout.LayoutParams.MATCH_PARENT);
filterDialog.getWindow().setGravity(Gravity.END);
filterDialog.show();
Well, you have to set your dialog's height and width before to show this ( dialog.show() )
so, do something like this:
dialog.getWindow().setLayout(width, height);
//then
dialog.show()
By far the most simplest way I can think of -
If your dialog is made out of a vertical LinearLayout, just add a "height filling" dummy view, that will occupy the entire height of the screen.
For example -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editSearch" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView"/>
<!-- this is a dummy view that will make sure the dialog is highest -->
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout>
Notice the android:weightSum="1" in the LinearLayout's attributes and the android:layout_weight="1" in the dummy View's attributes
Well, you have to set your dialog's height and width before to show this ( dialog.show() )
so, do something like this:
dialog.getWindow().setLayout(width, height);
//then
dialog.show()
Getting this code, i made it some changes:
dialog.getWindow().setLayout((int)(MapGeaGtaxiActivity.this.getWindow().peekDecorView().getWidth()*0.9),(int) (MapGeaGtaxiActivity.this.getWindow().peekDecorView().getHeight()*0.9));
however, dialog size's could change when the device change its position. Perhaps you need to handle by your own when metrics changes.
PD: peekDecorView, implies that layout in activity is properly initialized otherwise you may use
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int wwidth = metrics.widthPixels;
in order to get screen size
After initialize your dialog object and set the content view. Do this and enjoy.
(in the case i am setting 90% to width and 70% to height because width 90% it will be over toolbar )
DisplayMetrics displaymetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = (int) ((int)displaymetrics.widthPixels * 0.9);
int height = (int) ((int)displaymetrics.heightPixels * 0.7);
d.getWindow().setLayout(width,height);
d.show();
Just give the AlertDialog this theme
<style name="DialogTheme" parent="Theme.MaterialComponents.Light.Dialog.MinWidth">
<item name="colorPrimary">#color/colorPrimary</item>
<item name="android:windowMinWidthMajor">90%</item>
<item name="android:windowMinWidthMinor">90%</item>
</style>
***In Kotlin You can Code like This : -***
fun customDialog(activity: Activity?, layout: Int): Dialog {
val dialog = Dialog(activity!!)
try {
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.setCancelable(false)
dialog.setContentView(layout)
dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
dialog.window!!.setLayout(ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);
dialog.show()
} catch (e: Exception) {
}
return dialog
}
My answer is based on the koma's but it doesn't require to override onStart but only onCreateView which is almost always overridden by default when you create new fragments.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.your_fragment_layout, container);
Rect displayRectangle = new Rect();
Window window = getDialog().getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
v.setMinimumWidth((int)(displayRectangle.width() * 0.9f));
v.setMinimumHeight((int)(displayRectangle.height() * 0.9f));
return v;
}
I've tested it on Android 5.0.1.
Above many of the answers are good but none of the worked for me fully. So i combined the answer from #nmr and got this one.
final Dialog d = new Dialog(getActivity());
// d.getWindow().setBackgroundDrawable(R.color.action_bar_bg);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.dialog_box_shipment_detail);
WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE); // for activity use context instead of getActivity()
Display display = wm.getDefaultDisplay(); // getting the screen size of device
Point size = new Point();
display.getSize(size);
int width = size.x - 20; // Set your heights
int height = size.y - 80; // set your widths
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(d.getWindow().getAttributes());
lp.width = width;
lp.height = height;
d.getWindow().setAttributes(lp);
d.show();
...
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
Dialog d = builder.create(); //create Dialog
d.show(); //first show
DisplayMetrics metrics = new DisplayMetrics(); //get metrics of screen
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = (int) (metrics.heightPixels*0.9); //set height to 90% of total
int width = (int) (metrics.widthPixels*0.9); //set width to 90% of total
d.getWindow().setLayout(width, height); //set layout
Here is my variant for custom dialog's width:
DisplayMetrics displaymetrics = new DisplayMetrics();
mActivity.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = (int) (displaymetrics.widthPixels * (ThemeHelper.isPortrait(mContext) ? 0.95 : 0.65));
WindowManager.LayoutParams params = getWindow().getAttributes();
params.width = width;
getWindow().setAttributes(params);
So depending on device orientation (ThemeHelper.isPortrait(mContext)) dialog's width will be either 95% (for portrait mode) or 65% (for landscape). It's a little more that the author asked but it could be useful to someone.
You need to create a class that extends from Dialog and put this code into your onCreate(Bundle savedInstanceState) method.
For dialog's height the code should be similar to this.
public static WindowManager.LayoutParams setDialogLayoutParams(Activity activity, Dialog dialog)
{
try
{
Display display = activity.getWindowManager().getDefaultDisplay();
Point screenSize = new Point();
display.getSize(screenSize);
int width = screenSize.x;
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
layoutParams.copyFrom(dialog.getWindow().getAttributes());
layoutParams.width = (int) (width - (width * 0.07) );
layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
return layoutParams;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
You need to use a style #style.xml such as CustomDialog to displaying the customize-able dialog.
<style name="CustomDialog" parent="#android:style/Theme.DeviceDefault.Light.Dialog">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">#color/colorWhite</item>
<item name="android:editTextColor">#color/colorBlack</item>
<item name="android:windowContentOverlay">#null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:backgroundDimEnabled">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
</style>
and use this style in Activity.java like this
Dialog dialog = new Dialog(Activity.this, R.style.CustomDialog);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_dialog);
and your custom_dialog.xml should inside your layout directory
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:textSize="20dp"
android:id="#+id/tittle_text_view"
android:textColor="#color/colorBlack"
android:layout_marginTop="20dp"
android:layout_marginLeft="10dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginLeft="20dp"
android:layout_marginBottom="10dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp">
<EditText
android:id="#+id/edit_text_first"
android:layout_width="50dp"
android:layout_height="match_parent"
android:hint="0"
android:inputType="number" />
<TextView
android:id="#+id/text_view_first"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:gravity="center"/>
<EditText
android:id="#+id/edit_text_second"
android:layout_width="50dp"
android:layout_height="match_parent"
android:hint="0"
android:layout_marginLeft="5dp"
android:inputType="number" />
<TextView
android:id="#+id/text_view_second"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:gravity="center"/>
</LinearLayout>
</LinearLayout>
Based in part on Anand's answer. This works for me:
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val fragmentActivity = requireActivity()
val v = View.inflate(context, R.layout.fragment_about_dialog, null)
val dialog = Dialog(fragmentActivity)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.setContentView(v)
val wm = fragmentActivity.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val display = if (VERSION.SDK_INT >= VERSION_CODES.R) {
fragmentActivity.display
} else {
wm.defaultDisplay // deprecated in API 30
}
val size = Point()
display?.getSize(size)
val width = size.x - 50
val height = size.y - 50
val lp = WindowManager.LayoutParams()
lp.copyFrom(dialog.window?.attributes)
lp.width = width
lp.height = height
dialog.show()
dialog.window?.attributes = lp
return dialog
}
For dialog layout used constraintLayout:
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/dialogLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
...
</androidx.constraintlayout.widget.ConstraintLayout>
Result:
This works fine when changing screen orientation.
Here is a short answer that worked for me (Tested on API 8 and API 19).
Dialog mDialog;
View mDialogView;
...
// Get height
int height = mDialog.getWindow()
.getWindowManager().getDefaultDisplay()
.getHeight();
// Set your desired padding (here 90%)
int padding = height - (int)(height*0.9f);
// Apply it to the Dialog
mDialogView.setPadding(
// padding left
0,
// padding top (90%)
padding,
// padding right
0,
// padding bottom (90%)
padding);
If you are using Constraint Layout, you can set any view inside it, to fill a percentage of the screen with:
layout_constraintWidth_percent="0.8"
So, for example, if you have a ScrollView inside the dialog and you want to set it to a percentage of the screen height. It would be like this:
<ScrollView
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintHeight_percent="0.8">
Hope it helps someone !!
If you use dialog fragment you can do it on onResume method.
It's code for Xamarin Android, but I think it so easy to understand it
public override void OnResume()
{
base.OnResume();
var metrics = Resources.DisplayMetrics;
double width = metrics.WidthPixels * 0.9;
double height = metrics.HeightPixels * 0.6;
this.Dialog.Window.SetLayout((int)width, (int)height);
this.Dialog.Window.SetGravity(Android.Views.GravityFlags.Center);
}
Make your dialog an activity. 3 Steps
STEP 1:
Put one of these in styles.xml
Style One:
I like this one because you can change the parent theme to the name of your theme that you are using for the rest of your app.
<style name="DialogTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">#color/transparent</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowMinWidthMajor">90%</item>
<item name="android:windowMinWidthMinor">90%</item>
</style>
Style Two:
<style name="DialogTheme" parent="Theme.AppCompat.Dialog">
<item name="android:windowMinWidthMajor">90%</item>
<item name="android:windowMinWidthMinor">90%</item>
</style>
STEP 2:
Then put this in AndroidManifest.xml
<activity
android:name="com.example.YourApp.DialogActivity"
android:theme="#style/DialogTheme" />
STEP 3:
And make sure you have your main layout width fill_parent or match_parent in activity_dialog.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
tools:context=".DialogActivity">
</androidx.constraintlayout.widget.ConstraintLayout>
dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.WRAP_CONTENT);
final AlertDialog alertDialog;
LayoutInflater li = LayoutInflater.from(mActivity);
final View promptsView = li.inflate(R.layout.layout_dialog_select_time, null);
RecyclerView recyclerViewTime;
RippleButton buttonDone;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mActivity);
alertDialogBuilder.setView(promptsView);
// create alert dialog
alertDialog = alertDialogBuilder.create();
/**
* setting up window design
*/
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.show();
DisplayMetrics metrics = new DisplayMetrics(); //get metrics of screen
mActivity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = (int) (metrics.heightPixels * 0.9); //set height to 90% of total
int width = (int) (metrics.widthPixels * 0.9); //set width to 90% of total
alertDialog.getWindow().setLayout(width, height); //set layout
recyclerViewTime = promptsView.findViewById(R.id.recyclerViewTime);
DialogSelectTimeAdapter dialogSelectTimeAdapter = new DialogSelectTimeAdapter(this);
RecyclerView.LayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerViewTime.setLayoutManager(linearLayoutManager);
recyclerViewTime.setAdapter(dialogSelectTimeAdapter);
buttonDone = promptsView.findViewById(R.id.buttonDone);
buttonDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertDialog.dismiss();
}
});

Categories

Resources