在android中的特定位置设置按钮

时间:2013-11-06 06:58:01

标签: android android-layout

我想在特定位置的图像视图上放置一个按钮。在固定的x,y位置。是否可以这样做,因为android为每个设备都有不同的屏幕尺寸。

我尝试过使用布局参数,但它无法正常工作。

POI3 = new Button(this);
    POI3.setId(3);
    POI3.setBackgroundColor(Color.TRANSPARENT);
    POI3.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            onButtonClick("3");
        }
    });
    params = new RelativeLayout.LayoutParams(75, 75);
    params.leftMargin = 466;
    params.topMargin = 255;

    // This line defines how params.leftMargin and params.topMargin are interpreted.
    // In this case, "<80,90>" means <80,90> to the right of the yellow ImageView.
    params.addRule(RelativeLayout.RIGHT_OF, yellow_iv_id);

    rl.addView(POI3, params);

1 个答案:

答案 0 :(得分:0)

要将您的按钮设置为修复位置,您必须使用dp而不是xp,请使用以下代码进行转换:

    /**
    * This method converts dp unit to equivalent pixels, depending on device density. 
    * 
    * @param dp A value in dp (density independent pixels) unit. Which we need to        convert into pixels
    * @param context Context to get resources and device specific display metrics
   * @return A float value to represent px equivalent to dp depending on device density
   */
    public static float convertDpToPixel(float dp, Context context){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float px = dp * (metrics.densityDpi / 160f);
    return px;
  }

 /**
 * This method converts device specific pixels to density independent pixels.
 * 
 * @param px A value in px (pixels) unit. Which we need to convert into db
 * @param context Context to get resources and device specific display metrics
 * @return A float value to represent dp equivalent to px value
  */
public static float convertPixelsToDp(float px, Context context){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float dp = px / (metrics.densityDpi / 160f);
    return dp;
}