Android - how to set dialog's outer margin - android

I know that this question have been asked a few times, but none of the solutions I came across worked for me, hence this topic. As the title states - I want to set dialog's outer margin:
PurchaseDetailsDialogFragment
public class PurchaseDetailsDialogFragment extends DialogFragment {
private static final String MAX_AMOUNT = "maxAmount";
private static final String UNIT_PRICE = "unitPrice";
private static final String PICKUP_TIME_FROM = "pickupTimeFrom";
private static final String PICKUP_TIME_TO = "pickupTimeTo";
public PurchaseDetailsDialogFragment() { }
public static PurchaseDetailsDialogFragment newInstance(int maxAmount, float unitPrice, String pickupTimeFrom, String pickupTimeTo) {
PurchaseDetailsDialogFragment fragment = new PurchaseDetailsDialogFragment();
Bundle args = new Bundle();
args.putInt(MAX_AMOUNT, maxAmount);
args.putFloat(UNIT_PRICE, unitPrice);
args.putString(PICKUP_TIME_FROM, pickupTimeFrom);
args.putString(PICKUP_TIME_TO, pickupTimeTo);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
int maxAmount = getArguments().getInt(MAX_AMOUNT);
float unitPrice = getArguments().getFloat(UNIT_PRICE);
String pickupFrom = getArguments().getString(PICKUP_TIME_FROM);
String pickupTo = getArguments().getString(PICKUP_TIME_TO);
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Context context = getContext();
FragmentPurchaseDetailsDialogBinding binding = DataBindingUtil.inflate(
LayoutInflater.from(context),
R.layout.fragment_purchase_details_dialog,
null,
false);
binding.setDataContext(new PurchaseDetailsViewModel(context));
AlertDialog dialog = new AlertDialog.Builder(getActivity(), R.style.DialogTheme)
.setView(binding.getRoot())
.create();
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
return dialog;
}
}
fragment_purchase_details_dialog
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#drawable/dialog">
<data>
<variable
name="dataContext"
type="com.myapp.viewModels.PurchaseDetailsViewModel" />
</data>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="80dp"
android:paddingTop="20dp"
android:layout_centerHorizontal="true"
android:background="#color/white">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/choose_amount"
style="#style/Widget.App.PurchaseTextViewTitle" />
</FrameLayout>
<LinearLayout
android:id="#+id/dialogCentralContent"
android:layout_width="match_parent"
android:layout_height="200dp"
android:orientation="vertical"
android:layout_marginTop="80dp"
android:background="#color/dirtyWhite">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="74" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="46dp"
android:layout_centerHorizontal="true">
<Button
android:layout_width="44dp"
android:layout_height="44dp"
android:layout_marginTop="6dp"
android:background="#drawable/button_filled"
android:text="-"
style="#style/Widget.App.PurchaseIncDecButton" />
<FrameLayout
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:background="#drawable/edittext_white_rounded">
<EditText
android:layout_width="30dp"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
android:gravity="center_horizontal"
android:maxLines="1"
style="#style/Widget.App.PurchaseAmountEditText" />
</FrameLayout>
<Button
android:layout_width="44dp"
android:layout_height="44dp"
android:layout_marginTop="6dp"
android:background="#drawable/button_filled"
android:text="+"
style="#style/Widget.App.PurchaseIncDecButton" />
</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_below="#+id/dialogCentralContent"
android:text="#string/buttonBuyText"
android:background="#drawable/button_submit"
style="#style/Widget.App.SubmitButton" />
</RelativeLayout>
</layout>
Now with the above code only, my dialog takes up whole width of the screen. If I however do this, in the fragment java code:
AlertDialog dialog = new AlertDialog.Builder(getActivity(), R.style.DialogTheme) /// the rest of the code
And add a theme:
<resources>
<style name="DialogTheme" parent="#android:style/Theme.Material.Dialog.Alert">
<item name="android:windowMinWidthMajor">380dp</item>
<item name="android:windowMinWidthMinor">380dp</item>
</style>
</resources>
Then some funky stuff happens. On API23 all looks fine, while on API19 and below (didn't check apis between 19 and 23) the dialog is 100% wide and aligned to top of the screen. How to make it work the way I'd like it to?

There's one really simple solution to this. Just put your layout inside, for example a FrameLayout and set appropriate paddings on the outer layout element. Then everything is gonna look the same across all apis:
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/defaultMargin"
android:paddingRight="#dimen/defaultMargin">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</RelativeLayout>
</FrameLayout>

Have you tried this ?
How to Build AppCompatDialog From AlertDialog.Builder or Equivalent?
It suggests you to use android.support.v7.app.AlertDialog rather than android.app.AlertDialog
So for dialogs with multiple choices try AppCompactDialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.DialogTheme)
.setView(binding.getRoot())
.create();
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
AppCompatDialog alert = builder.create();
alert.show();
I have not tried this. Let me know if this works.

