error in doing onLongClickListener(Android Studio)

732 views Asked by At

I have an EditText with a text, and there is a button, what I want the code to make is that when a long click is done on the Button(IButton1) the EditText's will be gone... The code:

    private void Delete() {
            ImageButton IButton1=(ImageButton)findViewById(R.id.ibdelete);
//Click:
            IButton1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(getApplicationContext(),"A long click is required in order to delete the text", Toast.LENGTH_LONG).show();
                }
            });
//Long Click:
                IButton1.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        return false;
                        EditText text1 = (EditText) findViewById(R.id.EditText1);
                        text1.setText("");
                        Toast.makeText(getApplicationContext(), "The text is gone!", Toast.LENGTH_SHORT).show();
                    }
                });
        }

Now, the problemis that it says: "Unreachable statement" and the line EditText text1 = (EditText) findViewById(R.id.EditText1); is underline with red(an error), and I would like to solve this...

1

There are 1 answers

0
takendarkk On BEST ANSWER

Right now the first statement executed in onLongClick() is return false; which will end the method. Any and all code after that in the method can never be reached. The return should be the last thing in your method.

You need to move your return statement to the end of the method like this.

public boolean onLongClick(View v) {
    EditText text1 = (EditText) findViewById(R.id.EditText1);
    text1.setText("");
    Toast.makeText(getApplicationContext(), "The text is gone!", Toast.LENGTH_SHORT).show();
    return false;
}