Android 横竖屏幕切换(layout-land和layout-port)

本文详细介绍如何在Android应用中控制屏幕的横竖屏切换,包括设置Activity为无标题和全屏模式,通过XML布局文件实现不同屏幕方向的适配,以及在代码中动态地改变屏幕方向。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.首先通过以下语句设置Activity为无标题和全屏模式:

1 // 设置为无标题栏  
2 requestWindowFeature(Window.FEATURE_NO_TITLE);  
3   
4 // 设置为全屏模式  
5 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  
6                      WindowManager.LayoutParams.FLAG_FULLSCREEN);  
7 setContentView(R.layout.main);  

2.下面给出xml文件配置,这里我们在res目录下建立layout-land和layout-port目录,相应的layout文件不变,比如main.xml。layout-land是横屏的layout,layout-port是竖屏的layout,其他的不用管模拟器自动寻找
main.xml文件如下:

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout  
  xmlns:android="http://schemas.android.com/apk/res/android"  
  android:background="@drawable/white"  
  android:orientation="vertical"  
  android:layout_width="fill_parent"  
  android:layout_height="fill_parent"  
>  
  <TextView  
    android:id="@+id/myTextView1"  
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"  
    android:textColor="@drawable/blue"   
    android:text="the portrait"  
  />  
  <Button  
    android:id="@+id/myButton1"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:text="@string/str_button1" />  
</LinearLayout>  

这个xml文件需要在上述所说的2个文件夹下都需要放置.

3.获取资源id的view:

mButton01 = (Button) findViewById(R.id.myButton1);  
mTextView01 = (TextView) findViewById(R.id.myTextView1); 

4.返回当前显示Activity的显示状态(横屏还是竖屏)

// Return the current requested orientation of the activity

if (getRequestedOrientation() == -1){
     
   mTextView01.setText(getResources().getText(R.string.str_err_1001));  
}  

5.设置按钮点击监听器

/* 当点击按钮旋转屏幕画面 */  
    mButton01.setOnClickListener(new Button.OnClickListener()  
    {
     
      // @Override  
      public void onClick(View arg0)  
      {
     
        /* 方法一:重写getRequestedOrientation */  
  
        /* 若无法取得screenOrientation属性 */  
        if (getRequestedOrientation() == -1)  
        {
     
          /* 提示无法进行画面旋转功能,因无法判别Orientation */  
          
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安卓兼职framework应用工程师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值