0

我想在特定位置的图像视图上放置一个按钮。即在固定的 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);
4

1 回答 1

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;
}
于 2013-11-20T05:15:25.833 回答