Suppose my current activity is Main.java and I have already declared its layout through setContentView(R.layout.layout1) from its onCreate method. Now, is it in any way possible for me to access a different layout? For e.g., assuming there is another layout - layout2 which has TextView with id tv, then I won't be able to execute the following code from Main.java :
TextView text = (TextView) findViewById(R.id.tv);
text.setText("blah blah");
Is there any way that I can set tv's value from Main.java.
My actual code is the following
setContentView(R.layout.layout);
Button button = (Button) findViewById(button);
button(buttonListener);
Dialog dialog;
Inside the listener, I have the following code:
TextView dialogTitle = (TextView) findViewById(R.id.dialog_title);
dialogTitle.setText("Email");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View customView = getLayoutInflater().inflate(R.layout.dialog, null);
builder.setView(customView);
dialog = builder.create();
dialog.show();
The problem that I am facing is that dialog_title is in dialog.xml and not in layout.xml
You can always inflate any XML layout you want at any time:
View layout2 = LayoutInflater.from(this).inflate(R.layout.layout2, null);
You can use Bundles
In Activity 1
String your_string = "Hello, World!";
Bundle bundle = new Bundle();
bundle.putString("The key for this string", your_string );
Intent ActivityToLaunch= new Intent(this, ActivityB.class);
ActivityToLaunch.putExtras(bundle);
this.startActivity(ActivityToLaunch);
In Activity 2
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout2); //Setup some layout, set to your own
String content = getIntent().getExtras().getString("The key for this string");
TextView text = (TextView) findViewById(R.id.tv);
text.setText(content);
}
The thread starter said that he wanted to raise a custom dialog, so here goes the edit
This is my class which will generate a custom Dialog:
public class ErrorDialog {
TextView msgTextView;
Button toSettings;
final Context c;
Dialog errorDialog;
/**
* #param c The Context
* #param title Title of the Dialog
* #param msg Message og the Dialog
* #param textOnButton The text on the button
*/
public ErrorDialog(final Context c, String title, String msg, String textOnButton) {
this.c = c;
errorDialog = new Dialog(c);
errorDialog.setContentView(R.layout.error_dialog);
errorDialog.setTitle(title);
msgTextView = (TextView) errorDialog.findViewById(R.id.errorMSG);
msgTextView.setText(msg);
toSettings = (Button) errorDialog.findViewById(R.id.toSettings);
toSettings.setText(text);
toSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//doing operations when the user clicks my button in the dialog.
}
});
errorDialog.show();
errorDialog.setCancelable(true);
}
}
Use this class this way:
new ErrorDialog(getApplicationContext(), "My Title", "My Message to the user", "Text on the button");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View customView = getLayoutInflater().inflate(R.layout.dialog, null);
builder.setView(customView);
TextView dialogTitle = (TextView) customView.findViewById(R.id.dialog_title);
dialogTitle.setText("Email");
Related
EDIT: Attached the code for my onCickListener which sends Rating Value to and then Show my Dialog.
I have a TextView which shows me a rating in numbers format (4.5). And when I press this TextView a dialog pops up to let me change the rating trough a RatingBar. The Ratingbar`s rating is set to equal the TextView Rating when it pops up. This functions as expected and the TextView is updated to the new rating when I press OK. BUT when I press the TextView again, the initial first value is shown and not the value which I just updated it to. I have figured out as much as this is because I have all my code within the onCreateDialog (). I have tried to get this to work by using OnStart() and onResume() but then my app crashes. How do I write this code correctly?
Attached is my functional code with all code set within the onCreadeDialog()
public class RatingDialog extends DialogFragment{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
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
final View DialogView = inflater.inflate(R.layout.dialog_rating, null);
/**
* Retrieve the argument "num" (Previously rating) and set ratingbar´s rating equal to this.
*/
getArguments().getFloat("num");
RatingBar ValueView = (RatingBar) DialogView.findViewById(R.id.Ratingbar);
ValueView.setRating(getArguments().getFloat("num"));
builder.setView(DialogView)
// Add action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
/**
* Get the new value from the Ratingbar and send this back to the AddRating TextView
*/
RatingBar ValueView = (RatingBar) DialogView.findViewById(R.id.Ratingbar);
float Value = ValueView.getRating();
TextView Text = (TextView) getActivity().findViewById(R.id.AddRating);
Text.setText(String.valueOf(Value));
RatingDialog.this.getDialog().cancel();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
RatingDialog.this.getDialog().cancel();
}
});
return builder.create();
}
}
Below is the code for onCickListener which sends Rating Value to and then Show my Dialog:
/**
* Set the On Click Listener and send the Rating value to the Dialog
*/
final TextView Rating = (TextView) findViewById(R.id.AddRating);
String S = (String) Rating.getText();
final Float F;
if (S==""){
F=0.0f;}
else
F = Float.valueOf(S);
Rating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RatingDialog newFragment = new RatingDialog();
newFragment.show(getSupportFragmentManager(), "Rating");
/**
* Send Verdien av rating til dialogvinduet
*/
Bundle args = new Bundle();
args.putFloat("num", F);
newFragment.setArguments(args);
}
});
You are passing same F value all the time.
It should be:
final TextView rating = (TextView) findViewById(R.id.AddRating);
rating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RatingDialog newFragment = new RatingDialog();
newFragment.show(getSupportFragmentManager(), "Rating");
/**
* Send Verdien av rating til dialogvinduet
*/
Bundle args = new Bundle();
args.putFloat("num", TextUtils.isEmpty(rating.getText()) ?
0.0f : Float.valueOf(rating.getText().toString()));
newFragment.setArguments(args);
}
});
In that case you will pass actual value of rating TextView.
And yes, please follow java code convention. Because it's hard to read your code.
Context: There is a custom Listview and each list item has a button in it. When you click the button an alertDialog appears with an edit text and submit button. This only happens on the first click, on subsequent clicks a Toast will simply appear with the number of times it has been clicked thus far.
When you click the submit button a toast will appear displaying the text that was entered into the editText and the number of times they have clicked on it which will presumably always be 1 since this can only happen on the first click.
Problem: The timesClicked counter is not working properly if the user so much as clicks on the editText before clicking submit. It is restting to 0 I guess. However if the user does not click on the editText then the program works normally. 0_o I'm at a loss.
Attempts at solving: I simplified the code down quite a bit to try and pinpoint the problem and this is where I am stuck. Originally I was inflating a view that only had an edit text and then I was just using builder.setPositiveButtton. I thought implementing the buttons directly in the view would fix it but that doesn't seem to be the case. I have been stuck on this for awhile. Any help would be great
Here is a video of the bug happening
private class OnSubtractClickListener implements View.OnClickListener {
final int id; //id of list item that was clicked
int timesClicked;
Toast toast;
public OnSubtractClickListener(int id, View view) {
super();
this.id = id;
timesClicked = 0;
}
#Override
public void onClick(View view) {
if (timesClicked != 0) {
toast.setText(Integer.toString(timesClicked));
toast.show();
}
else{
toast = Toast.makeText(view.getContext(), "", Toast.LENGTH_SHORT);
final View dialogView = LayoutInflater.from(view.getContext()).inflate(R.layout.dialog_add_notes, null);
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setView(dialogView);
builder.setTitle("Subtract cigar?");
builder.setIcon(R.mipmap.monkey_launcher);
final AlertDialog dialog = builder.create();
Button yesButton = (Button)dialogView.findViewById(R.id.dialog_notes_yes_button);
yesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editText = (EditText)dialogView.findViewById(R.id.dialog_editText);
String userInput = editText.getText().toString();
String timesClickedString = Integer.toString(++timesClicked);
toast.setText(timesClickedString + ": " + userInput);
toast.show();
dialog.dismiss();
}
});
dialog.show(); //new
}
}
}
You can make class that extend Dialog.
example:
public class CustomDialog extends Dialog {
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WindowManager.LayoutParams lpWindow = new WindowManager.LayoutParams();
lpWindow.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
lpWindow.dimAmount = 0.8f;
getWindow().setAttributes(lpWindow);
setContentView(R.layout.activity_custom_dialog);
editText = (EditText) findViewById(R.id.editText);
}
}
You can use this dialog..
mCustomDialog = new CustomDialog();
mCustomDialog.show();
You can make the layout as you wish.
======================================================================
You can use AlertDialog.Builder.setPositiveButton.
site : setPositiveButton
example...
toast = Toast.makeText(view.getContext(), "", Toast.LENGTH_SHORT);
final View dialogView = LayoutInflater.from(view.getContext()).inflate(R.layout.dialog_add_notes, null);
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setView(dialogView);
builder.setTitle("Subtract cigar?");
builder.setIcon(R.mipmap.monkey_launcher);
builder.setPositiveButton("text", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
EditText editText = (EditText)dialogView.findViewById(R.id.dialog_editText);
String userInput = editText.getText().toString();
String timesClickedString = Integer.toString(++timesClicked);
toast.setText(timesClickedString + ": " + userInput);
toast.show();
}
});
final AlertDialog dialog = builder.create();
dialog.show(); //new
I found the solution. Basically what was happening was that when the Keyboard appeared it would cause the listview to adjust the size recreating the whole listview with recycled/old versions of the list items from before the dialog appeared -effectively undoing any changes made to the ListView items by the dialog.
In your listview XML add this:
android:descendantFocusability="beforeDescendants"
In Mainfest.xml:
<activity android:name= ".yourActivity"
android:windowSoftInputMode="adjustPan"/>
im trying to build share dialog.
in this share dialog I have facebook,whatsapp,mail and more.
im trying the make the background of every view change on touch to indicate the toch.
so far no problem.
the problem is that I also want to let the user move is finger into other option and when he do that the previous background return to his original color and the new view background changes.
i just cant get the hover event at all, and I couldn't trigger other onTouchEvent as long as the first one is still alive.
this is my code so far:
public class customDialogFragment1 extends DialogFragment {
public customDialogFragment1() {
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
postShareUrl=getActivity().getResources().getString(R.string.servicePostShareUrl);
id=getArguments().getString("body");
postTitle=getArguments().getString("subject");
Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);
sendIntent.setType("text/plain");
Dialog dialog = new Dialog(getActivity(),android.R.style.Theme_Translucent_NoTitleBar);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),android.R.style.Theme_Translucent_NoTitleBar);
LayoutInflater inflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.share_title_layout, null);
// Set title divider color
TextView txtTitle= (TextView) v.findViewById(R.id.share_title);
Typeface tf = Typeface.createFromAsset(getActivity().getResources().getAssets(),
"fonts/OpenSansHebrew-Bold.ttf");
txtTitle.setTypeface(tf);
View layout=inflater.inflate(R.layout.custom_share_layout_inner,null);
builder.setView(layout);
ImageView facebook= (ImageView) layout.findViewById(R.id.imgFaceebook);
ImageView whatsapp= (ImageView) layout.findViewById(R.id.imgWhatsapp);
ImageView more= (ImageView) layout.findViewById(R.id.imgMore);
ImageView mail= (ImageView) layout.findViewById(R.id.imgMail);
facebook.setOnClickListener(imageClickListener);
whatsapp.setOnClickListener(imageClickListener);
more.setOnClickListener(imageClickListener);
mail.setOnClickListener(imageClickListener);
List activities = getActivity().getPackageManager().queryIntentActivities(sendIntent, 0);
Context context=(Activity)getActivity();
for(int i=0;i<activities.size();i++) {
ResolveInfo appPacageName = (ResolveInfo) activities.get(i);
Log.i("pacageName", appPacageName.toString());
if (appPacageName.toString().contains("com.facebook.composer")) {
shareCheckList[0] = appPacageName;
} else if (appPacageName.toString().contains("whatsapp")) {
shareCheckList[1] = appPacageName;
} else if (appPacageName.toString().contains("mail")) {
shareCheckList[2] = appPacageName;
}
}
dialog.setContentView(layout);
Window window = dialog.getWindow();
window.setLayout(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
window.setGravity(Gravity.CENTER);
window.setLayout(MainActivity.screenWidth-90,350);
return dialog;
}
and this is my ontouch listener :
private View.OnClickListener imageClickListener=new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT,getArguments().getString("subject"));
intent.putExtra(Intent.EXTRA_TEXT,getArguments().getString("body"));
switch (v.getId()){
case R.id.imgFaceebook:
if(!shareCheckList[0].toString().isEmpty()){
intent.setClassName(shareCheckList[0].activityInfo.packageName, shareCheckList[0].activityInfo.name);
((Activity)getActivity()).startActivity(intent);
break;
case R.id.imgWhatsapp:
intent.setClassName(shareCheckList[1].activityInfo.packageName, shareCheckList[1].activityInfo.name);
((Activity)getActivity()).startActivity(intent);
}
break;
case R.id.imgMail:
try{
intent.setClassName(shareCheckList[2].activityInfo.packageName, shareCheckList[2].activityInfo.name);
((Activity)getActivity()).startActivity(intent);
break;
case R.id.imgMore:
CustomDialogFragment2 cdf=new CustomDialogFragment2();
Bundle bundle = new Bundle();
bundle.putString("body",id);
bundle.putString("subject", postTitle);
cdf.setArguments(bundle);
cdf.show(getActivity().getFragmentManager(), "customDialogFragment2");
break;
}
}
};
If I understood right, you should use state list:
http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList
Just create xml drawable file for every ImageView, and set for each state item with source you need.
I am developing a android app where I have created Customize alert dialog. I declare Globally alert dialog and and AlertDialog.builder as follow. Now I am calling three method f1(), f2(),f3(), in button click.
btn_my_order.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
f1();
f2();
f3();
return false;
}
});
I Declared orderDialog and builde globally as follow :-
private AlertDialog orderDialog = null;
AlertDialog.Builder builder;
My f1() block is as follow :-
F1{
builder = new AlertDialog.Builder(MainScreen.this);
mContext = getApplicationContext();
/**
* by the help of inflater my ordre is showing in list view
*/
inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
orderDialogLayout = inflater.inflate(R.layout.my_order_list,(ViewGroup)findViewById(R.id.order_list_root));
orderList = (ListView) orderDialogLayout.findViewById(R.id.order_list);
ibOrderDelete = (ImageButton)orderDialogLayout.findViewById(R.id.deleteOrder);
tvPrice = (TextView) orderDialogLayout.findViewById(R.id.order_list_total);
tvTaxes = (TextView) orderDialogLayout.findViewById(R.id.order_list_taxes);
tvTotal = (TextView) orderDialogLayout.findViewById(R.id.order_list_grand_total);
Button bclose = (Button) orderDialogLayout.findViewById(R.id.close);
Button bPlaceOrder = (Button) orderDialogLayout.findViewById(R.id.my_order_placeorder);
bclose.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
orderDialog.dismiss();
System.out.println(" click on close button");
}
});
/**
* click of place order to kitchen
*/
bPlaceOrder.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
System.out.println("Place order click");
palceMyOrdertoServer();
new SendOrderFromTable().execute();
System.out.println("place order to server is called");
String msg = "Your Order is Successfully placed to Kitcken";
Message msgObject = new Message();
msgObject.what = 1;
msgObject.obj = msg;
addMenuItemHandler.sendMessage(msgObject);
orderDialog.dismiss();
}
});}
My f2() is for some Cursor work with data base
F2{
// many stuff to be here populate data from cursor and bind it with adapter
// no any issue in this mehod
}
Now finally I am calling f3()
F3{
builder.setView(orderDialogLayout);
orderDialog = builder.create();
orderDialog.show();
}
Now i am going to explain all my problem f1() method is for initialization f2() is for populate data and f3() to show customize alert dialog . Why my
orderDialog.dismiss();
is not working for me.Even though i am able to see my logcat with message
"Click on close button"
That means execution is going on dismiss() method then why customize alert dialog didn't close at click. Thanks in advance to all
You should add final in your orderDialog private variable.
I'm trying to get some values from a dialog. I have an activity called Splash that shows a dialog with a form. It displays the form wel but i gives me an error when i try to get that values (nullpointer).
I have the folowing code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
//datos objeto
nombre = (TextView) findViewById(R.id.tv_nombre);
padre = (TextView) findViewById(R.id.tv_nom_padre);
madre = (TextView) findViewById(R.id.tv_nom_madre);
rgSexo = (RadioGroup) findViewById(R.id.rg_sexo);
fecha_nac = (DatePicker) findViewById(R.id.dp_fecha_nac);
rb_m = (RadioButton) findViewById(R.id.rb_masc);
rb_f = (RadioButton) findViewById(R.id.rb_fem);
perfil = new PerfilCRUD(this);
perfil.open();
//first time
if (perfil.primeraVez()){
//muestro el popup
Log.v(TAG, "prim vez");
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog_perfil);
dialog.setTitle("Datos del usuario");
dialog.show();
Button botOk = (Button) dialog.findViewById(R.id.b_ok);
botOk.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Log.v(TAG, "boton ok");
Log.v(TAG, nombre.getText().toString());
}
});
It gives me the error when i try to get the nombre.getText().toString() value. It happens that with all variables/controls values. It forces to close the application.
Thanks!!
Its because nombre is in your original layout. Either call a TextView in the layout that you inflate in the dialog or create a class level variable String name = ""; then in
if (perfil.primeraVez()){
name = nombre.getText().toString();
then you can use name in your dialog