android:更新查看位置和大小

时间:2012-10-04 07:48:57

标签: android

我想以编程方式更新视图的位置和大小,但我无法做到这一点,如果我使用其中一个,它可以正常工作。首先我更新尺寸

oldLayout = (android.widget.RelativeLayout.LayoutParams) view.getLayoutParams();
    changeInWidth = oldLayout.width*ratioWidth;
    changeInHeight = oldLayout.height*ratioHeight;


newLayout = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
    if (standardWidth>screenWidth)
        newLayout.width = (int) (oldLayout.width-changeInWidth);
    else if (standardWidth<screenWidth)
        newLayout.width = (int) (oldLayout.width+changeInWidth);
    else
        newLayout.width=oldLayout.width;
    if (standardHeight>screenHeight)
        newLayout.height = (int) (oldLayout.height-changeInHeight);
    else if (standardHeight<screenHeight)
        newLayout.height = (int) (oldLayout.height+changeInHeight);
    else
        newLayout.height=oldLayout.height;

    //newLayout.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    //newLayout.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

现在此代码开始更新位置

    if (standardWidth>screenWidth)
        newLayout.leftMargin =  (int) (oldLayout.leftMargin-changeInWidth);
    else if (standardWidth<screenWidth)
        newLayout.leftMargin =  (int) (oldLayout.leftMargin+changeInWidth);
    else
        newLayout.leftMargin=oldLayout.leftMargin;
    if (standardHeight>screenHeight)
        newLayout.topMargin = (int) (oldLayout.topMargin-changeInHeight);
    else if (standardHeight<screenHeight)
        newLayout.topMargin = (int) (oldLayout.topMargin+changeInHeight);
    else
        newLayout.topMargin=oldLayout.topMargin;

    view.setLayoutParams(newLayout);

1 个答案:

答案 0 :(得分:1)

        TextView Status = (TextView) findViewById(R.id.Status);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)Status.getLayoutParams();
        Context context = getApplicationContext();
        float d = context.getResources().getDisplayMetrics().density;//get density 
        int p = (int)(80 * d);//size 80 is in pixel so multiply by d to get it in dp
        params.setMargins(0 , p , 0 , 0 ); //substitute parameters for left, top, right, bottom
        Status.setLayoutParams(params);