边距不起作用

时间:2012-09-05 09:55:30

标签: android android-layout

我以编程方式进行了以下布局:

LinearLayout progressLayout = new LinearLayout(this);
    progressLayout.setOrientation(LinearLayout.VERTICAL);

    TextView t = new TextView(this);
    t.setText("Test..");
    t.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);

    LayoutParams l = new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    l.setMargins(10, 10, 10, 25);   ===> does not work? 
    t.setLayoutParams(l);

    ProgressBar circle = new ProgressBar(this, null,
            android.R.attr.progressBarStyleLarge);
    circle.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));


    progressLayout.setLayoutParams(new LayoutParams(
            android.view.ViewGroup.LayoutParams.FILL_PARENT,
            android.view.ViewGroup.LayoutParams.FILL_PARENT));

    progressLayout.setGravity(Gravity.CENTER);

    progressLayout.addView(t);
    progressLayout.addView(circle);

    this.setContentView(progressLayout);

但是我在setMargins中作为值没有给出什么,它根本没有任何效果。
是什么原因?

布局具有fill_parent的高度和宽度,因此不会出现问题..

Thx:)

2 个答案:

答案 0 :(得分:0)

progressLayout.setGravity(Gravity.CENTER); 

将textview和progressbar对齐在中心。

答案 1 :(得分:0)

试用此解决方案

LinearLayout progressLayout = new LinearLayout(this);
        progressLayout.setOrientation(LinearLayout.VERTICAL);

        TextView t = new TextView(this);
        t.setText("Test..");
        t.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);

        LayoutParams l = new LayoutParams(
                android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
                android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
        // ===> does not work?
        // l.setMargins(50, 50, 50, 25);
        // t.setLayoutParams(l);
        l.leftMargin = 10;
        l.topMargin = 0;
        l.rightMargin = 0;
        l.bottomMargin = 150;

        ProgressBar circle = new ProgressBar(this, null,
                android.R.attr.progressBarStyleLarge);
        LayoutParams p = new LayoutParams(
                android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
                android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
        // circle.setLayoutParams(p);
        p.leftMargin = 0;
        p.topMargin = 0;
        p.rightMargin = 0;
        p.bottomMargin = 20;

        progressLayout.setLayoutParams(new LayoutParams(
                android.view.ViewGroup.LayoutParams.FILL_PARENT,
                android.view.ViewGroup.LayoutParams.FILL_PARENT));

        progressLayout.setGravity(Gravity.CENTER);

        progressLayout.addView(t, l);
        progressLayout.addView(circle, p);

        this.setContentView(progressLayout);