<item name="android:windowMinWidthMinor">380dp</item>
this will keep the dialog width to be a mininum of 380dp, but if device width < 380dp, then the dialog will take up the whole available space
If you tested with a device with a smaller width(very likely if the device has a lower api, for example Galaxy Nexus's width is 360dp), of course it will take up the whole width.
It's better to specify the minWidth as a percentage
for your particular case, to achieve a predefined margin(without modifying the Window's layout attributes programmatically), we can set the min width to be 100%
<item name="android:windowMinWidthMinor">100%</item>
and use an inset drawble as the windowBackground, which is already the case if you are using AppCompat
<item name="android:windowBackground">#drawable/abc_dialog_material_background</item>
abc_dialog_material_background:
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetLeft="16dp"
android:insetTop="16dp"
android:insetRight="16dp"
android:insetBottom="16dp">
<shape android:shape="rectangle">
<corners android:radius="#dimen/abc_dialog_corner_radius_material" />
<solid android:color="#android:color/white" />
</shape>
</inset>

Related

Custom Alertdialog width is bigger than the shown width in layout xml

I am trying to create custom alertdialog. Here is my alertdialog custom layout xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center"
android:orientation="horizontal">
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:text="Processing" />
</LinearLayout>
</RelativeLayout>
and the code from activity where i call custom alertdialog
LayoutInflater inflater = MainActivity.this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.layoutalertprogress, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setView(dialogView);
alertDialog = alertDialogBuilder.create();
if(!alertDialog.isShowing())
{
alertDialog.show();
}
problem is even in layout file linearlayout width is wrapped to its content like this
the real width of alertdialog looks like this in runtime
so the real width of alertdialog is wider (wider than the layout shown above).
It seems that linearlayout width is not wrapped to its contents so there is big unused space from its edges to its child elements. how to make this linearlayout width to wrap its contents so the unused space from its edges can be removed? Thanks
Try this
set background color to child LinearLayout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center"
android:background="#android:color/white"
android:orientation="horizontal">
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Processing" />
</LinearLayout>
</RelativeLayout>
and then add this line in your java code
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
after this
AlertDialog alertDialog = alertDialogBuilder.create();
Use simply just setLayout method with your desired width and height. This will make your dialog width and height as specified.
Kotlin version,
private fun showDialog() {
val dialog = AlertDialog.Builder(this)
val layout = LayoutInflater.from(this).inflate(R.layout.custom_dialog_layout, null, false)
dialog.setView(layout)
val alert = dialog.create()
alert.show()
alert.window?.setBackgroundDrawableResource(android.R.color.transparent)
alert.window?.setLayout(600, 600)
}
LayoutInflater inflater = MainActivity.this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.layoutalertprogress, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setView(dialogView);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000")));
if(!alertDialog.isShowing())
{
alertDialog.show();
}
I faced the same problem and the solution which worked for me is:
Create a theme with the followings:
<style name="yourThemeName" parent="Theme.AppCompat.Dialog">
...
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">#android:color/transparent</item>
</style>
And then in code:
inflatedView= layoutInflater.inflate(R.layout.yourLayoutId, null)
dialog = AlertDialog.Builder(this, R.style.yourThemeName)
.setView(inflatedView)
dialog.show()
change your relative layout as below
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center"
android:orientation="horizontal">
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:text="Processing" />
</LinearLayout>
</LinearLayout>
Create a theme for alertdialog in style.xml as below
<style name="AlertDialogCustom" parent="AlertDialog.AppCompat">
<item name="android:textColor">#00FF00</item>
<item name="android:typeface">monospace</item>
<item name="android:textSize">10sp</item>
<item name="android:layout_width">wrap_content</item>
</style>
Create below method to call your dialog.
public void showDemoDialog() {
LayoutInflater inflater = MainActivity.this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.demodg, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this, R.style.AlertDialogCustom);
alertDialogBuilder.setView(dialogView);
AlertDialog alertDialog = alertDialogBuilder.create();
if (!alertDialog.isShowing()) {
alertDialog.show();
alertDialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
}
This is the result when run on device.

DialogPreference in Full Screen Width

I created a custom dialog preference in my Android application, but I can not figure out how to get the dialog which is displayed to span the complete width of the display.
image of dialog with too much space on left and right side
I found many proposed solutions to get a normal Dialog in full screen mode
Android get full width for custom Dialog
https://gist.github.com/koocbor/88db64192638bff09aa4
http://blog.jimbaca.com/force-dialog-to-take-up-full-screen-width/
But setting the attributes via getWindow does not work:
#Override
public Dialog getDialog() {
Dialog dialog = super.getDialog();
dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
// or
// dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
return dialog;
}
And applying a full screen theme to my dialogs root element didn't do the job neither:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
[...]
android:theme="#style/FullscreenTheme">
Moreover I'm not able to access the onCreate Method (at least I don't know how) of the Dialog, to set the style there.
Did anyone had the same problem and figured out a solution for this very specific issue?
My layout:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:orientation="vertical"
android:padding="0dp"
android:paddingTop="#dimen/preferences_dialog_def_padding"
android:paddingBottom="#dimen/preferences_dialog_def_padding">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginTop="-2dp"
android:background="#color/expandable_preference_divider"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/preferences_expandable_margin_top_bottom"
android:layout_marginTop="#dimen/preferences_expandable_margin_top_bottom">
<RelativeLayout
android:id="#+id/icon_wrapper_choose"
android:layout_width="#dimen/preferences_expandable_icon_wrapper_size"
android:layout_height="#dimen/preferences_expandable_icon_wrapper_size"
android:layout_marginBottom="0dp"
android:layout_marginEnd="#dimen/preference_expandable_icon_margin"
android:layout_marginStart="#dimen/preference_expandable_icon_margin"
android:layout_marginTop="0dp"
android:gravity="center">
<ImageView
android:layout_width="#dimen/preferences_expandable_icon_size"
android:layout_height="#dimen/preferences_expandable_icon_size"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:cropToPadding="true"
android:scaleType="centerCrop"
android:src="#drawable/ic_settings_white_36dp"/>
</RelativeLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/icon_wrapper_choose"
android:paddingBottom="#dimen/preferences_expandable_text_padding_top_bottom"
android:paddingTop="#dimen/preferences_expandable_text_padding_top_bottom"
android:text="#string/pref_wheel_circumference_choose"
android:textColor="#color/colorAccent"
android:textSize="#dimen/text_size_medium"
android:textStyle="bold"/>
</RelativeLayout>
<TextView
android:layout_width="match_parent"
android:layout_marginEnd="#dimen/preference_expandable_icon_margin"
android:layout_marginStart="#dimen/preference_expandable_icon_margin"
android:layout_height="wrap_content"
android:text="#string/etrto_hint"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeight"
android:orientation="horizontal"
android:paddingBottom="20dp"
android:paddingEnd="?android:attr/scrollbarSize"
android:layout_marginStart="#dimen/preference_expandable_icon_margin"
android:weightSum="3"
>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/etrto"/>
<Spinner
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingBottom="20dp"
android:paddingEnd="?android:attr/scrollbarSize"
android:layout_marginStart="#dimen/preference_expandable_icon_margin"
android:weightSum="3"
>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/manufacturer"/>
<Spinner
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"/>
</LinearLayout>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginTop="-2dp"
android:background="#color/expandable_preference_divider"/>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/preference_category_wrapper"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:orientation="vertical"
android:padding="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/preferences_expandable_margin_top_bottom"
android:layout_marginTop="#dimen/preferences_expandable_margin_top_bottom">
<RelativeLayout
android:id="#+id/icon_wrapper_manual"
android:layout_width="#dimen/preferences_expandable_icon_wrapper_size"
android:layout_height="#dimen/preferences_expandable_icon_wrapper_size"
android:layout_marginBottom="0dp"
android:layout_marginEnd="#dimen/preference_expandable_icon_margin"
android:layout_marginStart="#dimen/preference_expandable_icon_margin"
android:layout_marginTop="0dp"
android:gravity="center">
<ImageView
android:id="#+android:id/icon"
android:layout_width="#dimen/preferences_expandable_icon_size"
android:layout_height="#dimen/preferences_expandable_icon_size"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:cropToPadding="true"
android:scaleType="centerCrop"
android:src="#drawable/ic_edit_white_36dp"/>
</RelativeLayout>
<TextView
android:id="#+android:id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toEndOf="#+id/icon_wrapper_manual"
android:paddingBottom="#dimen/preferences_expandable_text_padding_top_bottom"
android:paddingTop="#dimen/preferences_expandable_text_padding_top_bottom"
android:text="#string/pref_wheel_circumference_manually"
android:textColor="#color/colorAccent"
android:textSize="#dimen/text_size_medium"
android:textStyle="bold"/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeight"
android:orientation="horizontal"
android:paddingBottom="20dp"
android:paddingEnd="?android:attr/scrollbarSize"
android:layout_marginStart="#dimen/preference_expandable_icon_margin"
android:weightSum="2.5"
>
<EditText
android:id="#+id/pref_dialog_wheelcircumference_et"
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="wrap_content"
android:textAlignment="textEnd"
android:textColor="#color/colorFont"
android:textSize="#dimen/text_size_small"
android:inputType="number"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:textAlignment="center"
android:text="#string/wheel_circumference_unit"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
My custom preference class
public class WheelCircumferencePreference extends android.preference.DialogPreference {
private static String TAG = "CustomSwitchPreference";
private int mWheelCircumference;
public static int WHEEL_CIRCUMFERENCE_DEFAULT = 2125;
private int mDialogLayoutResId = R.layout.pref_dialog_wheelcircumference;
public WheelCircumferencePreference(Context context) {
this(context, null);
}
public WheelCircumferencePreference(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.dialogPreferenceStyle);
}
public WheelCircumferencePreference(Context context, AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
setLayoutResource(R.layout.custom_preference);
setDialogLayoutResource(mDialogLayoutResId);
setPositiveButtonText(getContext().getString(R.string.dialog_save));
setNegativeButtonText(getContext().getString(R.string.dialog_cancel));
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index) {
// Default value from attribute. Fallback value is set to WHEEL_CIRCUMFERENCE_DEFAULT.
return a.getInteger(index, WHEEL_CIRCUMFERENCE_DEFAULT);
}
#Override
protected void onSetInitialValue(boolean restorePersistedValue,
Object defaultValue) {
would load value from shared preferences
if (restorePersistedValue) {
mWheelCircumference = getPersistedInt(WHEEL_CIRCUMFERENCE_DEFAULT);
} else {
mWheelCircumference = (Integer) defaultValue;
persistInt(mWheelCircumference);
}
}
private EditText mWheelCircumferenceEt;
#Override
protected void onBindDialogView(View view) {
mWheelCircumferenceEt = view.findViewById(R.id.pref_dialog_wheelcircumference_et);
if (mWheelCircumferenceEt == null) {
throw new IllegalStateException("preference dialog view must contain" +
" a EditText with id 'pref_dialog_wheelcircumference_et'");
}
mWheelCircumferenceEt.setText(Integer.toString(mWheelCircumference));
super.onBindDialogView(view);
}
#Override
public Dialog getDialog() {
//Dialog dialog = super.getDialog();
// WindowManager.LayoutParams p = getDialog().getWindow().getAttributes();
//p.height = LinearLayout.LayoutParams.WRAP_CONTENT;
//dialog.getWindow().setAttributes(p);
return dialog;
}
#Override
protected void onDialogClosed(boolean positiveResult) {
if (positiveResult) {
String circumferenceText = mWheelCircumferenceEt.getText().toString();
try {
mWheelCircumference = Integer.parseInt(circumferenceText);
} catch (Exception e) {
NLog.e(TAG, "onDialogClosed - ", e);
mWheelCircumference = WheelCircumferencePreference.WHEEL_CIRCUMFERENCE_DEFAULT;
}
persistInt(mWheelCircumference);
}
}
Edit:
Actually I only want the dialog to span over the full width of the screen, not the height. If I would use a additional PreferenceFragment (as the DialogPreference is already embedded in a PreferenceFragment ) the "Dialog" (aka Fragment) would take the complete width and height (i guess).
I already implemented a solution without a DialogPrefrence, that works but is not exactly elegant
using just a normal EditTextPreference
adding an onPreferenceClickListener to this preference in my SettingsFragment Code
the ClickListener displays a simple Dialog
Example:
Preference preference = findPreference(EXAMPLE_PREFRENCE);
if (preference != null) {
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
// showDialog();
}
});
But as I have a lot of preferences which will display dialogs the code for the dialog creation and display bloads the SettingsFragment and makes it nearly unreadable. Therefore I thought it would be a nice solution to put the responsibility of displaying the dialog and handling the preference values to the Preference and the XML layout.
Unfortunately I got stuck with the "full width issue" mentioned above.
Note: fixed the code of getDialog as I tested different versions (also in combination with the xml theme set)
Finally I did find a solution for this problem:
Fetch the AlertDialog of the Preference in showDialog method
#Override
protected void showDialog(Bundle state) {
super.showDialog(state);
CustomDialogPreference.makeDialogFullScreen((AlertDialog) getDialog());
}
make it span the complete width:
public static void makeDialogFullScreen(AlertDialog d) {
NLog.d(TAG, "makeDialogFullScreen enter ");
if (d != null) {
ViewGroup.LayoutParams params = d.getWindow().getAttributes();
if (params != null) {
params.width = WindowManager.LayoutParams.MATCH_PARENT;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
d.getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
}
}
}
Try this in the onResume of your dialog.
// Store access variables for window and blank point
Window window = getDialog().getWindow();
Point size = new Point();
// Store dimensions of the screen in `size`
Display display = window.getWindowManager().getDefaultDisplay();
display.getSize(size);
// Set the width of the dialog proportional to 75% of the screen width and height
window.setLayout((int) (size.x * 0.75), (int) (size.y * 0.75));
window.setGravity(Gravity.CENTER);
// Call super onResume after sizing
Adjust accordingly for 100%. It works great for a dialogFragment. Haven't tried it for your case though.
Wait, you're not looking for the bog-standard 'Pref settings user options appear in a dialog' thing are you? That's almost definitely already done in AndroidStudio's add activity...> Settings Activity in boiler plate, check it out, or look for sample settings apps
Anyway, I do actually have a fullscreen dialog in my app, although it purposely doesn't fill the full screen, and I actually use an activity with some fragments now instead.
Personally I think this is what your problem is, I remember having this exact issue when I first needed a dialog like this. You should just use activities and have up navigation (if you want a full screen "popup" type thing you could use the Navigation pattern that makes the home/up button an 'X' instead of a '<');
Or anything else, you don't need to have a dialog explicitly, and if you do then extend activity or dialog and get what you want.
Here's my activity stuff in case it's any use
my theme:
<style name="AppTheme.FullScreenDialog"
parent="#style/Theme.AppCompat.Light.Dialog">
<item name="windowActionBar">true</item>
<item name="windowNoTitle">true</item>
</style>
my onCreate gist:
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
...
requestWindowFeature(Window.FEATURE_NO_TITLE);
...
super.onCreate(savedInstanceState);
setContentView(getConcreteContentView());
ButterKnife.bind(this);
setUpUIComponents();
...
}
my general layout gist:
<CoordinatorLayout>
<AppBarLayout>
<android.support.v7.widget.Toolbar/>
</android.support.design.widget.AppBarLayout>
<RelativeLayout
android:id="#+id/container_main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:paddingTop="6dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<RelativeLayout
android:id="#+id/container_recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_security_word"
android:paddingEnd="18dp"
android:paddingStart="18dp" />
<RelativeLayout
android:id="#+id/container_security"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/container_recycler"
android:minHeight="150dp"
android:paddingEnd="18dp"
android:paddingStart="18dp"
android:visibility="visible" />
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/security_container"
android:layout_centerHorizontal="true"
android:contentDescription="#string/app_name"
android:minHeight="50dp"
android:scaleType="centerInside" />
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
Bon Chance!

