如何用RelativeLayout替换绝对布局



我有一个在代码下面使用的类

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);

因为它接受两个args,比如低于

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

我该怎么办?

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

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

这样做

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);

相关内容

  • 没有找到相关文章

最新更新