我同时使用使用 Activity 或不使用 Activity,在 Android 中没有同时获得高度和宽度。请纠正我,我做错了什么。
这里有活动:
public class LandPort extends Activity{
public final static int height = 0;
public final static int width = 0;
Context context;
DisplayMetrics displaymetrics = new DisplayMetrics();
public LandPort(Context context) {
this.context = context;
}
public int getHeight() {
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
return height;
}
public int getWidth() {
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = displaymetrics.widthPixels;
return width;
}
}
在 MainActivity 中:
LandPort lp= new LandPort(getApplicationContext());
int height = lp.getHeight();
int width =lp.getWidth();
将高度和宽度都设为 0;
另一个没有活动:
public class GetHeigthWidth {
public final static int height = 0;
public final static int widht = 0;
Context context;
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
public GetHeigthWidth(Context context) {
this.context = context;
}
public int getHeight() {
@SuppressWarnings("deprecation")
int height = display.getHeight();
return height;
}
public int getWidth() {
@SuppressWarnings("deprecation")
int widht = display.getWidth();
return widht;
}
}
来自 MainActivity:
GetHeigthWidth ghw= new GetHeigthWidth(getApplicationContext());
int height = ghw.getHeight();
int width =ghw.getWidth();
Aslo 得到高度和宽度 0。
那么,如何在此获得实际高度和宽度>