How to use one loading window instance in all activities - android

First of all, thank you.
I want to make one loading window for all activity.
Loading window's layout is match_parent/match_parent ConstraintLayout, have one lottieAnimationView(or ProgressBar).
In other words, I want Transparent FullScreen Loading window.
Per Activitiy, add ProgressBar..attach.. I don't think it's a good solution.
So, I tried to use the AlertDialog as a singleton, but when I ran the AsyncTask, I had a problem closing the dialog when the activity's context changed.
How can I use a custom loading window singleton in all my activities?
class AlertUtils {
companion object {
private var loadingDialog:AlertDialog?=null
#JvmStatic
fun showLoadingDialog(activity : Activity, theme: LoadingColorTheme=LoadingColorTheme.COLOR_WHITE_DEFAULT) {
if (activity.isFinishing)
return
loadingDialog = AlertDialog.Builder(activity, android.R.style.Theme_Translucent_NoTitleBar).create()
loadingDialog?.let {
it.setCancelable(false)
it.show()
it.setContentView(R.layout.progress_dialog_loading_lottie)
setThemeLoadingDialog(activity, it, theme)
}
}
#JvmStatic
fun hideLoadingDialog() {
loadingDialog?.let {_loadingDialog ->
if (_loadingDialog.isShowing) {
_loadingDialog.dismiss()
}
}
}
private fun setThemeLoadingDialog(activity: Activity, loadingDialog: AlertDialog, theme: LoadingColorTheme) {
val parentLayout = loadingDialog.findViewById<ConstraintLayout>(R.id.progress_dialog_loading_lottie_layout)
val lottieView = loadingDialog.findViewById<LottieAnimationView>(R.id.progress_dialog_lottie_view)
if (theme === LoadingColorTheme.COLOR_BLACK) {
parentLayout?.setBackgroundColor(ContextCompat.getColor(activity, R.color.colorBlackAlpha70))
lottieView?.setAnimation(R.raw.loading_indicator_white)
} else {
parentLayout?.setBackgroundColor(ContextCompat.getColor(activity, R.color.colorWhiteAlpha80))
lottieView?.setAnimation(R.raw.loading_indicator_color)
}
}
}
}

I've created a class which have below method and
public static void showDialog4Activity(final Context context, String title, String message) {
LayoutInflater inflater = LayoutInflater.from(context);
#SuppressLint("InflateParams") final View dialogView = inflater.inflate(R.layout.aommoncls_dialogbox, null);
TextView titileTextView = (TextView) dialogView.findViewById(R.id.tv_titile);
TextView msgTextView = (TextView) dialogView.findViewById(R.id.tv_msg);
Button dialogButtonOKButton = (Button) dialogView.findViewById(R.id.dialogButtonOK);
titileTextView.setTypeface(Validations.setTypeface(context));
msgTextView.setTypeface(Validations.setTypeface(context));
dialogButtonOKButton.setTypeface(Validations.setTypeface(context));
msgTextView.setText(message + "");
titileTextView.setText(title + "");
// final AlertDialog.Builder builder = new AlertDialog.Builder(context);
//
// final AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(context, R.style.myDialog));
final Dialog builder = new Dialog(context, R.style.myDialog);
// final AlertDialog b = builder.create();
builder.create();
// builder.setTitle("Material Style Dialog");
builder.setCancelable(true);
// builder.setView(dialogView);
builder.setContentView(dialogView);
builder.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
builder.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
builder.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
builder.show();
// final AlertDialog show = builder.show();
dialogButtonOKButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// show.dismiss();
builder.dismiss();
}
});
}
And have called like below
CLASSNAME.showDialog4Activity(LoginActivity.this, "","");
Here CLASSNAME is the class in which we have defined showDialog4Activity method.

Related

Custom view button click on AlertDialog

