如何用 RelativeLayout 替换 AbsoluteLayout

How to replcae AbsoluteLayout with RelativeLayout

我在下面的代码

中使用了一个Class
this.guageBack= (AbsoluteLayout) findViewById(R.id.gaugeFrame);
AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams(this.needleWidth,this.needleHeight,this.needleX,this.needleY);
gaugeNeedle.setLayoutParams(params);

AbsoluteLayout 已弃用 所以当我想使用 RelativeLayout 时我没有替换

AbsoluteLayout.LayoutParams(this.needleWidth,this.needleHeight,this.needleX,this.needleY);

因为它接受如下两个参数

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(needleWidth, needleHeight);

我该怎么办?

这样做

public class CodeLayout extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Creating a new RelativeLayout
        RelativeLayout relativeLayout = new RelativeLayout(this);

        // Defining the RelativeLayout layout parameters.
        // In this case I want to fill its parent
        RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.FILL_PARENT,
                RelativeLayout.LayoutParams.FILL_PARENT);

        // Creating a new TextView
        TextView tv = new TextView(this);
        tv.setText("Test");

        // Defining the layout parameters of the TextView
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.CENTER_IN_PARENT);

        // Setting the parameters on the TextView
        tv.setLayoutParams(lp);

        // Adding the TextView to the RelativeLayout as a child
        relativeLayout.addView(tv);

        // Setting the RelativeLayout as our content view
        setContentView(relativeLayout, rlp);
    }
} 

试试这个代码,

AbsoluteLayout absoluteLayout = //get absolute layout

Button button = new Button();
AbsoluteLayout.LayoutParms params = absoluteLayout.generateDefaultLayoutParams();
params.x = 100;
params.y = 100;

absoluteLayout.addView(button, params);

只需添加此代码而不是您的代码

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(needleWidth, needleHeight);
        params.topMargin = needleY;
        params.leftMargin = needleX;