Native UI Confirm Dialog LibGDX - java

I'm looking for a way to get a yes/no dialog box to display for android.
I'm looking for something that functions similar to this:
Gdx.input.getTextInput(new TextInputListener() {
#Override
public void input (String text) {
}
#Override
public void canceled () {
}
}, "Question", "");
Except, instead of getting text input, I want it to simply prompt the user for a yes or no.
I've looked into this, but I haven't been able to get it to work, as it's probably pretty out-dated. If anyone could think of a solution to this, that'd be wonderful. Thanks so much!

Try to change your Activity to look like this. Everything else (e.g. RequestHandler) should be correct.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initialize(new ConfirmTest(this), false);
}
#Override
public void confirm(final ConfirmInterface confirmInterface) {
runOnUiThread(new Runnable(){
#Override
public void run() {
new AlertDialog.Builder(ConfirmTestAndroidActivity.this)
.setTitle("Confirm")
.setMessage("Are you sure?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
confirmInterface.yes();
dialog.cancel();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.create().show();
}
});
}
To use custom configuration you can use this:
Game myGame = new Game(); // your game class which implements ApplicationListener
AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
cfg.useGL20 = true;
cfg.useCompass = false;
cfg.useAccelerometer = false;
cfg.useWakelock = true;
cfg.touchSleepTime = 16;
initialize(myGame, cfg);
Remember that using WakeLock feature requires permission in AndroidManifest.xml to be declared or SecurityException will be thrown.
<uses-permission android:name="android.permission.WAKE_LOCK" />

You could use gdx-dialogs library. Instructions to use it here: https://github.com/TomGrill/gdx-dialogs
You can build these kinds of native dialogs:
GDXProgressDialog: For loading dialog
GDXTextPrompt: For text input
GDXButtonDialog: For multi-options pop-up
And it works on iOS, Android and Desktop

Related

Delete touch around a dialog in Java Android Studio

I'm looking at how to remove the effect of the touch around a dialog
I created a dialog when there is no connection detected
Code
#Override
public void onErrorResponse(String _param1, String _param2) {
final String _tag = _param1;
final String _message = _param2;
nc.setTitle("No connection");
nc.setIcon(R.drawable.ic_launcher);
nc.setMessage("Turn on your connection and then relaunch the app");
nc.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface _dialog, int _which) {
i.setClass(getApplicationContext(), SplashActivity.class);
startActivity(i);
}
});
nc.setNegativeButton("Close App", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface _dialog, int _which) {
finish();
}
});
nc.create().show();
}
};
}
When the dialog appears it must make the 350x100
When I click on the screen around the dialog it removes
I would like to know if it is possible to remove the touch around the dialog when it is displayed ?
Try this: dialog.setCanceledOnTouchOutside(false);. It will still allow you to cancel the dialog with back button, but it will prevent the dialog from closing when touching around it.
EDIT
In your code you should change the nc.create().show(); at the end to:
AlertDialog alertDialog = nc.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
You probably need to add setCancelable(false) during creating
https://developer.android.com/reference/android/app/AlertDialog

Multiple DialogFragments with different functionalities

