Trying to change custom dialog Background color - java

Ok so I am trying change my background of my dialog box from white to a dark blue. However when I long press on one of the grid elements the dialog box looks like this:
I am trying to make it look something like this (this is a photoshop):
Here is snipet of my XML code for the edit dialog
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:background="#color/customBG">
Java code for custom dialog
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.edit_game_dialog,null);
editTitle = view.findViewById(R.id.editTitle);
editTitle.setText(currentTitle);
imageView = view.findViewById(R.id.item_image_dialog);
imageView.setImageResource(currentImage);
changeImageBt = view.findViewById(R.id.change_image);
changeImageBt.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
}
});
builder.setView(view).setTitle("Edit game")
.setPositiveButton("Apply Changes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialogInterface, int i)
{
String title = editTitle.getText().toString();
int image = R.drawable.blank; //PLACE HOLDER CODE
editGameDialogListener.applyChanges(pos,title,image);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialogInterface, int i)
{
}
});
return builder.create();
}

I think you should use Dialog instead of AlertDialog.
Alert Dialog has its own Title and Button.
With Dialog you will have the benefit of defining your Title and Buttons.
Create a Layout as your design needs and set it in Dialog.
class ABC(context: Context) : Dialog(context) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.your_custom_layout)
}
}

When you create your dialog, you can pass theme as a second param
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.MyDialogTheme);
and set the custom theme to override anything you need. For background color something like this should work:
<style name="MyDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:background">#color/customBG</item>
</style>

Related

Custom AlertDialog disappears on back button press

Hi guys I have a custom alert dialog I created. In the builder I set cancelable to false yet it still disappears when I press the back button, any ideas?
This is the code for the dialog:
public final class HemisphereDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View customTitle = inflater.inflate(R.layout.hemisphere_dialog_custom_title, null);
builder.setCustomTitle(customTitle);
String[] entries = new String[2];
entries[0] = getResources().getString(R.string.northern_hemisphere);
entries[1] = getResources().getString(R.string.southern_hemisphere);
builder.setItems(entries, new DialogInterface.OnClickListener() {
//The 'which' argument contains the index position of the selected item
public void onClick(DialogInterface dialog, int which) {
if( which == 0 ) {
GlobalVariables.getShared().setIsInNorthernHemisphere(true);
} else if( which == 1 ) {
GlobalVariables.getShared().setIsInNorthernHemisphere(false);
}
ToolbarActivity.outfitsFragment.hemisphereSelected();
GlobalVariables.getShared().setHasAskedForHemisphere(true);
}
});
builder.setCancelable(false);
//Create the AlertDialog object and return it
return builder.create();
}
And this is how it's displayed:
new HemisphereDialogFragment().show(getSupportFragmentManager(), "hemisphereDialog");
Another small side question, is there a way to change the text size for the items in the dialog?
You set your alert dialog cancelable to false, but your fragment is still set to cancelable, you need to add setCancelable(false) to your fragment as well.
You should call setCancellable(false) in the Dialog fragment itself not the AlertDialog.Builder.

Alertdialog with checkbox ( Don't show again )

I need to show an AlertDialog with "Don't Show Again" checkbox. I searched, but I couldn't find a working solution :/
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
PackageManager pk = getPackageManager();
Drawable icon;
alertDialogBuilder
.setTitle(R.string.confirm)
.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//Do something
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
If i'm not wrong then just Make one class extends with View.
public class DialogShow extends View {
SharedPreferences dialogPreferences;
String prefrencestring;
CheckBox nevershowagain;
Button closedialog;
Dialog dialog;
View view;
public DialogShow(final Context context) {
super(context);
dialog = new Dialog(context);
view = View.inflate(context, R.layout.startdialog, null);
dialog.setContentView(view);
nevershowagain = (CheckBox) view.findViewById(R.id.nevershowagain);
closedialog = (Button) view.findViewById(R.id.closedialog);
closedialog.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (nevershowagain.isChecked()) {
prefrencestring = "1";
dialogPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
Editor editprefrences = dialogPreferences.edit();
editprefrences.putString("showdialog", prefrencestring);
editprefrences.commit();
}
dialog.dismiss();
}
});
dialogPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
String check = dialogPreferences.getString("showdialog", "");
if (check.equals("1")) {
} else {
dialog.show();
}
}
}
Now call this class in your splash Activity on onCreate() method..
DialogShow d = new Dialog(this);
You can try this for AlertDialog :
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.myDialogLayout, null));
Dialog d = builder.create();
Edit: Please look into HERE FOR DETAILS EXPLANATION
Pass your view to the setView() method and it will set your view to the dialog body.
alertDialogBuilder.setView(your_view);
Since the accepted answer is not a good one in 2023 (IMO) and this post is the first one on google search, here is my solution:
private void showAlertWithCheck() {
boolean infoShowed = PreferenceManager.getDefaultSharedPreferences(this).
getBoolean(Const.PREF_KEY_INFO_SHOWN, false);
if (!infoShowed) {
View view = getLayoutInflater().inflate(R.layout.dialog_remember_check, null);
final CheckBox chk_drc_Remember = view.findViewById(R.id.chk_drc_Remember);
chk_drc_Remember.setText(R.string.dont_show_again);
chk_drc_Remember.setChecked(true);
new AlertDialog.Builder(MainActivity.this).
setIcon(android.R.drawable.ic_dialog_info).
setMessage(R.string.fixed_info).
setView(view).
setNeutralButton(R.string.caption_ok, null).
setOnDismissListener(dialog ->
PreferenceManager.getDefaultSharedPreferences(this).edit().
putBoolean(Const.PREF_KEY_INFO_SHOWN,
chk_drc_Remember.isChecked()).apply()).
show();
}
}
requied view XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:animateLayoutChanges="true"
android:orientation="vertical"
android:padding="#dimen/dialog_padding"
tools:context=".dialogs.PrayTimeDetailDialog"
tools:ignore="RtlHardcoded">
<CheckBox
android:id="#+id/chk_drc_Remember"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:paddingLeft="#dimen/dialog_padding"
android:paddingRight="#dimen/dialog_padding"
android:text="#string/remember_method" />

