Is there a way to access Dialog objects from MainActivity? - android

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();
}

Related

How to use one loading window instance in all activities

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.

How to create a popup when button is pushed in Android?

How can I create a custom popup class that accepts a simple string message? Im new to Android and help with code will be appreciated.
When a button is pushed in the main layout, the popup must pop up on the screen.
Custom popup class
public class CustomPopup extends PopupWindow {
private String message;
private Double anchorX;
private Double anchorY;
PopupWindow popup;
public CustomPopup(String message) {
super();
this.message = message;
}
public void showPopup(Activity context) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
}
Main Class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText messageTxt = (EditText) findViewById(R.id.messageTxt);
Button generateBtn = (Button) findViewById(R.id.generateBtn);
String message = messageTxt.getText().toString();
final CustomPopup popup = new CustomPopup(message);
generateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
popup.showPopup();
}
});
}
}
You can change the following code any way you need. This is just an example of how you make and implement a custom DialogFragment.
He is the code I use. I find it quite flexible because you can create several similar dialogs for slightly different tasks. You will need to create a layout file - this gives you a great deal of flexibility on function and style.
My layout file is fragment_ok_cancel_dialog.
To satisfy your requirements just create your own layout file with all the elements in it you need (like your image).
In the Activity that calls the dialog you will need to implement the Listener.
implements OkCancelDialogFragment.OkCancelDialogListener
Another advantage is with my code you can change the title and the message to fit the needs of any Activity.
private void callMyDialog(){
//Customize the title and message as needed
String title = "This is my dialog title";
String mess = "This is my dialog message";
OkCancelDialogFragment dialog = OkCancelDialogFragment.newInstance(title, mess);
dialog.show(getFragmentManager(), "OkCancelDialogFragment2");
}
Now you need to implement the dialog callback in the Activity that calls the DialogFragment.
#Override
public void onFinishOkCancelDialog(boolean submit) {
if(submit){
// Do something positive
}
else{
// Do something negative
}
}
Now the code for the DialogFragment:
public class OkCancelDialogFragment extends DialogFragment {
private static final String ARG_TITLE = "title";
private static final String ARG_MESSAGE = "message";
Context context = null;
private String title;
private String message;
private boolean submitData = false;
private OkCancelDialogListener mListener;
public OkCancelDialogFragment() {
}
public static OkCancelDialogFragment newInstance(String title, String message) {
OkCancelDialogFragment fragment = new OkCancelDialogFragment();
Bundle args = new Bundle();
args.putString(ARG_TITLE, title);
args.putString(ARG_MESSAGE, message);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
title = getArguments().getString(ARG_TITLE);
message = getArguments().getString(ARG_MESSAGE);
}
}
#Override
public Dialog onCreateDialog(Bundle saveIntsanceState){
context = getActivity();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View rootView = inflater.inflate(R.layout.fragment_ok_cancel_dialog, null, false);
final TextView titleView = (TextView)rootView.findViewById(R.id.tvTitle);
final TextView messView = (TextView)rootView.findViewById(R.id.tvMessage);
titleView.setText(title);
messView.setText(message);
builder.setView(rootView)
// .setTitle(title)
.setPositiveButton(R.string.ok_button_dialog_title, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
submitData = true;
if(mListener == null) mListener = (OkCancelDialogListener) context;
mListener.onFinishOkCancelDialog(submitData);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
submitData = false;
if(mListener == null) mListener = (OkCancelDialogListener) context;
mListener.onFinishOkCancelDialog(submitData);
}
});
return builder.create();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
if(mListener == null) mListener = (OkCancelDialogListener) context;
}
catch (Exception ex){
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OkCancelDialogListener {
void onFinishOkCancelDialog(boolean submit);
}
}
Please note that .setTitle(title) is valid for API 23 or higher (or maybe API 21 or higher?).
You can create your custom xml layout
and in the OnClickListener of the button you can put this :
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
alertLayout = inflater.inflate(R.layout.YOUR_CUSTOM_POPUP_LAYOUT, null);
final AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setView(alertLayout);
TextView msg= alertLayout.findViewById(R.id.YOUR_TEXTVIEW_ID);
alert.show();
after that you can add another button in your popup and set a listener on it to dismiss the layout after the click.