So i'm developing Android app where user is often asked what he wants to do on some actions (Button click etc.). For that i was using AlertDialog and wrote text on it and added Buttons i needed. It was working super until i realized, that on device rotation, an opened AlertDialog would disappear.
I found on the web that the proper way to handle rotation is to use Fragment, so i choose to make class extending DialogFragment:
public class MyDialogFragment extends DialogFragment {
public interface YesNoListener {
void onYes();
void onNo();
void onNeu();
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String[] data = getArguments().getStringArray("data"); //vzame vrednosti, ki smo jih nastavili preden se pokliče .show();
if(data != null) {
switch (data.length) {
case 3:
return new AlertDialog.Builder(getActivity())
.setTitle(data[0])
.setMessage(data[1])
.setNeutralButton(data[2], new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((YesNoListener) getActivity()).onNeu();
}
})
.create();
case 4:
return new AlertDialog.Builder(getActivity())
.setTitle(data[0])
.setMessage(data[1])
.setPositiveButton(data[2], new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((YesNoListener) getActivity()).onYes();
}
})
.setNegativeButton(data[3], new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((YesNoListener) getActivity()).onNo();
}
})
.create();
case 5:
return new AlertDialog.Builder(getActivity())
.setTitle(data[0])
.setMessage(data[1])
.setPositiveButton(data[2], new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((YesNoListener) getActivity()).onYes();
}
})
.setNegativeButton(data[3], new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((YesNoListener) getActivity()).onNo();
}
})
.setNeutralButton(data[4], new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((YesNoListener) getActivity()).onNeu();
}
})
.create();
default:
return null;
}
}
else
return null;
}
}
I used interface too so i could implement Button.onClick() behaviour in the class where i would use MyDialogFragment. With getArguments() i passed all texts that would be used in Dialog.
The problem is that i can only use this class for one Dialog, since i have to Override interface functions, but i have multiple Dialogs with different behaviour.
I wanted to solve this issue with three public Objects Runnable, where i would just initialize Runnable where i need to change the behaviour of the Button.onClick()
...
Runnable runnablePositive, runnableNegative, runnableNeutral;
...
#Override
public void onYes(){
threadPositive.start();
}
#Override
public void onNo(){
threadNegative.start();
}
#Override
public void onNeu(){
threadNeutral.start();
}
static MyDialogFragment newInstance(String[] arg) {
MyDialogFragment f = new MyDialogFragment();
Bundle args = new Bundle();
args.putStringArray("data", arg);
f.setArguments(args);
return f;
}
...and on usage:
threadPositive = new Thread()
{
public void run()
{
//do A
}
};
threadNegative = new Thread()
{
public void run()
{
//do B
}
};
threadNeutral = new Thread()
{
public void run()
{
//do C
}
};
newInstance(new String[]{title, besedilo, nevtralno}).show(getFragmentManager(), "tag");
It is working good untill i open Dialog and rotate (this is the main problem, other things somehow work) the device (reason why i use DialogFragment in the first place). All the variables are "deleted" on the rotation and i already passed all variables i needed for further work, but there comes new issue, which i have no idea how to solve: i can't pass Objects on rotation, whether i try with onRetainCustomNonConfigurationInstance() or onSaveInstanceState() all in vain...
So i have no idea how to solve this, i had gone through hundreds of question regarding similar issue, but had no luck... And i would be grateful for any helpful advice or answer regarding this problem (even if it is a different way to solve the problem).
Thanks in advance!
If you have multiple dialogs with different behavior, then you should simply create more instances of your dialog and assign them different tags. Instead of doing just
newDialogFragment(someArgs).show(getFragmentManager(), "tag")
you can do
newDialogFragment(someArgs).show(getFragmentManager(), "dialogWithArgs")
newDialogFragment(someOtherArgs).show(getFragmentManager(), "dialogWithOtherArgs")
and so on. Your interface should be changed to
public interface YesNoListener {
void onYes(String tag);
void onNo(String tag);
void onNeu(String tag);
}
When you call its methods from the dialog, pass the fragment tag so you know which dialog called the method. That way you can handle any number of dialogs easily.
As to saving the objects, those that don't change, go into the arguments, those that do, should be made Parcelable and saved to Bundle, if you can't, then you can create a separate fragment and call setRetainInstance(true) on it, then store the objects in it.

Android Safe vs Unsafe Usage of Inner Classes

I'm new to Android development and I've been having a lot of trouble finding ways to make sure my app doesn't leak memory. I've read online that using inner classes can cause memory leaks, especially when they may outlive their Activity. Here are some of the inner classes I use. Which of these, if any, could cause a memory leak?
public class TitleScreenActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_title_screen);
final MyHandler mHandler = new MyHandler(this);
final Intent intent = new Intent(mHandler.mActivity.get(), IntroActivity.class);
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
startActivity(intent);
mHandler.mActivity.get().finish();
}
}, 2000);
}
private static class MyHandler extends Handler {
public final WeakReference<TitleScreenActivity> mActivity;
public MyHandler(TitleScreenActivity activity) {
mActivity = new WeakReference<>(activity);
}
}
}
I based this code off of what I found in this article. However, I don't think it would be possible for me to make my Runnable static, like they did in the article. Can this code cause a memory leak, even though I finish the Activity in the runnable?
Another example:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.no_tiles);
builder.setPositiveButton(R.string.store, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// start new Activity
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Do nothing, just close dialog
}
});
AlertDialog dialog = builder.create();
dialog.show();
I have trouble believing that this could cause a leak because it doesn't contain an explicit reference to an Activity, View, etc and it (to the best of my knowledge) the dialog gets destroyed when the user clicks a button, so the listeners would be destroyed as well. However, I wanted to make sure.
Last example:
TranslateAnimation translate;
translate = new TranslateAnimation(0, 0, 0, 100);
translate.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
// modify a few variables
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
translate.setDuration(200);
findViewById(R.id.game_board).startAnimation(translate);
I'm not sure if this could cause because theoretically the animation could outlive the Activity it's in.
All help is appreciated, thanks!

edit text in alert dialog

