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"/>
Related
I have this button to show a dialog which in turn has an EditText for the users to write something and then tap the done button to save it otherwise another button to close the dialog. The problem here is that I am not able to fetch that String that the user wrote. It returns me a null sting instead and causes the app to crash. Here's the code :
I call the dialog up on clicking on a button:
//Write Review Dialog Box
writeReviewBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("HAPPENED", "This Onclick is working");
try{
// Create custom dialog object
final Dialog dialog = new Dialog(GetReviewActivity.this);
// Include dialog's xml file
dialog.setContentView(R.layout.write_review_activity);
// Set dialog title
dialog.setTitle("Your review is valuable");
final EditText etWR = (EditText)findViewById(R.id.etWR);
Button writeButton = (Button) dialog.findViewById(R.id.buttonWR);
Button declineButton = (Button) dialog.findViewById(R.id.buttonNoThanks);
dialog.show();
//Done Button
writeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("HAPPENED: ","writeButton Block Is WORKING!");
Activity activity = GetReviewActivity.this;
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
String Review = etWR.getText().toString();
StoreAReview(Review);
}
});
}
});
// if decline button is clicked, close the custom dialog
declineButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Close dialog
dialog.dismiss();
}
});
}catch (Exception e){
e.printStackTrace();
}
}
});
final EditText etWR = (EditText)findViewById(R.id.etWR); is resolving to Activity#findViewById. But your dialog's layout is not attached to your activity window, it's attached to the dialog. so you have to inflate EditText from your dialog's view:
Try
final EditText etWR = (EditText)dialog.findViewById(R.id.etWR);
instead of
final EditText etWR = (EditText)findViewById(R.id.etWR);
Been through this issue before. I tried initiating EditText with Dialog reference but this didn't work
final EditText etWR = (EditText)dialog.findViewById(R.id.etWR);
Solution:
This is how I solved it:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View dialogWR = getActivity().getLayoutInflater().inflate(R.layout.write_review_activity, null);
etWR = (EditText) dialogWR.findViewById(R.id.etWR);
}
You should initialize EditText
EditText etWR = (EditText)dailog.findViewById(R.id.etWR);
becoz your EditText is coming from dailog. So
U just miss the dialog.findViewById(R.id.etWR)
change this line
final EditText etWR = (EditText)findViewById(R.id.etWR);
to this one
final EditText etWR = (EditText)dialog.findViewById(R.id.etWR);
then, add click event code
i have an activity that when user click on button , a dialog open. in this dialog there is a spinner that have 3 choices: Blue,Red,Green. and there is a submit button. i want that when user select a color and click on submit, in caller activity, its String color set to selected color in dialog. i try this: but not worked. please help me....
String color;
String dialogColor;
showDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("my dialog");
Spinner spinner = (Spinner) dialog.findViewById(R.id.spinner);
final TextView status = (TextView) dialog.findViewById(R.id.status);
Button submit = (Button) dialog.findViewById(R.id.submit);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
dialogColor = parent.getItemAtPosition(position).toString();
status.setText("Color is: "+dialogColor);
color = dialogColor;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("Color",dialogColor);
dialog.dismiss();
}
});
dialog.show();
}
});
i use both of direct and with intent ways to assign my color String to selected value. but not worked. where i have mistake?
I think the best way to create custom dialogs now is the Dialog Fragment, because the simple dialog it's limited. For example it's the way to create a dialogs with material design. And you have a differents ways to take info from dialog fragment, the first and the second for example.
This is basic code to create a dialog fragment:
//Method to call and start dialog fragment class
public void ShowPhotoFilesDialog(Activity context,File photo){
//Declaration of classes
Custom_DialogFragment custom_dialogFragment = new Custom_DialogFragment ();
FragmentManager fragmentManager = context.getFragmentManager();
// The device is using a large layout, so show the fragment as a dialog
custom_dialogFragment.show(fragmentManager, "dialog");
}
And this is the basic dialog fragment class:
public class Custom_DialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
try {
// The only reason you might override this method when using onCreateView() is
// to modify any dialog characteristics. For example, the dialog includes a
// title by default, but your custom layout might not need it. So here you can
// remove the dialog title, but you must call the superclass to get the Dialog.
Dialog dialog = super.onCreateDialog(savedInstanceState);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//To hide action bar from layout
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Declaration of controls
View v = getActivity().getLayoutInflater().inflate(R.layout.my_custom_layout);
builder.setView(v);
//My code
return builder.create();
}
catch (Exception ex){
Log.e("-- Custom_DialogFragment.onCreateDialog --","",ex);
return null;
}
}
}
Tell me if I helped you, good programming!
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 am new to developing apps for android and i want to create a simple Conterter app, just for the start. In my view i have a edittext and a Button. If i click the button, it will open a AlertDialog with list of strings. I cant figure out how to manage this: When i click on one item in the AlertView i want to set the text of the button to the selected string and dismiss the AlertDialog. Can somebody please help me ?
public class VypocetDlzkyActivity extends Activity {
EditText HodnotaDlzka;
Button prevodDlzkaZtlacidlo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vypocet_dlzky);
}
public void zmenPrevodZ(View view){
final String[] jednotkyDlzky = {"milimeter", "centimeter", "decimeter", "meter", "kilometer", "svetelny rok"};
AlertDialog.Builder builder = new AlertDialog.Builder(VypocetDlzkyActivity.this);
builder.setTitle("Vyberte jednotku");
builder.setItems(jednotkyDlzky,null);
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String value = jednotkyDlzky[item].toString();
prevodDlzkaZtlacidlo.setText(value);
dialog.cancel();
}
};
final AlertDialog alert = builder.create();
alert.show();
}
You need to set the values of these 2 member variables in your onCreate() method, like this:
HodnotaDlzka = (EditText)findViewById(R.id.xxxx);
prevodDlzkaZtlacidlo = (Button)findViewById(R.id.yyyy);
xxxx is the ID you gave the EditText in activity_vypocet_dlzky.xml and yyyy is the ID you gave to the Button.
Also, after a button is clicked in the AlertDialog, the dialog is automatically dismissed, so you don't need to call dialog.cancel().
Problem is you didnt add any onClick listnerz.On clicking on button you need to call the required method.
public class MainActivity extends Activity implements OnClickListener {
EditText HodnotaDlzka;
Button prevodDlzkaZtlacidlo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HodnotaDlzka = (EditText) findViewById(R.id.e1);
prevodDlzkaZtlacidlo = (Button) findViewById(R.id.b1);
prevodDlzkaZtlacidlo.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final String[] jednotkyDlzky = {"milimeter", "centimeter", "decimeter", "meter", "kilometer", "svetelny rok"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Vyberte jednotku");
builder.setItems(jednotkyDlzky,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String value = jednotkyDlzky[item].toString();
prevodDlzkaZtlacidlo.setText(value);
}
});
enter code here
final AlertDialog alert = builder.create();
alert.show();
}
}
Hi I'm an android newbie and I've been stuck for a week on this. Any help would be appreciated! I've done a lot of research and can't figure out what is wrong. I've successfully run the bluetoothchat sample code on two phones and successfully communicated via bluetooth. I've also successfully written and run a standalone app that, after a button click on the main activity, opens a custom alertdialog which accepts user input, and passes the input back to the main activity. But when I write the alertdialog code into the BluetoothChat code, nothing happens when I click the button. I've tried to step through the debugger with the phone but with no luck. It doesn't seem to step to the code containing the button click. There are no errors showing. Why won't the alertdialog pop up on button click? Here's the BluetoothChat.java code I've modified :
public class BluetoothChat extends Activity implements OnClickListener{
final Context context = this;
private Button rButton;
View rScreen;
private EditText mAlertDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "+++ ON CREATE +++");
// Set up the window layout
setContentView(R.layout.main);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
//components from main.xml
//When button is clicked, the alert dialog is pulled up
rButton = (Button)findViewById(R.id.buttonr);
mAlertDialog = (EditText)findViewById(R.id.edittextresultm);
//add button listener
rButton.setOnClickListener(new OnClickListener() {
//#Override
public void onClick_register(View view) {
String title = "title";
String buttonOk = "OK";
String buttonCancel = "Cancel";
String madd, name;
//get review.xml view
LayoutInflater li = LayoutInflater.from(context);
View rView = li.inflate(R.layout.review, null);
//AlertDialog dialog;
AlertDialog.Builder adRegister = new AlertDialog.Builder(context);
//set review.xml to adRegister builder
adRegister.setView(rView);
//set title
adRegister.setTitle(title);
//Set EditText views to get user input
final EditText mField = (EditText)rView.findViewById(R.id.editTextm);
final EditText nField = (EditText)rView.findViewById(R.id.editTextn);
//set dialog message
adRegister.setMessage("Message")
.setCancelable(false)
.setPositiveButton(buttonOk, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String madd = mField.getText().toString();
String name = nField.getText().toString();
//get user input and set it to result on main activity
mAlertDialog.setText(mField.getText());
}
})
.setNegativeButton(buttonCancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//if this button is clicked, close current activity
dialog.cancel();
}
});
//Create alert dialog
AlertDialog alertDialog = adRegister.create();
//dialog= adRegister.create();
//show it
adRegister.show();
//dialog.show();
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
}
}
Write your inputDialog code in OnClick Method.
Enjoy!!