简体   繁体   中英

Android Studios: Unlock Screen Orientation On Button Click

I setup a program where there is an image and a select button. When you press select the button disappears and a new back button appears. I want the app to be locked on portrait mode, but when you press select I want the screen rotation to unlock, and when turned sideways i want the image to fill be the center of the screen, and the back button to disappear. When turned sideways again I want the back button to reappear. When the back button is clicked it disappears and the select button returns again. I want it to lock the screen to portrait again.

If this is possible I would really appreciate any help! Thanks!

public class MainActivity extends AppCompatActivity {

private Button select;
private Button right;
private Button left;
private Button back;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_main);

            select = findViewById(R.id.select);
    left = findViewById(R.id.button2);
    right = findViewById(R.id.button3);
    back = findViewById(R.id.back);

    back.setVisibility(View.INVISIBLE);

    select.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            right.setVisibility(View.INVISIBLE);
            left.setVisibility(View.INVISIBLE);
            back.setVisibility(View.VISIBLE);
            select.setVisibility(View.INVISIBLE);
        }
    });

    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            right.setVisibility(View.VISIBLE);
            left.setVisibility(View.VISIBLE);
            back.setVisibility(View.INVISIBLE);
            select.setVisibility(View.VISIBLE);
        }
    });
}
}

You can lock and unlock the orientation whenever you need want to by calling methods like these

/** Locks the device window in landscape mode. */
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);


/** Locks the device window in portrait mode. */
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);


/** Allows user to freely use portrait or landscape mode. */
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);

It is up to you when you want to call them

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM