-1

I have a number of EditText lines on a UI where the user enters some data. The user enters a Date (from a DatePicker fragment) on the fListenerEditText line. The focus is then returned to the first EditText line which is cListenerEditText. For the default Back button behavior, if the user then presses the Back button, the Activity would close and the Date data would be immediately lost, and the user is returned to the previous Activity.

In my case, I would like to launch a Dialog fragment that asks the user if they want to discard the Date they previously entered at fListenerEditText. If the user clicks the "OK" button, the data is discarded, the Activity closes and the user returns to the previous activity. Note in my case, the soft keyboard is not open when the user presses the Back button key.

How do I use a FocusListener and a Back button listener together? What am I missing here?

public class EditActivity extends AppCompatActivity {

    private ListenerEditText cListenerEditText, dListenerEditText, eListenerEditText, fListenerEditText;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(layout.activity_edit); 

    cListenerEditText = (ListenerEditText) findViewById(id.CEditText);
    dListenerEditText = (ListenerEditText) findViewById(id.DEditText);
    eListenerEditText = (ListenerEditText) findViewById(id.EEditText);
    fListenerEditText = (ListenerEditText) findViewById(id.FEditText);

    final int stringDueDate = fListenerEditText.getText().toString().replace(" ", "").length();

    cListenerEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus && fListenerEditText.getText().length() > 0) {
            // add some type of Back button listener here.    
            }
        }
    });
AJW
  • 1,578
  • 3
  • 36
  • 77

2 Answers2

2
  1. Override method onBackPressed() and check the input length of field fListenerEditText. If its not 0 then show confirmation dialog otherwise call super.onBackPressed() to finish activity to show previous one from activity-stack.

  2. If your click on OK button, then just finish EditActivity.

Update EditActivity as below:

public class EditActivity extends AppCompatActivity {

    private ListenerEditText cListenerEditText, dListenerEditText, eListenerEditText, fListenerEditText;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(layout.activity_edit);

        cListenerEditText = (ListenerEditText) findViewById(id.CEditText);
        dListenerEditText = (ListenerEditText) findViewById(id.DEditText);
        eListenerEditText = (ListenerEditText) findViewById(id.EEditText);
        fListenerEditText = (ListenerEditText) findViewById(id.FEditText);

        ..........
        ...............
    }

    @Override
    public void onBackPressed() {

        if (cListenerEditText.hasFocus() && fListenerEditText.getText().toString().length() > 0) {
            // Show dialog
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Discard?");
            builder.setMessage("Your change will be discarded");

            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    // Finish activity
                    finish();
                }

            });

            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // Do nothing
                    dialog.dismiss();
                }
            });

            AlertDialog alert = builder.create();
            alert.show();

        } else {
            super.onBackPressed();
        }
    }
}

FYI, If you want to do extra operation depending on the focus then use cListenerEditText.hasFocus() to check the focus and to change the focus after picking date just use cListenerEditText.requestFocus() and fListenerEditText.clearFocus().

Hope this will help~

Ferdous Ahamed
  • 21,438
  • 5
  • 52
  • 61
  • Nice. Ok only issue is that I need to somehow handle the fact that the the focus will be on cListenerEditText line and not on the fListenerEditText line when the user presses the Back button. So I need a FocusListener for cListernerEditText and test the length of fListenerEditText. Any thoughts on how to achieve? – AJW Jul 09 '17 at 21:01
  • check my updated answer. Use condition: `if (cListenerEditText.hasFocus() && fListenerEditText.getText().toString().length() > 0) {......}` – Ferdous Ahamed Jul 09 '17 at 21:02
  • Ok I see. And add onBackPressed() NOT in onCreate() section correct? Just add in the main part of the Activity? – AJW Jul 09 '17 at 21:07
  • app crashes at "alert.show();" line. Logcat says "You need to use a Theme.AppCompat theme (or descendant) with this activity. – AJW Jul 09 '17 at 21:10
  • Use `AlertDialog.Builder builder = new AlertDialog.Builder(this);` OR `AlertDialog.Builder builder = new AlertDialog.Builder(EditActivity.this);`. I have updated my answer. – Ferdous Ahamed Jul 09 '17 at 21:15
  • That did the trick. Is the AlertDialog.Builder preferred versus launching a DialogFragment because it is simple? – AJW Jul 09 '17 at 21:21
  • 1
    As you are showing simple dialog, you can use `AlertDialog.Builder`. For better understanding check this answer: https://stackoverflow.com/questions/7977392/android-dialogfragment-vs-dialog and https://stackoverflow.com/questions/13765127/dialogfragment-advantages-over-alertdialog – Ferdous Ahamed Jul 09 '17 at 21:25
  • 1
    Very good, I will study. Answer upvoted and accepted. You mentioned AlertDialog.Builder(this) OR ...(EditActivity.this). What is difference between these two and how should I decide which to use? – AJW Jul 09 '17 at 21:29
  • This represents the current activity context. In SO there are lots of question and answers regarding `Context`. Check this: https://stackoverflow.com/questions/22966601/what-is-different-between-mainactivity-this-vs-getapplicationcontext – Ferdous Ahamed Jul 09 '17 at 21:31
  • I appreciate your time and expertise to answer the original question and the follow-up questions. Cheers! – AJW Jul 09 '17 at 21:34
1

You can show new Dialog which asks if the user wants to discard the changes or keep them in OnBackpress() and onOptionSelected()

cListenerEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus && fListenerEditText.getText().length() > 0) {
            // add some type of Back button listener here.  
              onBackPressed()
            }
        }
    });

@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
        .setTitle("Your dialog title")
        .setMessage("Do you want to discard the old changes")
        .setNegativeButton("No", new OnClickListener(){
          public void onClick(){
           // your task
          }
        })
        .setPositiveButton("yes", new OnClickListener() {

            public void onClick(DialogInterface arg0, int arg1) {
                EditActivity.super.onBackPressed();
            }
        }).create().show();
}
Ritt
  • 3,181
  • 3
  • 22
  • 51
  • Yes, but where do I put the onBackPressed code so that it is only handled if the cListenerEditText has focus and stringDueDate > 0? – AJW Jul 09 '17 at 20:54
  • call onBackPressed from your if condition. check the updated answer. – Ritt Jul 09 '17 at 21:00
  • The cListenerEditText.setOnFocusChangeListener is in the onCreate() section. Do I put your onBackPressed() in the onCreate() section or below it in the main section of the Activity? – AJW Jul 09 '17 at 21:14