How to customise android dialogs to material theme?

I wanted to customise android Dialog to make it look like a floating dialog as below which is suggested in https://material.google.com/components/dialogs.html#dialogs-simple-dialogs
I tried creating a DialogFragment in which onCreateDialog returns a Dialog with a view whose root is a CardView.But couldn't get the expected result.Can I have some suggestions on how to achieve this?
My layout looks like this,
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center|top"
card_view:cardElevation="5dp"
card_view:cardPreventCornerOverlap="false">
//Contents come here
</android.support.v7.widget.CardView>
and in code,
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = new Dialog(getActivity());
View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_font_selection,null,false);
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(view);
float width = (I am getting screen width here) * .80f;
dialog.getWindow().setLayout((int) width, ViewGroup.LayoutParams.WRAP_CONTENT);
return dialog;
}`
but the result looks like this,
Instead of getting elevation I was getting a black shade
AlertDialog.Builder mydialog = new AlertDialog.Builder( context);
mydialog.setTitle("Set backup accounts");
mydialog.setItems(CharSequence[] items, OnClickListener);
mydialog.show();
mydialog.setContentView(R.layout.mydialogLayout);
This in your activity/fragment. And so declare your layout as follow:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<TextView
android:id="#+id/myID1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
After that, if you want to handle the clicks just do that:
TextView myView1 = (TextView) mydialog.findViewById(myID1);
myView1.setOnClickListener(...);
MaterialAlertDialogBuilder is now available for Android:
material.io/develop/android/components/dialog

how to remove rectangle frame of the custom dialog

i custom a dialog :
public class CustomizeDialog extends Dialog implements OnClickListener {
Button close;
TextView tv;
public CustomizeDialog(Context context,String Stringcontent) {
super(context);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_diolog_main);
tv=(TextView) findViewById(R.id.content);
tv.setText(Stringcontent);
close = (Button) findViewById(R.id.close);
close.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == close)
dismiss();
}
}
the xml is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="100dip"
android:orientation="vertical"
android:background="#drawable/custom_diolog_bg"
android:layout_width="250dip">
<TextView android:layout_height="wrap_content"
android:textColor="#000"
android:textStyle="bold"
android:textSize="18sp"
android:id="#+id/content"
android:layout_marginLeft="15dip"
android:layout_marginTop="5dip"
android:layout_alignParentTop="true"
android:layout_width="250dip"
android:text=" Custom Dialog "/>
<Button android:layout_width="70dip"
android:layout_marginLeft="80dip"
android:background="#drawable/custom_dialog_button_bg"
android:layout_alignParentBottom="true"
android:layout_height="40dip" android:text="关闭"
android:id="#+id/close"></Button>
</RelativeLayout>
my dialog is vrry well,but custom_diolog_bg is a rounded rectangle image,and when i show my dialog ,it show a system Frame behide my custom,so i used this.getwindow.setBackgroundDrawable(null),then the system Frame seems have remove but only the Four Corners not remove,we also see dark Four Corners,because i used the rounded rectangle image.so my question how to remove all the Frame so that my dialog seem Very well
the pic is http://i.stack.imgur.com/EG7oz.jpg ,so you can see there is dark frame in the last,how to remove it? thank you
Solution that worked for me
<style name="DialogTheme" parent="#android:style/Theme.Dialog">
<item name="android:windowBackground">#android:color/transparent</item>
</style>
Dialog dialog = new Dialog(this, R.style.DialogTheme);
Use following lines before calling setContentView() :-
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
will work perfectly.
Dialog mydialog = new dialog (this,android.R.style.Theme_Translucent_NoTitleBar);
instead of calling
super(context);
call
super(context, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
Update : Use this xml layout instead
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="100dip"
android:orientation="vertical"
android:background="#drawable/custom_diolog_bg"
android:layout_width="250dip">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="vertical"
android:layout_centerInParent="true">
<TextView
android:layout_height="wrap_content"
android:textColor="#000"
android:textStyle="bold"
android:textSize="18sp"
android:id="#+id/content"
android:layout_marginLeft="15dip"
android:layout_marginTop="5dip"
android:layout_alignParentTop="true"
android:layout_width="250dip"
android:text=" Custom Dialog " />
<Button
android:layout_width="70dip"
android:layout_marginLeft="80dip"
android:background="#drawable/custom_dialog_button_bg"
android:layout_alignParentBottom="true"
android:layout_height="40dip"
android:text="关闭"
android:id="#+id/close"></Button>
</LinearLayout>
</RelativeLayout>
Try this it worked for me like a charm.
ContextThemeWrapper wrapper = new ContextThemeWrapper(this, android.R.style.Theme_Holo);
final LayoutInflater inflater = (LayoutInflater) wrapper.getSystemService(LAYOUT_INFLATER_SERVICE);
AlertDialog.Builder builder = new AlertDialog.Builder(wrapper);

Black line in custom dialog on Galaxy S 2

I've built a custom dialog and there are black lines at the top and bottom. They only appear on the Galaxy S2. On some other devices it looks ok. Is there an attribute I have to set to get rid of them?
Here is my code:
public class MyDialog extends Dialog {
private Context context;
private String title, message;
private TextView titleView, messageView;
private ImageView icon;
private int iconRes;
private boolean spin;
public MyDialog(Context context, int icon, boolean spin, String title, String message) {
...
}
private void init() {
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(R.layout.my_dialog);
...
}
}
Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:minWidth="300dip" style="#style/basic" android:orientation="vertical">
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" android:background="#drawable/titlebar_bg"
android:orientation="horizontal" android:gravity="center_vertical"
android:paddingBottom="5sp">
<ImageView android:src="#drawable/info" android:id="#+id/dialogIcon"
android:layout_height="32sp" android:layout_width="32sp" />
<TextView android:id="#+id/titleText" android:text="Title"
android:textSize="20sp" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textColor="#color/darkgrey"
android:layout_marginLeft="5sp" />
</LinearLayout>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:paddingTop="5sp"
android:textColor="#000" android:id="#+id/messageText" android:text="Message" />
</LinearLayout>
After quite a long time investigating this issue, I found out, that Samsung seems to have a failing panel_background.9.png in their resources...
A workaround to get ride of this black lines is to set your own background for Dialogs like this:
<style name="CustomDialog" parent="#android:style/Theme.Dialog">
<item name="android:windowBackground">#drawable/panel_background</item>
</style>
Then Copy the panel_background.9.png from the android source or create an own one! Then make sure your Dialog is instantiate with the new Theme createt in your style.xml...
There is just one problem, now your dialog will loose the "Samsung-Dialog-Style". Which means the corner may differ from other default-dialogs in your app...

Categories

Resources