我正在制作一个应用程序,在这个应用程序中我需要显示设备的宽度和高度。最初我在一个班级中计算了宽度和高度,然后立即显示。但是为了使它看起来更有条理,我将它们分开放在一个单独的类中。这个代码在类中:
public class DisplayMeasurement extends Activity{
public int widthScreen = 0;
public int heightScreen = 0;
@SuppressWarnings("deprecation")
public void DisplayHeightWidthMeasurement(){
int Measuredwidth = 0;
int Measuredheight = 0;
Point size = new Point();
WindowManager w = getWindowManager();
if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB_MR2){
w.getDefaultDisplay().getSize(size);
Measuredwidth = size.x;
Measuredheight = size.y;
}else{
Display d = w.getDefaultDisplay();
Measuredwidth = d.getWidth();
Measuredheight = d.getHeight();
}
//int sepertiga = Measuredwidth/3;
//akhir ngukur layar
set(Measuredwidth,Measuredheight);
}
public void set(int Measuredwidth, int Measureheight){
this.widthScreen = Measuredwidth;
this.heightScreen = Measureheight;
}
public int getWidthScreen(){
return widthScreen;
}
public int getHeightScreen(){
return heightScreen;
}
}
然后这是mainActivity上的一段代码:
DisplayMeasurement screenValue = new DisplayMeasurement();
int WidthScreen = screenValue.getWidthScreen();
int HeightScreen = screenValue.getHeightScreen();
TextView text1 = (TextView) findViewById(R.id.text1);
TextView text2 = (TextView) findViewById(R.id.text2);
text1.setText("lebar" + WidthScreen);
text2.setText("tinggi" + HeightScreen);
但我得到的是价值0.是否有人经历过相同的事情,或者是否有人知道这个问题。
答案 0 :(得分:2)
抱歉,我对Android有点新意,但我会试一试。
我不确定你为什么要通过创建一个似乎过于复杂的新活动来组织代码。
public class DisplayMeasurement {
public int widthScreen = 0;
public int heightScreen = 0;
public void DisplayMeasurement(Context context){
Point size = new Point();
WindowManager w = (WindowManager) mContext.getSystemService(mContext.WINDOW_SERVICE);
if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB_MR2){
w.getDefaultDisplay().getSize(size);
widthScreen = size.x;
heightScreen = size.y;
} else {
Display d = w.getDefaultDisplay();
widthScreen = d.getWidth();
heightScreen = d.getHeight();
}
}
public int getWidthScreen(){
return widthScreen;
}
public int getHeightScreen(){
return heightScreen;
}
}
然后在你的主要活动中;
DisplayMeasurement screenValue = new DisplayMeasurement(this);
int WidthScreen = screenValue.getWidthScreen();
int HeightScreen = screenValue.getHeightScreen();
TextView text1 = (TextView) findViewById(R.id.text1);
TextView text2 = (TextView) findViewById(R.id.text2);
text1.setText("lebar" + WidthScreen);
text2.setText("tinggi" + HeightScreen);
不确定它是否会起作用,尚未测试过。
另外,我不确定为什么(仅编码6个月) - 但是当你从不打电话时,DisplayHeightWidthMeasurement()是如何调用的。你所做的就是:
DisplayMeasurement screenValue = new DisplayMeasurement();
所以你的方法:DisplayHeightWidthMeasurement实际上具有获取宽度和高度的逻辑永远不会被调用。您需要先调用它,否则它将返回0,这是您初始化的。
答案 1 :(得分:0)
您永远不会调用函数DisplayHeightWidthMeasurement()
,因此其中的方法set()
尚未调用,因此高度和宽度的值为正如你设置的那样零,就像@TheIT说它不是实例化Activity
的好方法一样,你可以定义一个Class
来获得宽度和 height 而不是使用Activity
。