我是安卓新手。我开始尝试构建一个方法库。我在 Java 中更自在,并且由于运行时的一切似乎都发生在 Java 中,我正在尝试构建处理 Java 中 GUI 的方法。到目前为止我没有太多,我正在寻找定义在什么 x 和 y 位置绘制对象。这是我目前所拥有的:
//method to get width or Xpos that is a one size fits all
public int widthRatio(double ratioIn){
DisplayMetrics dm = new DisplayMetrics(); //gets screen properties
getWindowManager().getDefaultDisplay().getMetrics(dm);
double screenWidth = dm.widthPixels; //gets screen height
double ratio = screenWidth/100; //gets the ratio in terms of %
int displayWidth = (int)(ratio*ratioIn); //multiplies ratio desired % of screen
return displayWidth;
}
//method to get height or Ypos that is a one size fits all
public int heightByRatio(double ratioIn){
DisplayMetrics dm = new DisplayMetrics(); //gets screen properties
getWindowManager().getDefaultDisplay().getMetrics(dm);
double screenHeight = dm.heightPixels; //gets screen height
double ratio = screenHeight/100; //gets the ratio in terms of %
int newHeight = (int)(ratio*ratioIn); //multiplies ratio by desired % of screen
return newHeight;
}
//sets size of any view (button, text, ...) to a one size fits all screens
public void setSizeByRatio(View object, int width, int height){
ViewGroup.LayoutParams params = object.getLayoutParams(); // gets params of view
params.width = widthRatio(width); // sets width by portion of screen
params.height = heightByRatio(height); // sets height by portion of screen
}
所以如果我有一个名为 button 的按钮,我说 setSizeByRatio(按钮, 25, 50);它将按钮高度设置为屏幕的 25%,并将其高度设置为任何屏幕的 50%。
我的主要问题是如何像在 reg java 中一样设置 x 和 y 位置以使其开始绘制? 我遇到了 layout(l, t, r, b);但它只设置相对于父级的 x 和 y。
接下来的问题是,就 GUI 方法而言,我还应该学习什么?我知道这会杀死很多人,但我如何在 XML 中发表评论?我对 XML 和 android 一样陌生。
最佳答案
这不是真正相关的,但它清理了一行代码(如果您有更多类似的东西,可以作为清理更多行代码的引用)。
这样,DisplayMetrics 就适用于这两个轴,而不必在每次获得另一个轴时都输入它。
//method to get width or Xpos that is a one size fits all
DisplayMetrics dm = new DisplayMetrics() { // This line now applies to both int and gets screen properties
public int widthRatio(double ratioIn){
getWindowManager().getDefaultDisplay().getMetrics(dm);
double screenWidth = dm.widthPixels; //gets screen height
double ratio = screenWidth/100; //gets the ratio in terms of %
int displayWidth = (int)(ratio*ratioIn); //multiplies ratio desired % of screen
return displayWidth;
}
//method to get height or Ypos that is a one size fits all
public int heightByRatio(double ratioIn){
getWindowManager().getDefaultDisplay().getMetrics(dm);
double screenHeight = dm.heightPixels; //gets screen height
double ratio = screenHeight/100; //gets the ratio in terms of %
int newHeight = (int)(ratio*ratioIn); //multiplies ratio by desired % of screen
return newHeight;
}
}
关于Android:设置 x 和 y 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9714413/