How to dismiss an android pop up window using an okay button - java

I'm making an app for a school project and I'm stuck on one area.
I want to use an okay button to dismiss the pop up window.
If you have any suggestions or if there is a better way to implement popups please share them.
package xyz.ashraf.whoisdelasalle;
import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
public class Pop extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popwindow);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int)(width*.8),(int)(height*.5));
}
}
Java code^
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="#FAFAFA">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="John Baptist de La Salle was a French priest, educational reformer, and founder of the Institute of the Brothers of the Christian Schools. He is a saint of the Roman Catholic Church and the patron saint of teachers."
android:id="#+id/textView"
android:background="#FAFAFA"
android:textColor="#000000"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:layout_marginRight="15dp"
android:layout_marginLeft="15dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK"
android:id="#+id/okButton_who"
android:textColor="#00E676"
android:background="#FAFAFA"
android:layout_below="#+id/textView"
android:layout_alignRight="#+id/textView"
android:layout_alignEnd="#+id/textView"
android:layout_marginTop="50dp"/>
</RelativeLayout>
</ScrollView>
XML^
Thanks in advance!

Not sure if this would work, but you can try:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popwindow);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int)(width*.8),(int)(height*.5));
Button okButton = (Button) findViewById(R.id.okButton_who);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
Or else you could use Dialogs or DialogFragments as akadouri suggested.

It looks like you're looking for Dialogs or DialogFragments.

I guess you could use AlertDialog to do this.
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
builder.setTitle(title); // If you want a header title
builder.setCancelable(false); // If you want to stop user dismissing with back button
builder.setMessage(message); // Message to user
//If you want custom layout (not needed)
LayoutInflater inflater = mActivity.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.pin_dialog, null);
builder.setView(dialogView)
builder.setPositiveButton(positiveLable, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Do something
}
});
builder.setNegativeButton(negativeLable, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Do something, or remove if you dont want negative button
}
});
builder.show();

Related

How to align EditText hint and input with AlertDialog message?

In my Android app I have an AlertDialog with an EditText to input the name of the user. The AlertDialog contains a title and a message, and the EditText contains a hint. All are left aligned, which is good, but they are not aligned with each other.
Here is my current code for the AlertDialog:
final EditText nameText = new EditText(this);
nameText.setHint(dialogHint);
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle(dialogTitle)
.setMessage(dialogMessage)
.setView(nameText)
.setPositiveButton(textPositiveButton, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Get name from player
String highScoreName = String.valueOf(nameText.getText());
// Do something with highScoreName
}
})
.setNegativeButton(textNegativeButton, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
}
})
.create();
dialog.show();
This is how it looks:
And this is how I want it to look:
Is there a way to achieve this? Searching for answers online only led me to questions about central aligning the AlertDialog message or aligning separate AlertDialog and EditText views. Any help is appreciated.
Well, technically, you can add margins to your EditText programmatically, for example, like described here. Note, that you can request layoutParams of your EditText only after dialog.show() method call. I highly don't recommend to follow this way and I'm not sure about its reliability.
So the best option, like was mentioned in the comments, is custom dialog with your own fully customisable layout.
Create layout file. For example, custom_dialog.xml. And create your dialog view.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Title" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Message" />
<EditText
android:id="#+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Hint" />
</LinearLayout>
Then insert it in the dialog.
View customDialogView = getLayoutInflater().inflate(R.layout.custom_dialog, null);
EditText editText = customDialogView.findViewById(R.id.edit_text);
AlertDialog alertDialog = new AlertDialog.Builder(requireContext())
.setView(customDialogView)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
editText.getText();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
}
})
.create();
alertDialog.show();
More information in the docs.

Exception When handling Custom AlertDialog with ButterKnife

