Q:

Setting gravity for auto generated TextView and Button

How can I set the gravity and margin for auto-generated(within the code) TextViews and Buttons? They are inside a LinearLayout.
Here is my generation code:
        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);
    }

Hope you find a way to set the button gravity without changing it size.

A:

1) Get Reference of TextView say tv.
2) tv.setGravity(Gravity.CENTER);
It is not sure work with LinearLayout.. Try Relative Or Absolute

