Android点击按钮实现全屏的代码

package com.hsx.test;

import java.lang.reflect.Field;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.tv_open_fullscreen).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                stateControl(true);

                int stateHeight = getStateHeight();
                Toast.makeText(MainActivity.this, "状态栏高度为:" + stateHeight, Toast.LENGTH_LONG).show();
            }
        });

        findViewById(R.id.tv_close_fullscreen).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                stateControl(false);
            }
        });

    }

    /**
     * 控制是否全屏
     * 
     * @param enable
     * @return
     * @author Doraemon
     * @time 2014年12月3日下午6:03:33
     */
    private void stateControl(boolean enable) {
        if (enable) {
            LayoutParams lp = getWindow().getAttributes();
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(lp);
        } else {
            LayoutParams attr = getWindow().getAttributes();
            attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attr);
        }

    }

    /**
     * 获取状态栏高度
     * 
     * @return
     * @return
     * @author Doraemon
     * @time 2014年12月3日下午6:03:45
     */
    private int getStateHeight() {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, sbar = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            sbar = getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sbar;
    }
}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。