Hello guys iam realy Confused i spent over 17 hours try to fix this Problem but
No hope
Am try to show Custom Dialog with > AlertDialog.Builder when i Click Button but when i run the App and click the button it gives me this Exception
i tried ButterKnife #OnClick Anotation and Casting the Item Inside the Dialog Function like Button item = findviewById(R.id.ItemID);
i search for questions has same problem like mine but useless till i found
this question Multiple injections but i found that its really very old May 29, 2014
The Exception
05-23 21:15:56.630 8769-8769/com.w4ma.soft.tamenly E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.w4ma.soft.tamenly, PID: 8769
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.w4ma.soft.tamenly.View.CreateandShow.ShowThePost.ShowCommentDialog(ShowThePost.java:133)
at com.w4ma.soft.tamenly.View.CreateandShow.ShowThePost.onClick(ShowThePost.java:159)
at com.w4ma.soft.tamenly.View.CreateandShow.ShowThePost_ViewBinding$1.doClick(ShowThePost_ViewBinding.java:52)
at butterknife.internal.DebouncingOnClickListener.onClick(DebouncingOnClickListener.java:22)
at android.view.View.performClick(View.java:5647)
at android.view.View$PerformClick.run(View.java:22462)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6221)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
Here is my code
ShowThePost.java
#Nullable #BindView(R.id.priceSuggested) EditText txtSuggestprice;
#Nullable #BindView(R.id.txtnotes) EditText txtNotes;
#Nullable #BindView(R.id.btnClose) Button btnclose;
#Nullable #BindView(R.id.btnCommentDone) Button btndone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_the_post);
ButterKnife.bind(this);
}
public void ShowCommentDialog() {
final AlertDialog.Builder alert = new AlertDialog.Builder(context);
view = getLayoutInflater().inflate(R.layout.create_comment,null);
alert.setCancelable(false);
alert.setView(view);
final AlertDialog dialog = alert.create();
// final Dialog dialog = new Dialog(context);
// dialog.setContentView(R.layout.create_comment);
// dialog.setCancelable(false);
// dialog.setTitle("This is Dialog");
// EditText txtSuggestprice = findViewById(R.id.priceSuggested);
// EditText txtNotes = findViewById(R.id.txtnotes);
// Button btnDonee = (Button)findViewById( R.id.btnCommentDone);
// Button btnClosee =(Button)findViewById(R.id.btnClose);
//
// btndone.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
//
//
// }
// });
// btnclose.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// dialog.dismiss();
//
// }
// });
final String Notes = txtNotes.getText().toString();
final String Description = txtSuggestprice.getText().toString();
alert.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toasty.success(context,"Done" + Notes + Description, Toast.LENGTH_LONG).show();
}
}).setNegativeButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
btndone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Done", Toast.LENGTH_SHORT).show();
}
});
btnclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Closed", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
#OnClick(R.id.fabComment)
public void ShowDialog(){
ShowCommentDialog();
}
CreatComment.xml this is the Custom Dialog which should Inflate to the Dialog
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardCornerRadius="#dimen/_12sdp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Comment"
android:textSize="#dimen/_22sdp"
android:textColor="#000"
android:textAlignment="center"
android:layout_margin="#dimen/_9sdp"
android:typeface="serif"/>
<View
android:layout_width="match_parent"
android:layout_height="#dimen/_1sdp"
android:background="#color/lightgray"
android:padding="#dimen/_4sdp"/>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/_4sdp">
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/priceSuggested"
android:layout_margin="#dimen/_5sdp"
android:hint="Suggest Price"
android:inputType="number"
android:typeface="serif"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/_4sdp">
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="#dimen/_5sdp"
android:hint="Notes"
android:id="#+id/txtnotes"
android:typeface="serif"/>
</android.support.design.widget.TextInputLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Done"
android:background="#drawable/btncommentstyle"
android:id="#+id/btnCommentDone"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Close"
android:layout_marginTop="#dimen/_4sdp"
android:background="#drawable/btncommentstyle"
android:id="#+id/btnClose"/>
</LinearLayout>
</android.support.v7.widget.CardView>
The exception is caused by this line:
final String Notes = txtNotes.getText().toString();
As described in the reason, the txtNotes member is null, which means that the binding did not work (probably the view with txtnotes id was not found).
From what I see, you call ButternKnife.bind() for the activity which has the activity_show_the_post layout as content view. But the view with txtnotes id is actually in the create_comment layout, of which ButterKnife knows nothing about, and doesn't even exist at that time. Thus, the binding fails, no reference to txtnotes is created and you later get a NPE.
You need to bind the views for create_comment.xml too
view = getLayoutInflater().inflate(R.layout.create_comment,null);
Butterknife.bind(view,this);
alert.setCancelable(false);
alert.setView(view);
final AlertDialog dialog = alert.create();

How to make single-choice item