I have a RecyclerView Adapter class in which every view holder has an onclick listener. When the user clicks on the view holder, I want a dialog box to be shown with a custom view.
My dialog_custom.xml is like this:-
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
… >
<com.google.android.material.textfield.TextInputLayout
… >
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/txt_name"
… />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="#+id/btn_ok"
… />
</androidx.constraintlayout.widget.ConstraintLayout>
When the user clicks the Button(btn_ok), I want to return the name entered in txt_name to the ViewHolder class and display it in a TextView. How many I supposed to do this?
My MyAdapter.kt:-
class MyAdapter : RecyclerView.Adapter<MyAdapter.ViewHolder>() {
…
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
if (list.isEmpty()) holder.addMessage()
else holder.bind(list[position])
}
inner class ViewHolder(itemView: View, private val context: Context) : RecyclerView.ViewHolder(itemView) {
init {
itemView.setOnClickListener {
AlertDialog.Builder(context)
.setView(R.layout.dialog_custom)
.setCancelable(true)
.create().show()
}
}
…
}
}
To do this you could use Kotlins MutableLiveData. Use a wrapper class the show your AlertDialog and post the value of the text field.
class MyInputDialog(private val context){
public var input = MutableLiveData("")
public fun showDialog(){
val dialog = AlertDialog.Builder(context).run{
setView(R.layout.dialog_custom)
show()
}
dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Confirm") { _, _ -> Unit
input.postValue(dialog.your_text_input.text.toString())
}
}
}
Then in your Viewholder you call:
InputDialog(context).apply{
showDialog()
input.observe(context, Observer {
if(it != ""){
//Do whatever you want with it
}
}
}
Note that this code isn't tested, but it should work something like this.
Here is the way I do what you need to do:
public class NumberDialog extends AppCompatDialogFragment {
private final static String DIALOG_TITLE_PARAM = "DIALOG_TITLE_PARAM";
private final static String DIALOG_PARAM_PARAM = "DIALOG_PARAM_PARAM";
private OnNumberDialogClickListener mCallback = null;
private EditText mEdit = null;
private int mParam = 0;
public interface OnNumberDialogClickListener {
void onNumberDialogPositiveClick(int req, int val);
}
public static NumberDialog newInstance(String title, int req) {
NumberDialog dialog = new NumberDialog();
Bundle params = new Bundle();
params.putString(DIALOG_TITLE_PARAM, title);
params.putInt(DIALOG_PARAM_PARAM, req);
dialog.setArguments(params);
return dialog;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
Fragment frag = getTargetFragment();
if (frag != null) {
mCallback = (OnNumberDialogClickListener)frag;
} else {
mCallback = (OnNumberDialogClickListener)context;
}
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() +
" must implement OnNumberDialogClickListener");
}
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String title = getArguments().getString(DIALOG_TITLE_PARAM);
mParam = getArguments().getInt(DIALOG_PARAM_PARAM);
View layout = LayoutInflater.from(getContext()).inflate(R.layout.dialog_select_number, null, false);
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(title).
setView(layout).
setPositiveButton(R.string.ok, null).
setNegativeButton(R.string.cancel, null);
mEdit = layout.findViewById(R.id.dialog_number_edit);
final AlertDialog alert_dialog = builder.create();
alert_dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
alert_dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mEdit != null) {
String valStr = mEdit.getText().toString();
int val;
try {
val = Integer.parseInt(valStr);
} catch (Exception e) {
return;
}
mCallback.onNumberDialogPositiveClick(mParam, val);
dismiss();
}
}
});
}
});
alert_dialog.setCanceledOnTouchOutside(true);
return alert_dialog;
}
}
This is a sample class for a number dialog which validates input to be a number and closes the alert dialog only if it is a number. If number is valid, it calls back to main class using onNumberDialogPositiveClick().
This code shows you how to:
Use a callback from your alert dialog to run a code on your class class.
How to validate your data in your alert dialog before closing it.
Use custom layout for your alert dialog.
Just create a instance of NumberDialog and implement onNumberDialogPositiveClick() to see how it works. This gives you the general idea of how your code should change.

Is there a way to access Dialog objects from MainActivity?

