Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Click on back button twice?

Tags:

android

back

I am a beginner in android.

My Scenario

I have a screen A which has 2 buttons Button A Button B.

When I open my application screen A opens up with the above 2 buttons, when I click on Button B a textview and Edittext is displayed.

What I want ?

When the back button is pressed the textview and edittext should hide and when I press back again, I should exit out of Screen A.

What have I tried so far ?

Is my below code correct for what I want ?

Main Activity.xml

import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {

    TextView title;
    EditText userinput;
    Button buttonA,buttonB;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initialize();
    }

    private void initialize() {
        userinput = (EditText)findViewById(R.id.userinput);
        title = (TextView)findViewById(R.id.title);
        buttonA = (Button)findViewById(R.id.buttonA);
        buttonB = (Button)findViewById(R.id.buttonB);
        buttonA.setOnClickListener(this);
        buttonB.setOnClickListener(this);
    }



@Override
public void onBackPressed() {
  title.setVisibility(View.INVISIBLE);
 userinput.setVisibility(View.INVISIBLE); 


    }

    @Override
    public void onClick(View v) {

        switch(v.getId())
        {

        case R.id.buttonA:
            break;

        case R.id.buttonB:

            title.setVisibility(View.VISIBLE);
            userinput.setVisibility(View.VISIBLE);
            break;
        }


    }


}

I referred this and this link but did not understand. If some one could help me in achieving me want I want 1


1 Answers

When the back button is pressed the textview and edittext should hide and when I press back again,

@Override
public void onBackPressed() {
   if (title.getVisibility() != View.VISIBLE && 
             userInput.getVisibility() != View.VISIBLE) {
      super.onBackPressed();
      return;
   }
   title.setText(null);
   userinput.setText(null);
   title.setVisibility(View.INVISIBLE);
   userinput.setVisibility(View.INVISIBLE);        
 }
like image 66
Blackbelt Avatar answered Jun 06 '26 13:06

Blackbelt