I want to make an alert dialog that contains a single-choice list item which will help the user choose the theme of the app. I have read on developer's website(Developers Website) how to make the multiple-choice items but I don't quite get how to make the single-choice list item
Thanks in Advance.
//MY CODE
public class ThemeDialog extends DialogFragment {
ArrayList mSelectedItems = new ArrayList(); // Track the selected items
public static ThemeDialog newInstance(){
ThemeDialog f = new ThemeDialog();
return f;
}
//Single-choice Item code
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
dialog.setTitle("Please Select");
dialog.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Action when cancel is clicked
dialog.dismiss();
}
});
CharSequence[] cs = new CharSequence[]{"Item-1", "Item-2","Item-3"};
dialog.setSingleChoiceItems(cs, defaultSelectedPosition, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Action when any item is clicked
dialog.dismiss();
}
});
return dialog.create();
}
dialog.setSingleChoiceItems(cs, position, selectItemListener); will create the single choice dialog.
create xml layout file
<LinearLayout 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:layout_gravity="bottom"
android:background="#color/colorWhite"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#color/colorPrimary">
</View>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorWhite"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="please select a theme"
android:textColor="#color/colorRed"
android:textSize="18sp" />
<RadioGroup
android:id="#+id/cancle_booking_radio_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<RadioButton
android:id="#+id/theme1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:buttonTint="#color/colorPrimary"
android:text="theme1" />
<RadioButton
android:id="#+id/theme2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:buttonTint="#color/colorPrimary"
android:text="theme2" />
<RadioButton
android:id="#+id/theme3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:buttonTint="#color/colorPrimary"
android:text="theme3" />
<RadioButton
android:id="#+id/theme4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:buttonTint="#color/colorPrimary"
android:text="theme4" />
<RadioButton
android:id="#+id/theme5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:buttonTint="#color/colorPrimary"
android:text="theme5" />
</RadioGroup>
</LinearLayout>
now create custom dialog
final Button btnCancelbooking;
final TextView tvHideCancelDialog;
final RadioButton theme1, theme2, theme3, theme4, theme6;
final Dialog cancelDialog = new Dialog(BookingConfirmClass.this, R.style.DialogSlideAnim);
//cancelDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); /*use when not set in style file*/
cancelDialog.setContentView(R.layout.custom_cancel_booking);
getWindow().setGravity(Gravity.BOTTOM);
cancelDialog.show();
theme1 = (RadioButton) cancelDialog.findViewById(R.id.theme1);
theme2 = (RadioButton) cancelDialog.findViewById(R.id.theme2);
theme3 = (RadioButton) cancelDialog.findViewById(R.id.theme3);
theme4 = (RadioButton) cancelDialog.findViewById(R.id.theme4);
theme6 = (RadioButton) cancelDialog.findViewById(R.id.theme5);
final RadioGroup radioGroup = (RadioGroup) cancelDialog.findViewById(R.id.cancle_booking_radio_group);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
View radioButton = radioGroup.findViewById(checkedId);
int index = radioGroup.indexOfChild(radioButton);
switch (index) {
case 0:
//do your action for theme 1
break;
case 1:
//do your action for theme 2
break;
case 2:
//do your action for theme 3
break;
case 3:
//do your action for theme 4
break;
case 4:
//do your action for theme 5
break;
}
}
});
Using a final variable obviously won't work (since it can only be assigned once, at declaration time). So-called "global" variables are usually a code smell (especially when they become part of an Activity class, which is usually where AlertDialogs are created). The cleaner solution is to cast the DialogInterface object to an AlertDialog and then call getListView().getCheckedItemPosition(). Like this:
new AlertDialog.Builder(this)
.setSingleChoiceItems(items, 0, null)
.setPositiveButton(R.string.ok_button_label, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
int selectedPosition = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
// Do something useful withe the position of the selected radio button
}
})
.show();
To make it more customize look at this -How to design Single Selection Dialog?
You need to add Radio buttons inside the RadioGroup Tag in ur dialog xml file.
custom_dialog.xml
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/RGroup">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Blue Theme"
android:id="#+id/bluetheme"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Black Theme"
android:id="#+id/blacktheme"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Brown Theme"
android:id="#+id/browntheme" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Orange Theme"
android:id="#+id/orangetheme"/>
</RadioGroup>
Just attach this xml with dialog fragment...this is just simple example..u can use it in ur way also
public class DFragment extends DialogFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.custom_dialog, container,
false);
getDialog().setTitle("DialogFragment Tutorial");
// Do something else
return rootView;
}
}

Do not show again checkbox on a DialogFragment