Trying to use getIntent() within a custom dialog comes up as an error. Solution to get around this error?

I am sending a string from an activity to my custom dialog.
This is the activity in which I create a bundle and insert the string, then send it to the dialog activity.
Bundle sendToDialog = new Bundle();
sendToDialog.putString("caloreis", strCalories);
Intent a = new Intent(CaloriesLogMainActivity.this, ActivityDialog.class);
a.putExtras(sendToDialog);
This is the custom dialog activity in which I am trying to receive the intent from the activity.
getIntent(), is coming up as an error. How would I get around this error?
public class ActivityDialog {
Context mContext;
Date mDate;
public ActivityDialog(Context context, CaloriesLogMainActivity caloriesLogMainActivity) {
mContext = context;
}
public void show() {
LayoutInflater factory = LayoutInflater.from(mContext);
View view = factory.inflate(R.layout.dialog_activity, null);
AlertDialog.Builder builder = new AlertDialog.Builder((mContext));
final EditText calories = (EditText) view.findViewById(R.id.etCalories);
Bundle recieveFromActivity = getIntent().getExtras();
String strCaloreis = recieveFromActivity.getString("calories");
calories.setText(strCaloreis);
builder.setTitle(R.string.edit_log_title);
builder.setNegativeButton(R.string.create_log_negative_button,
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNeutralButton(R.string.create_log_neutral_button, null);
builder.setPositiveButton(R.string.create_log_positive_button, null);
builder.create().show();
builder.setView(view);
builder.create().show();
}
}
you have to extend Activity class , then only you can access getIntent()...
so your code should be like this
public class ActivityDialog extends Activity{
Context mContext;
Date mDate;
protected void onCreate(Bundle savedInstanceState){
//here you can call getIntent()
}
public void show() {
// or even from here ,you can call getIntent()
LayoutInflater factory = LayoutInflater.from(mContext);
View view = factory.inflate(R.layout.dialog_activity, null);
AlertDialog.Builder builder = new AlertDialog.Builder((mContext));
final EditText calories = (EditText) view.findViewById(R.id.etCalories);
Bundle recieveFromActivity = getIntent().getExtras();
String strCaloreis = recieveFromActivity.getString("calories");
calories.setText(strCaloreis);
builder.setTitle(R.string.edit_log_title);
builder.setNegativeButton(R.string.create_log_negative_button,
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNeutralButton(R.string.create_log_neutral_button, null);
builder.setPositiveButton(R.string.create_log_positive_button, null);
builder.create().show();
builder.setView(view);
builder.create().show();
}
}
Your ActivityDialog class is an Activity and thus should extend Activity. This is a general rule, but specifically your problem here is due to the fact that getIntent() is defined in Activity, so you must extend that in order to use it.
It might be because of your spelling mistake in sendToDialog.putString("caloreis", strCalories); because you later reference the extra as "calories" not "caloreis". (I tried to put this in an edit but it was uner 6 characters long...)

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;

Set dynamically created TextView on frame layout

I want to pass some data from one activity to another and set it in dynamically created TextView over frame layout of that activity..I'm using intent for that but at second activity the data is not getting extracted..Can any one tell me the simple way for this..
Following is my code..
Hidden.java
public class Hidden extends Activity implements OnClickListener {
Button btnnameadd, btnnameremove, btnmobileadd, btnmobileremove, btndone;
EditText etname, etmobile;
ImageView ivlogo;
private AlertDialog dialog;
private Uri mImageCaptureUri;
Intent jump;
//options for image selection
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
LinearLayout llname, llmobile, llimage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hidden);
captureImageInitialization();
init();
}
private void init() {
etname=(EditText)findViewById(R.id.editTextname);
etmobile=(EditText)findViewById(R.id.editTextmobile);
btnnameadd=(Button)findViewById(R.id.buttonnameadd);
btnnameremove=(Button)findViewById(R.id.buttonnameremove);
btnmobileadd=(Button)findViewById(R.id.buttonmobileadd);
btnmobileremove=(Button)findViewById(R.id.buttonmobileremove);
btndone=(Button)findViewById(R.id.buttondone);
llname=(LinearLayout)findViewById(R.id.name);
llmobile=(LinearLayout)findViewById(R.id.mobile);
btnnameadd.setOnClickListener(this);
btnnameadd.setOnClickListener(this);
btnnameremove.setOnClickListener(this);
btnmobileadd.setOnClickListener(this);
btnmobileremove.setOnClickListener(this);
btndone.setOnClickListener(this);
}
#Override
public void onClick(View v) {
jump=new Intent(Hidden.this,Framelayout.class);
if(v.getId()==R.id.buttonnameadd)
{
String strname=etname.getText().toString();
Log.d("Log",strname);
jump.putExtra("Name",strname);
}else if(v.getId()==R.id.buttonnameremove)
{
btnnameremove.setEnabled(false);
llname.removeView(findViewById(R.id.editTextname));
}else if(v.getId()==R.id.buttonmobileadd)
{
String strmobile=etmobile.getText().toString();
Log.d("Log",strmobile);
jump.putExtra("Mobile",strmobile);
Log.d("LOG",jump.putExtra("Mobile",strmobile).toString());
}else if(v.getId()==R.id.buttonmobileremove)
{
llmobile.removeView(findViewById(R.id.editTextmobile));
}else if(v.getId()==R.id.buttondone)
{
Log.d("LOG","1");
startActivity(jump);
}
}
}
FrameLayout.java
public class Framelayout extends Activity implements OnClickListener {
FrameLayout frameLayout;
Button b2,b3;
//private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_framelayout);
frameLayout = (FrameLayout)findViewById(R.id.f1);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.buttonload);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
}
public void onClick(View v) {
if(v.getId()==R.id.button2){
Intent i=new Intent(Framelayout.this,Hidden.class);
startActivity(i);
}else if(v.getId()==R.id.buttonload){
Log.d("Log",getIntent().getStringExtra("Name"));
editframelayout();
}
}
private void editframelayout() {
String name=getIntent().getExtras().getString("Name");
String mobile=getIntent().getExtras().getString("Mobile");
TextView tvname=new TextView(this);
tvname.setText(name);
tvname.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tvname.setGravity(Gravity.CENTER);
TextView tvmobile=new TextView(this);
tvmobile.setText(mobile);
tvmobile.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tvmobile.setGravity(Gravity.CENTER);
frameLayout.addView(tvname);
frameLayout.addView(tvmobile);
}
}
You must use one of putExtra() overloaded methods of the intent instance you created to add your data.
Here is a sample:
Intent intent = new Intent(this, SignoutActivity.class); // # this parameter is the context of the caller
intent.putExtra("PARAM_TEXTBOX_TEXT", textboxText);
startActivity(intent);
Edit for the code you added, your design is very poor and doesn't accomplish what is intended.
Every time you click a Button a new instance of Intent is created. you are calling startActivity() only in single case:
else if(v.getId()==R.id.buttondone)
{
Log.d("LOG","1");
startActivity(jump);
}
Now you assume that the parameters added in previous button clicks are still there, but they aren't. When you click buttondone you create a new instance of Intent with no extras at all.
You can work this around as follows:
...
else if(v.getId()==R.id.buttondone)
{
String strname = etname.getText().toString();
if (strname != null && !strname.equals(""))
{
jump.putExtra("Name",strname);
}
String strmobile = etmobile.getText().toString();
if (strmobile != null && !strmobile.equals(""))
{
jump.putExtra("Mobile",strmobile);
}
startActivity(jump);
}
It still isn't well structured, but might do the trick for you
Use getIntent().getStringExtra("Name") instead of getIntent().getExtras().getString("Name");
getIntent().getStringExtra("Name")

Categories

Resources