Custom style on DialogFragment

Possible duplicate here, sorry in that case...
I can't get my head around how to add a custom style to my DialogFragment. At the moment I have a class
public final class SelectFragment extends DialogFragment {
which I call from different parts of my app. E.g from my "CreateInvoice" class like this:
private void showFragment(int selectedIndex) {
SelectFragment fragment = SelectFragment.newInstance(selectedIndex, getOnOptionSelectListener());
fragment.setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Holo_Light_Dialog);
fragment.show(getActivity().getSupportFragmentManager(), "");
}
What I want to do is to change the fragment.setStyle to a custom one, for example with my own color scheme as color on the border, background etc.. And I would really appreciate if someone could walk me through it since it's the first time I've worked with fragments. :-)
Thanks!
The way I would do it is to simply write your own layout for your dialog, then load it up when you show the fragment
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
View v = inflater.inflate(R.layout.custom_dialog_layout, null, false);
builder.setView(v)
// Add action buttons
.setPositiveButton(R.string.save_note, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// do stuff
}
})
.setNegativeButton(R.string.note_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do stuff
}
});

Android custom AlertDialog height not honoring layout parameters

So I am creating a custom AlertDialog using the Builder. I have a custom view I am inflating in the dialog with the following layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<EditText android:id="#+id/edit_username"
style="#style/EditPassword"
android:hint="#string/login_username_hint" />
<EditText android:id="#+id/edit_password"
style="#style/EditPassword"
android:hint="#string/login_password_hint" />
</LinearLayout>
The android:layout_height style for the EditText controls is set to "wrap_content". When I show the dialog with this custom view the dialog is stretched to fill the height of the entire screen. No matter what I set the layout_height on the LinearLayout to (including hardcoded pixel values), it still fills the entire screen on my emulator.
I'm hoping there's something simple that I'm missing here?
EDIT: I looked in the Hierarchy Viewer and the layout I included in this question is correctly defined, but it is wrapped within a FrameLayout within a FrameLayout, and the outermost FrameLayout is set to "wrap_content" but is rendering in the Viewer with a bunch of empty space below it.
EDIT 2: As requested, the code that inflates the layout.
protected Dialog onCreateDialog(int id) {
switch(id) {
case AUTHENTICATION_DIALOG:
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
final View loginView = inflater.inflate(R.layout.login_dialog, null);
return new AlertDialog.Builder(HomeActivity.this)
.setTitle("Upload profile data")
.setView(loginView)
.setPositiveButton("Upload", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText userName = (EditText)loginView.findViewById(R.id.edit_username);
EditText password = (EditText)loginView.findViewById(R.id.edit_password);
String userNameStr = StringUtils.convertToTrimmedString(userName.getText());
String passwordStr = StringUtils.convertToTrimmedString(password.getText());
if (userNameStr.equals("") || passwordStr.equals("")) {
new AlertDialog.Builder(HomeActivity.this)
.setTitle("Required fields missing")
.setMessage("You must enter a username and password")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
HomeActivity.this.showDialog(AUTHENTICATION_DIALOG);
dialog.dismiss();
}
}).show();
} else {
dialog.dismiss();
} // end if user entered username and password
} // end "Upload" onClick
}) // end setPositiveButton DialogInterface.OnClickListener()
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
} // end "Cancel" onClick
}).create();
default:
return null;
}
}
So I switched to using a RelativeLayout like so:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<EditText android:id="#+id/edit_username"
style="#style/EditPassword"
android:hint="#string/login_username_hint" />
<EditText android:id="#+id/edit_password"
style="#style/EditPassword"
android:layout_below="#+id/edit_username"
android:hint="#string/login_password_hint" />
</RelativeLayout>
and it works fine. I switched back to Linear to test and it exhibited the old broken behavior when I switched back to the LinearLayout. I'm going to leave this answer unmarked in the hopes that someone can tell me why it's freaking out over LinearLayout vs Relative.