So the title explains it all. I have a dialogfragment that currently pops up and I want to add a do not show checkbox to it and then obviously implement that check and not show if it was checked. I know there is a .setSingleChoiceItems, but I am not entirely sure on what would be going in there as it isn't really an item I would add somewhere. But then again I could probably be wrong as I am just getting into Android development.
Dialogfragment java
public class WifivsDataDialog extends DialogFragment {
#
Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_box)
.setPositiveButton(R.string.WiFi, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
}
})
.setNegativeButton(R.string.Cell_Data, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
Here is the code calling it in my MainActivity.java
WifivsDataDialog myDiag = new WifivsDataDialog();
myDiag.show(getFragmentManager(), "dialog_layout");
myDiag.setCancelable(false);
The accepted answer works, but it doesn't look like the normal material design system dialog, which is what I wanted.
Here's an option using a custom view layout to hold just the text and checkbox (with padding that matches material design), and allow the AlertDialog to manage the buttons.
no_location_dialog.xml layout file:
<?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="24dp"
android:paddingRight="12dp">
<TextView
android:id="#+id/no_location_text"
style="?android:attr/textAppearance"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="14dp"
android:paddingBottom="6dp"
android:text="#string/main_nolocation"
android:textSize="16sp"
android:autoLink="all"
android:linksClickable="true"></TextView>
<CheckBox
android:id="#+id/location_never_ask_again"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/main_never_ask_again" />
</LinearLayout>
And the code for setting up the AlertDialog:
private Dialog createNoLocationDialog() {
View view = getActivity().getLayoutInflater().inflate(R.layout.no_location_dialog, null);
CheckBox neverShowDialog = (CheckBox) view.findViewById(R.id.location_never_ask_again);
neverShowDialog.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
// Save the preference
PreferenceUtils.saveBoolean(getString(R.string.preference_key_never_show_location_dialog), isChecked);
}
});
Drawable icon = getResources().getDrawable(android.R.drawable.ic_dialog_map);
DrawableCompat.setTint(icon, getResources().getColor(R.color.theme_primary));
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
.setTitle(R.string.main_nolocation_title)
.setIcon(icon)
.setCancelable(false)
.setView(view)
.setPositiveButton(R.string.rt_yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivityForResult(
new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS),
REQUEST_NO_LOCATION);
}
}
)
.setNegativeButton(R.string.rt_no,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Ok, I suppose we can just try looking from where we
// are.
mMapFragment.mController.onLocation();
}
}
);
return builder.create();
}
It looks like this:
Here's the full code in a commit on Github - https://github.com/OneBusAway/onebusaway-android/commit/98135b66b0be5b73187e0148bef5d308c42a9fbe.
The DialogFragment class
public class WifivsDataDialog extends DialogFragment implements View.OnClickListener {
private CheckBox checkBox;
private Button button1;
private Button button2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mainView = inflater.inflate(R.layout.wifi_dialog, container);
checkBox = (CheckBox) mainView.findViewById(R.id.checkBox);
button1 = (Button) mainView.findViewById(R.id.button1);
button2 = (Button) mainView.findViewById(R.id.button2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
// Store the isChecked to Preference here
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("DONT_SHOW_DIALOG", isChecked);
editor.commit();
}
});
return mainView;
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
// Do wifi stuff here
break;
case R.id.button2:
// Do cellular stuff here
break;
}
}
}
The Layout xml wifi_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Some information to be displayed to human"
android:id="#+id/textView" android:textSize="30dp"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Do now show this dialog again."
android:id="#+id/checkBox"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:gravity="center">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="WiFi"
android:id="#+id/button1" android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CELL"
android:id="#+id/button2"/>
</LinearLayout>
</LinearLayout>
And on your Activity or where ever you display the dialog, check the preference set by user before displaying the dialog. Something like below.
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
boolean dontShowDialog = sharedPref.getBoolean("DONT_SHOW_DIALOG", false);
if (!dontShowDialog) {
new WifivsDataDialog().show(getFragmentManager(), "WiFi");
}

Buttons of alert dialog are cut off

