Android:设置x和y pos

时间:2012-03-15 05:22:33

标签: android android-layout relativelayout

我是android新手。我开始尝试构建一个方法库。我在java中更舒服,因为运行时的所有内容似乎都发生在java中,我正在尝试构建处理java中GUI的方法。到目前为止我没有太多的东西,我正在寻找去定义x和y pos来绘制对象。这就是我到目前为止所做的:

//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
}

所以如果我有一个按钮命名按钮,我说     setSizeByRatio(button,25,50);它将按钮高度设置为屏幕的25%,高度设置为任何屏幕的50%。

我的主要问题是你如何设置你希望它开始绘制的x和y位置,就像你在reg java中一样? 我跑过布局(l,t,r,b);但它只设置相对于父母的x和y。

接下来的问题是我应该学习哪些GUI方法?我知道这会杀死很多人,但我如何评论XML呢?我和XML一样是新手。

1 个答案:

答案 0 :(得分:1)

这不是真正相关的,但它清理了一行代码(如果你有更多这样的东西,可以用作清理更多代码行的参考)。

这样,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;
    }
}