0

如何设置自动生成的gravitymargin(在代码中)TextViewsButtons?它们在一个LinearLayout.

这是我的生成代码:

        for(int i=0; i<num_enter; i++){
    final int cuco = i;
    LinearLayout linlay = new LinearLayout(this);
    linlay.setOrientation(0);
    TextView text = new TextView(this);
    text.setText(name[cuco] + "        ");
    linlay.addView(text);
    TextView num = new TextView(this);
    num.setId(cuco);
    num.setText("" + current[cuco]);
    linlay.addView(num);
    Button minus = new Button(this);
    minus.setText("-");
    minus.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            int cval = current[cuco];
            int currentF = current[cuco] - 1;
            current[cuco] = current[cuco] -1;
            SetSql update = new SetSql(SpellCast.this);
            update.open();
            update.changeCurrent(currentF, cval, name[cuco]);
            update.close();
            ((TextView) findViewById(cuco)).setText("" + currentF);
        }
    });
    LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.RIGHT);
    minus.setLayoutParams(p);
    linlay.addView(minus);
    Button plus = new Button(this);
    plus.setText("+");
    plus.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            int cval = current[cuco];
            int currentF = current[cuco] + 1;
            current[cuco] = current[cuco] + 1;
            SetSql update = new SetSql(SpellCast.this);
            update.open();
            update.changeCurrent(currentF, cval, name[cuco]);
            update.close();
            ((TextView) findViewById(cuco)).setText("" + currentF);
        }
    });
    LinearLayout.LayoutParams w = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.RIGHT);
    plus.setHeight(LayoutParams.WRAP_CONTENT);
    plus.setWidth(50);
    plus.setLayoutParams(w);
    linlay.addView(plus);

    main.addView(linlay);
    }

希望你能找到一种方法来设置按钮重力而不改变它的大小。

4

3 回答 3

1

1)获取TextView的参考说电视。

2) tv.setGravity(Gravity.CENTER);

不确定是否可以使用 LinearLayout .. 尝试相对或绝对

于 2012-05-04T19:53:00.250 回答
0

使用View.setLayoutParams(ViewGroup.LayoutParams params). 查看http://developer.android.com/reference/android/R.styleable.html#ViewGroup_LayoutLayoutParams.

于 2012-05-04T19:55:24.053 回答
0

由于没有人解决利润率问题

LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
p.setMargins(10, 10,10,10);
p.gravity = Gravity.CENTER;

textView.setLayoutParams(p);

使用 setLayoutParams 时,请确保布局参数的类型与父视图相匹配,在本例中为 LinearLayout

setGravity(Gravity.CENTER);将设置视图内文本的重力

于 2012-05-04T19:55:34.083 回答