如何设置gravity
和margin
自动生成(代码内)TextViews
和Buttons
?它们在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);
}
希望您能找到一种方法来设置按钮的重力而不改变尺寸。
答案 0 :(得分:1)
1)获取TextView参考电视。
2)tv.setGravity(Gravity.CENTER);
无法确定使用LinearLayout ..尝试相对或绝对
答案 1 :(得分:0)
使用View.setLayoutParams(ViewGroup.LayoutParams params)
。请http://developer.android.com/reference/android/R.styleable.html#ViewGroup_Layout查看LayoutParams
。
答案 2 :(得分: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);
将在视图中设置文本的重力