Search code examples
androidonbackpressedsetcontentview

How to get current content view of activity?


I have a content view say primary set on main activity, when clicked on a button, it sets another content view say secondary with setContentView(R.layout.sec_content). What i want now that when Back Button Pressed, It should set the primary content if current view is secondary otherwise it should close the activity. how do i do that? here is my code

public class Ch_1 extends AppCompatActivity {

Button men1, men2, men3;
TextView tv1;

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

    men1 = (Button)findViewById(R.id.men1);
    men1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            setContentView(R.layout.activity_read__view);
            TextView tv1 = (TextView)findViewById(R.id.read_view);
            tv1.setText("This is text in READ_VIEW activity");




        }
    });


}

}


Solution

  • public class MainActivity extends AppCompatActivity {
    
    Boolean isClose = true;
    Button btn;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.button);
    }
    
    public void onpressed(View view){
        isClose = false;
        setContentView(R.layout.second);
    }
    
    @Override
    public void onBackPressed() {
        if (isClose){
            finish();
        } else {
            setContentView(R.layout.activity_main);
            isClose = true;
        }
    }
    

    }