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

在android中的特定位置设置按钮,android,android-layout,Android,Android Layout,我想在图像视图的特定位置放置一个按钮,即固定的x、y位置。因为安卓系统的每个设备都有不同的屏幕大小,所以有可能做到这一点吗 我已经尝试过使用布局参数来实现这一点,但它不能正常工作 POI3 = new Button(this); POI3.setId(3); POI3.setBackgroundColor(Color.TRANSPARENT); POI3.setOnClickListener(new OnClickListener() { @Overri

我想在图像视图的特定位置放置一个按钮,即固定的x、y位置。因为安卓系统的每个设备都有不同的屏幕大小,所以有可能做到这一点吗

我已经尝试过使用布局参数来实现这一点,但它不能正常工作

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);
POI3=新按钮(此按钮);
POI3.setId(3);
POI3.setBackgroundColor(颜色:透明);
POI3.setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
onButtonClick(“3”);
}
});
params=新的RelativeLayout.LayoutParams(75,75);
params.leftMargin=466;
params.topMargin=255;
//此行定义如何解释params.leftMargin和params.topMargin。
//在这种情况下,“”表示黄色图像视图的右侧。
参数addRule(RelativeLayout.RIGHT\u OF,黄色\u iv\u id);
rl.addView(POI3,参数);

要将按钮设置在固定位置,必须使用
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;
}

“its not working normal”是否需要详细说明?请提供一行代码,说明您在何处初始化黄色的iv_id。“its not working normal”表示单击事件未到达该确切位置。但是,为什么要动态添加按钮。您可以针对每个屏幕大小使用xml进行设计。使用Point在特定位置添加视图