I have an alert dialog which is started when someone touches a specific button. The alert dialog contains a view that is defined by a layout xml file. This layout contains several controls like check boxes, edit text fields, ... These controls are all inside a scrool view so that you can scroll through the content, if the whole content doesn't fit on the screen.
The problem is now that when I start this alert dialog, the buttons at the bottom are cut off screen. Altough the scrool bar is working and I can scroll through the content of the alert dialog, the buttons of the alert dialog are sometimes not totally visible.
This means:
Sometimes, all is fine and I can see the buttons of the alert dialog, an sometimes for strange reason, the buttons are cut off. I think it's an issue of the view being to big for the alert dialog and pushing the buttons more down.
For example, the view contains an edit text control. If I enter my name ther, everything is fine. But if I add a new line to this edit text, the buttons start to be cut off a little bit.
What did I wrong? I thought the scroll view would handle the oversize of my view so that the alert dialog fits to the screen.
My app is in portrait mode always.
The code of the view:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/bitteeinstellungenwaehlen" />
<EditText
android:id="#+id/edtTeam1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/hteam1"
android:text="Christoph" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/edtTeam2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/hteam2"
android:text="Lea" />
<EditText
android:id="#+id/edtTeam3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/hteam3"
android:text="Ludwig" />
<EditText
android:id="#+id/edtTeam4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/hteam4"
android:text="Anja" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/weitereeinstellungen" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<CheckBox
android:id="#+id/chkModerationMode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/moderationsmodus" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="#string/info" />
</LinearLayout>
<CheckBox
android:id="#+id/chkPassOver"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/weitergeben" />
<CheckBox
android:id="#+id/chkBlackScreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/blankscreen" />
</LinearLayout>
</ScrollView>
And that's how I start the alert dialog:
final AlertDialog.Builder alert = new AlertDialog.Builder(QuizEditor.this);
alert.setTitle(getString(R.string.speichernUndVorschau) + "...");
alert.setMessage("");
LayoutInflater inflater = LayoutInflater.from(QuizEditor.this);
final View layFrage = inflater.inflate(R.layout.layoutquizsettings,null);
alert.setView(layFrage);
final CheckBox chkModeration = (CheckBox) layFrage.findViewById(R.id.chkModerationMode);
final CheckBox chkPassOver = (CheckBox) layFrage.findViewById(R.id.chkPassOver);
final CheckBox chkBlackScreen = (CheckBox) layFrage.findViewById(R.id.chkBlackScreen);
final EditText edtTeam1 = (EditText) layFrage.findViewById(R.id.edtTeam1);
final EditText edtTeam2 = (EditText) layFrage.findViewById(R.id.edtTeam2);
final EditText edtTeam3 = (EditText) layFrage.findViewById(R.id.edtTeam3);
final EditText edtTeam4 = (EditText) layFrage.findViewById(R.id.edtTeam4);
alert.setNeutralButton(getString(R.string.speichernUndVorschau), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.setNegativeButton(getString(R.string.abbrechen), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
final AlertDialog dialog2 = alert.create();
dialog2.setOnShowListener(new OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
// TODO Auto-generated method stub
Button btnStarten = (Button) dialog2.getButton(AlertDialog.BUTTON_NEUTRAL);
btnStarten.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ArrayList<String> teams = new ArrayList<String>();
String team1 = edtTeam1.getText().toString().trim();
String team2 = edtTeam2.getText().toString().trim();
String team3 = edtTeam3.getText().toString().trim();
String team4 = edtTeam4.getText().toString().trim();
if(team1.length() > 0) teams.add(team1);
if(team2.length() > 0) teams.add(team2);
if(team3.length() > 0) teams.add(team3);
if(team4.length() > 0) teams.add(team4);
if(teams.size() == 0) {
Toast.makeText(QuizEditor.this, getString(R.string.keinteameingegeben), Toast.LENGTH_SHORT).show();
}
else
{
// Quiz starten
dialog2.dismiss();
Intent myIntent;
if(chkBlackScreen.isChecked()) {
myIntent = new Intent(QuizEditor.this, BlackScreen.class);
}
else // Direkt das Quiz starten
{
myIntent = new Intent(QuizEditor.this, Quiz.class);
}
myIntent.putStringArrayListExtra("teams", teams);
myIntent.putExtra("moderation", chkModeration.isChecked());
myIntent.putExtra("passover", chkPassOver.isChecked());
myIntent.putExtra("filename", filename);
QuizEditor.this.startActivity(myIntent);
}
}
});
}
});
dialog2.show();
// dialog2.getWindow().setLayout(LayoutParams.WRAP_CONTENT, 300);
I am sorry for the German words. In the image you can see the problem.
Unfortunately I was not allowed to upload the screenshots I made...
The question was already solved in the comments, but I will add an answer for completeness and to show that it worked for me, too.
For an AlertDialog with a custom view, don't use the .setMessage line. Removing the following line in my project caused the buttons to stop getting clipped.
.setMessage("This is my message")
Set EditText lines to 1. Also set outer LinearLayout's to fill_parent.
Just make all the EditText property android:singleLine="true" and then try to test.

Categories

Resources