How to show or hide views within a layout

Android programming: mode selection and switching using a single activity, Show or hide view within a layout.

Sometimes ,we don't want to create several new activities to implement some simple view switching. So we can hide or show some view within a single layout to achieve layout reuse. :shipit:

In the xml file 🔍

android:visibility="visible"; 
android:visibility="invisible";    <!--The view  occupies the layout-->
android:visibility="gone";    <!--The view does not occupy the layout-->

In the java file 🔎

ImageView view = findViewById(R.id.Image_1)
view.setVisibility(View.VISIBLE);
view.setVisibility(View.INVISIBLE);
view.setVisibility(View.GONE);

Maybe we should also override the onOptionsItemSelected() function. 😶‍🌫️ Here is a sample: 🈂️

// Called when a button in the action bar is pressed
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    switch (item.getItemId()) {
        case android.R.id.home:
            // If the back button was pressed, handle it the normal way
            onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

// Called when the user presses the back button
@Override
public void onBackPressed() {
    // Close the activity
    if(auto_follow_buttons.getVisibility() == View.VISIBLE){
        auto_follow_buttons.setVisibility(View.GONE);
        modes.setVisibility(View.VISIBLE);
    }
    else {
        finish();
    }
}
posted @ 2022-07-26 10:59  litecdows  阅读(25)  评论(0编辑  收藏  举报