[英]Why is this WindowManager working until I ask to recall it's value?
I have some code that I am using to find the dimensions for my QR code image.我有一些代码可以用来查找二维码图像的尺寸。 However, I am trying to do so within a fragment.但是,我试图在一个片段中这样做。 What I've done is within the main activity, declare a public int for the dimen, and then run the dimension code within the MainActivity and do a getter for it.我所做的是在主要活动中,为维度声明一个公共整数,然后在 MainActivity 中运行维度代码并为其执行一个 getter。 However, whenever I try to use the dimen value, either from a getter or within MainActivity itself, the app crashes.但是,每当我尝试使用 dimen 值时,无论是从 getter 还是在 MainActivity 本身中,应用程序都会崩溃。 It will run, but it crashes the second you try to do anything with dimen, be it putting it into a toast, or for a method call.它会运行,但是当你尝试对 dimen 做任何事情时它会崩溃,无论是将它放入吐司中,还是用于方法调用。
public class MainActivity extends AppCompatActivity {
public int dimen;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
//initializing a variable for default display.
Display display = manager.getDefaultDisplay();
//creating a variable for point which is to be displayed in QR Code.
Point point = new Point();
display.getSize(point);
//getting width and height of a point
int width = point.x;
int height = point.y;
//generating dimension from width and height.
dimen = Math.min(width, height);
dimen = dimen * 3 / 4;
Toast.makeText(MainActivity.this,dimen,Toast.LENGTH_SHORT).show(); //If you remove this line, the code runs. However, using any other use of dimen will also crash the app. Toast.makeText is not the problem.
}
}
I have tried doing it within the fragment, and within the MainActivity.我已经尝试在片段和 MainActivity 中执行此操作。 I can't find the solution.我找不到解决方案。
I have found my problem.我发现了我的问题。 Within this line,在这条线内,
WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
It should be它应该是
WindowManager manager = (WindowManager) this.getSystemService(WINDOW_SERVICE);
This is because WindowManager requires to be called from an Activity or Service, but it is not being called from any.这是因为 WindowManager 需要从 Activity 或 Service 调用,但它没有被任何调用。
Secondly, there was an error within the toast message.其次,toast 消息中存在错误。 It should be它应该是
Toast.makeText(MainActivity.this,String.valueOf(dimen),Toast.LENGTH_SHORT).show();
Very simple, but ints must be string within Toast, so String.valueOf fixes this.非常简单,但 int 必须是 Toast 中的字符串,因此 String.valueOf 解决了这个问题。 Just posting so anyone in the future has a solution!只是发布,以便将来的任何人都有解决方案!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.