i've this dialog
case DIALOGO_EDIT:
final EditText editText = new EditText(context);
builder.setView(editText);
builder.setPositiveButton("Send", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int i) {
}
});
builder.setNegativeButton("Close", null);
break;
But when i rotate the device the dialog dismiss... How can i solve this problem and mantein the dialog during rotation? Or display the edit text at "full screen" like WhatsApp
When the screen is rotated, the activity actually is restarted and killed, so you need to save and be able to restore the data using the lifecycle methods. Have a look here: Saving Persistent State
You may want to have a look to this question here
The best way of avoid this problem is to use DialogFragment.
Create a new class extended to DialogFragment. Override onCreateDialog and return your old Dialog or an AlertDialog.
Them you can show it with DialogFragment.show(fragmentManager, tag).
Here an example with the activity like listener:
public class MyDialogFragment extends DialogFragment {
public interface YesNoListener {
void onYes();
void onNo();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof YesNoListener)) {
throw new ClassCastException(activity.toString() + " must implement YesNoListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.dialog_my_title)
.setMessage(R.string.dialog_my_message)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((YesNoListener) getActivity()).onYes();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((YesNoListener) getActivity()).onNo();
}
})
.create();
}
}
And in the Activity you call:
new MyDialogFragment().show(getSupportFragmentManager(), "tag"); // or getFragmentManager() in API 11+
This kind of questions already asked,and there are also solution for it, these three questions are matched with your problem (and they answered):
Android Best way of avoid Dialogs to dismiss after a device rotation
Android DialogFragment vs Dialog
How can I show a DialogFragment using compatibility package?

Preventing Android dialog from extending activities

How can I prevent my dialogs from extending activities?
When I create it in my main activity it doesn't dismiss itself when I click "Okay", which creates a new activity. The new activity that is created extends from the MainActivity.
I am using shared preferences to determine where to send the user when they open the app. I'm not sure if that could be playing into this situation.
I want to prevent the dialogs from extending the MainActivity. It shouldn't be showing up on the other activities that I create.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences sharedPreferences = getSharedPreferences("version", 0);
int savedVersionCode = sharedPreferences.getInt("VersionCode", 0);
int appVershionCode = 0;
try { appVershionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; }
catch (NameNotFoundException nnfe) { Log.w(TAG, "$ Exception because of appVershionCode : " + nnfe); }
if(savedVersionCode == appVershionCode){
// Returning user
Log.d(TAG, "$$ savedVersionCode == appVershionCode");
// Temporary Navigation
final Builder alertDialogBuilder = new Builder(this);
new AlertDialog.Builder(new ContextThemeWrapper(getBaseContext(), android.R.style.Theme_Dialog));
alertDialogBuilder.setTitle("Temporary Navigation");
alertDialogBuilder.setMessage("Go to the new activity.");
alertDialogBuilder.setPositiveButton("Okay", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "$$ onClick");
Intent newactivity = new Intent(MAINACTIVITY.this,NEWACTIVITY.class);
startActivity(newactivity);
dialog.cancel();
}
});
alertDialogBuilder.show();
// End
} else {
// First time visitor
Log.d(TAG, "$$ savedVersionCode != appVershionCode");
// Hide graphics meant for returning users
((Button)findViewById(R.id.Button01)).setVisibility(View.INVISIBLE);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
sharedPreferencesEditor.putInt("VersionCode", appVershionCode);
sharedPreferencesEditor.commit();
Builder alertDialogBuilder = new Builder(this);
alertDialogBuilder.setTitle("Welcome");
alertDialogBuilder.setMessage("Click Okay to continue.");
alertDialogBuilder.setNeutralButton("Okay", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "$$ onClick");
Intent leagues = new Intent(MAINACTIVITY.this,NEWACTIVITY.class);
startActivity(leagues);
}
});
alertDialogBuilder.show();
}
}
Try dialog.dismiss() like such:
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "$$ onClick");
Intent newactivity = new Intent(MAINACTIVITY.this,NEWACTIVITY.class);
startActivity(newactivity);
dialog.dismiss();
}
From a little understanding of your code, my suggestion would be keeping a check of when you want dialog to be shown and when you dont. e.g You can use a static boolean flag showDialog, set it true/false in your activity according to the use.
if(savedVersionCode == appVershionCode && showDialog)
if(savedVersionCode == appVershionCode && !showDialog)
Its more over over a programmatic problem with a programmatic solution. This is approach would be just a suggestion. As you are following a singleTon type of structure so you must be sure of methods you want to carry further.
Second approach could be, do not do it this way. The common method you want to implement in your activity is related to SharedPref checking, so why not :
Create a class which extends Activity.
Add your SharedPref related methods in it.
Now you can extend that class to all you activities.
public class commonMethod extends Activity{
public void my_sharedPrefMethod(){
// do some thing with prefs
}
#OverRide
public void onCreate(){
super.onCreate();
// common onCreate code for every activity. Recommend not to change this
// so that you can implement
}
// you can also write other methods onPause(), onDestroy() here too.
{
Now you can extend your classes with this class commonMethod. e.g
public class main extends commonMethod{
#overRide
public void oncreate(){
}
#overRide
public void my_sharedPrefMethod(){
}
public void showMyDialog(){
// this way dialog box would not be shown on every activity but just this one.
}
}

Categories