MainActivity如下:
package cc.teststatusbarheight; import java.lang.reflect.Field; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.app.Activity; import android.content.Context; /** * Demo描述: * 利用反射获取状态栏StatusBar的高度 * * 反射基础: * http://blog.csdn.net/lfdfhl/article/details/10311505 * * 参考资料: * http://blog.csdn.net/lilu_leo/article/details/10211327 * http://blog.csdn.net/dany1202/article/details/6571010 * Thank you very much */ public class MainActivity extends Activity { private Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init(){ mButton=(Button) findViewById(R.id.button); mButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { getStatusBarHeight(MainActivity.this); } }); } private void getStatusBarHeight(Context context){ int statusBarHeight=0; try { Class clazz=Class.forName("com.android.internal.R$dimen"); Object object=clazz.newInstance(); Field field=clazz.getField("status_bar_height"); //反射出该对象中status_bar_height字段所对应的在R文件的id值 //该id值由系统工具自动生成,文档描述如下: //The desired resource identifier, as generated by the aapt tool. int id = Integer.parseInt(field.get(object).toString()); System.out.println("id="+id); //依据id值获取到状态栏的高度,单位为像素 statusBarHeight = context.getResources().getDimensionPixelSize(id); System.out.println("statusBarHeight="+statusBarHeight+"pixel"); } catch (Exception e) { // TODO: handle exception } } }
main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" android:layout_centerHorizontal="true" android:layout_marginTop="100dip" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="利用反射获取状态栏StatusBar的高度" android:layout_centerInParent="true" /> </RelativeLayout>