I want to access the object of Dialog in MainActivity.
For example, in the MainActivity, use the Button to pop up a dialog.
case R.id.txtCalibMain:
SubMenu_Calib mCalibDialog = new SubMenu_Calib(instance);
mCalibDialog.show();
break;
In this way, but in the previous steps, before the Dialog
If you want to preserve the text content of the TextView inside the Dialog
How can you approach it?
Currently, Dialog is defined and called by using a separate class.
I'm trying to access it from the outside, so I'm importing a null value or an undefined TextView.
It is natural that an error will be raised.
Dialog Activity Code
public class SubMenu_Units extends Dialog implements View.OnClickListener {
public static SubMenu_Units mSubMenu_Units;
public static MainActivity instance;
public static List<SingleItem> singleItems;
static SingleAdapter mSingleAdapter;
public static TextView mtxtTestMenu;
public SubMenu_Units(Context context) {
super(context);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.submenu_units_layout);
mSubMenu_Units = this;
initialize();
mtxtTestMenu = (TextView)findViewById(R.id.txtTestCenterMenu);
}
void initialize()
{
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
setCanceledOnTouchOutside(true);
ColorDrawable dialogColor = new ColorDrawable(0xFF424957); // 0xFF424957
getWindow().setBackgroundDrawable(dialogColor);
mOrientation = getContext().getResources().getConfiguration().orientation;
WindowManager.LayoutParams mPortrait_params = getWindow().getAttributes();
mPortrait_params.width = 375;
mPortrait_params.height = 945;
mPortrait_params.gravity = Gravity.CENTER | Gravity.LEFT;
mPortrait_params.x = 5;
mPortrait_params.y = 68;
getWindow().setAttributes(mPortrait_params);
}
You need to have common class where you need to copy below code
i.e; You need to extend below CurrentActivity with CommonActivity
//In Current Activity
case R.id.txtCalibMain:
exitAlert("Some Message)
break;
// Main Acitivty
public void exitAlert(final String message) {
LayoutInflater inflater = LayoutInflater.from(this);
View mExitAlertView = inflater.inflate(R.layout.alert_exit_logout_dialog, null);
final Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(mExitAlertView);
dialog.setCanceledOnTouchOutside(true);
TextView txtAlertMessage = (TextView) mExitAlertView.findViewById(R.id.txtAlertMessage);
txtAlertMessage.setText(message);
mExitAlertView.setOnTouchListener((v, event) -> {
dialog.dismiss();
return false;
});
Button btnExitAlertNo = (Button) mExitAlertView.findViewById(R.id.btnExitAlertNo);
btnExitAlertNo.setOnClickListener(v -> dialog.dismiss());
Button btnExitAlertYes = (Button) mExitAlertView.findViewById(R.id.btnExitAlertYes);
btnExitAlertYes.setOnClickListener(v -> {
dialog.dismiss();
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
});
dialog.show();
}

Updating a shown Dialog

I created a Dialog, using a custom layout:
public class WaitDialog extends DialogFragment {
[..]
#SuppressLint("InflateParams")
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View viewDlg = inflater.inflate(R.layout.dialog_finish, null);
tvStatusMain = (TextView) viewDlg.findViewById(R.id.tvStatusMain);
[..]
}
public void setMessage(String message) {
tvStatusMain.setText(message);
}
}
This code, works fine, but when I instantiate the Dialog like this:
flexWaitDialog = new WaitDialog();
flexWaitDialog.setCancelable(false);
flexWaitDialog.show(this.getFragmentManager(), "login");
and then try to update the message:
flexWaitDialog.setMessage(getString(R.string.initialising));
it shows me the default string from the layout. However, when I use a Handler:
new Handler().post(new Runnable() {
#Override
public void run() {
flexWaitDialog.setMessage(getString(R.string.initialising));
}
});
it does work. Is there a reason for this hoop-jumping? And if not, is there a better way?
I think, onResume is called before onCreateDialog.
You can modify your class to handle that:
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View viewDlg = inflater.inflate(R.layout.dialog_finish, null);
tvStatusMain = (TextView) viewDlg.findViewById(R.id.tvStatusMain);
if (mMessage != null) {
tvStatusMain.seText(mMessage);
}
mViewCreated = true;
[..]
}
public void setMessage(String message) {
if (mViewCreated) {
tvStatusMain.setText(message);
} else {
mMessage = message
}
}

AlertDialog won't show in onCreate method