Parse XML and display it in an AlertDialog in Android

I have this .xml file with countries and their countrycodes in them. This is how it looks like:
<?xml version="1.0" encoding="UTF-8"?>
<landen>
<land>
<naam>Afghanistan</naam>
<code>AF</code>
</land>
<land>
<naam>Albani�</naam>
<code>AL</code>
</land>
<land>
<naam>Algerije</naam>
<code>DZ</code>
</land>
<land>
</landen>
Now I want people to choose one country out of an list. I though an AlertDialog would be nice to display everything.
The way i get the values out of my xml-file is like this:
protected ArrayList<Land> getLanden() {
ArrayList<Land> lijst = new ArrayList<Land>();
try {
DocumentBuilder builder =DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(getAssets().open("landenlijst.xml"));
NodeList nl = doc.getElementsByTagName("land");
for (int i=0;i<nl.getLength();i++) {
Node node = nl.item(i);
Land land = new Land();
land.land = Xml.innerHtml(Xml.getChildByTagName(node, "naam"));
land.landcode = Xml.innerHtml(Xml.getChildByTagName(node, "code"));
lijst.add(land);
}
Log.d("Gabug","Klaar met parsen");
Log.d("Gabug","Landen: " + lijst);
} catch (Exception e) {
e.printStackTrace();
}
return lijst;
}
And I use this to make my AlertDialog:
public void KiesLandMenu(){
ArrayList<Land> alleLanden = getLanden();
final CharSequence[] items = alleLanden.toArray(new CharSequence[alleLanden.size()]);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Kies land");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item){
case 0:
break;
case 1:
break;
case 2:
break;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
I don't know if this works as DDMS returns some bytecode or something when i Log it. And after that it Force Closes because of ArrayStoreException..
Now my question is; is this the best way to do this? if yes, how can I fix the ArrayStoreException? If no, what are better ways to let my user choose a country (a whole new view maybe)?
Furthermore, how can I register what country someone tapped?
EDIT:
I slightly changed the sample code below and I get an NullPointerException now..
public void KiesLandMenu(){
ArrayAdapter<Land> arrAdapter;
ArrayList<Land> alleLanden = getLanden();
arrAdapter = new ArrayAdapter<Land>(this, android.R.layout.simple_list_item_single_choice, alleLanden);
ListView list = (ListView)findViewById(R.layout.lijstview);
list.setAdapter(arrAdapter);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> list, View view, int position,
long id) {
Log.e("item clicked", String.valueOf(position));
}
});
}
The NullPointerException is at list.setAdapter(arrAdapter);
Make a layout with a ListView, then set that layout in your onCreate. To make the list, you can do something like:
public class RunTestProject extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); //whatever you want your layout to be
}
// getLanden() implementation goes here
public void KiesLandMenu(){
ArrayList<Land> alleLanden = getLanden();
arrAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, alleLanden);
Dialog dialog = new Dialog(this);
dialog.setTitle("Kies land");
dialog.setContentView(R.layout.withList); // The dialog layout
ListView list = (ListView) dialog.findViewById(android.R.id.list); //note that it's not simply findViewById
list.setAdapter(arrAdapter);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> list, View view, int position,
long id) {
Log.e("item clicked", String.valueOf(position));
}
});
dialog.show();
}
}
When the user chooses on an item, you can see in the log that the item's position in the array is shown.
Your layout file can be something like:
<?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="fill_parent"
>
<ListView android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
/>
</LinearLayout>
You could probably extend AlertDialog and give it a ListView as a view. Then bind the ListView to an ListAdapter which uses your ArrayList.
Edit:
ListView lv = new ListView(context);
ArrayAdapter aa = new ListAdapter(context, viewid, lijst);
lv.setAdapter(aa);
AlertDialog ad = new AlertDialog(context);
ad.setView(lv);
There is a bit more work than that though. You need to specify viewid which is the View representing each item in the ListView.
The sdk reference is very good you know.
new AlertDialog.Builder(this)
.setIcon(R.drawable.alert_dialog_icon)
.setTitle(R.string.alert_dialog_single_choice)
.setSingleChoiceItems(<ListAdapter> or CharaSequnce[] , 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked on a radio button do some stuff */
}
})
.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked Yes so do some stuff */
}
})
.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked No so do some stuff */
}
})
.create();
Note :
Please see This link to Api for Bold text mentioned below
.setSingleChoiceItems(CharacterSequnce[] , 0, new DialogInterface.OnClickListener()....
Hope this helps . Thanks :)

Categories

Resources