So I want to ask a user their name before continuing the build of an activity. Most of the activity is populated dynamically so it seems like this should be easy. For some reason, the Dialog never appears though. I've tried everything and the only thing I can think of is: Perhaps it doesn't like being in the onCreate method? It doesn't seem like this should be an issue though since it's literally the last method being called in onCreate. Check it out and let me know what you see:
onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeHotels();
FIRST_TURN = true;
clearOldBoard();
setContentView(R.layout.activity_game_board);
setUpBoardGUI();
setOnPlayerSetUpEventListener(new onPlayerSetUpEventListener() {
#Override
public void onPlayerSetUp(){
prepForFirstTurn();
}
});
startGameDialog();
}
And the startGameDialog method:
public void startGameDialog(){
Context context = getApplicationContext();
ContextThemeWrapper ctw = new ContextThemeWrapper(context, R.style.AppBaseTheme);
AlertDialog.Builder startGameDialog = new AlertDialog.Builder(ctw);
startGameDialog.setTitle(getResources().getString(R.string.whats_your_name));
LinearLayout dialogLayout = new LinearLayout(context);
final EditText newName = new EditText(context);
newName.setText("");
Button submit = new Button(context);
OnClickListener onClick = new OnClickListener() {
#Override
public void onClick(View v) {
GameBoardActivity.NAME = newName.toString();
setUpPlayers();
}
};
submit.setOnClickListener(onClick);
dialogLayout.addView(newName);
dialogLayout.addView(submit);
startGameDialog.setView(dialogLayout);
Dialog dialog = startGameDialog.create();
dialog.show();
dialog.setCancelable(false);
}
The create method return an instance of AlertDialog
Instead of initializing it to the Dialog when you call the create method of the AlertDialog
Dialog dialog = startGameDialog.create();
dialog.show();
pass it to the AlertDialog
AlertDialog alertDialog = startGameDialog.create();
alertDialog.show();
use the currents activity context rather than using the whole application contex.t
Context context = Your_activity.this;

Open a rating bar when a button is tapped

Is it possible to make an 'AlertDialog-like display' that has rating bar inside it when a button is clicked? If yes, will I able to get the value of the rating that is entered? Thanks.
Here is some code I used in an application to show a dialog fragment and get a selection out of it:
public class FeedChooserFragment extends DialogFragment {
/**
* Implement this interface if the activity needs to do something
* after the dialog has been dismissed.
*/
public interface FeedChooserListener {
public void onFeedSelected(NewsFeed feed, Object userData);
}
/**
* Create a new instance of the fragment
*/
public static FeedChooserFragment newInstance(Serializable userData) {
FeedChooserFragment f = new FeedChooserFragment();
Bundle args = new Bundle();
args.putSerializable(Extra.USER_DATA, userData);
f.setArguments(args);
return f;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// This is a list of items, but it could be a custom dialog showing some rating bar
BaseActivity a = (BaseActivity) getActivity();
List<NewsFeed> feed = a.getDataCache().getAllNewsFeed();
adapter = new FeedAdapter(a);
adapter.addAll(feed);
// Here you would create a custom dialog, find the rating bar in the inflated view
// and keep it ready for when the dialog gets dismissed.
AlertDialog.Builder builder = new AlertDialog.Builder(a);
// Here you would set the button listeners instead of the listview listener
builder.setAdapter(adapter, dialogClickListener);
return builder.create();
}
private OnClickListener dialogClickListener = new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
NewsFeed selectedFeed = adapter.getItem(which);
// This is where we try to notify the calling activity or fragment
if (getActivity() instanceof FeedChooserListener) {
((FeedChooserListener) getActivity()).onFeedSelected(selectedFeed, userData);
}
if (getTargetFragment() instanceof FeedChooserListener) {
((FeedChooserListener) getTargetFragment()).onFeedSelected(selectedFeed, userData);
}
dialog.dismiss();
}
};
private Object userData;
private FeedAdapter adapter;
}
Yes, Its possible, Try something like this...
PopupWindow pw;
//We need to get the instance of the LayoutInflater, use the context of this activity
LayoutInflater inflater = (LayoutInflater) TouchPaint.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Inflate the view from a predefined XML layout
View layout = inflater.inflate(R.layout.popup,
(ViewGroup) findViewById(R.id.popup_element));
//popup : name of the XML file which includes the popup_element(can be a linear layout which includes the rating bar)
pw = new PopupWindow(layout,70, 220, true);
pw.showAtLocation(layout, Gravity.LEFT,100,200);
rb =(RatingBar)layout. findViewById(R.id.RatingBar);
rb.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// To Do code
pw.dismiss();
}
});

Categories

Resources