我有一个相对布局,有两个按钮和一个textview。我想要做的是在最左边有一个按钮,中间是textview,最右边是另一个按钮。试着在没有XML的情况下做到这一点。
这是我的代码:
RelativeLayout fm = new RelativeLayout(this);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
fm.setLayoutParams(lp);
fm.setBackgroundColor(Color.CYAN);
Button done = new Button(this);
done.setId(10);
done.setText("Done");
Button save = new Button(this);
save.setId(12);
save.setText("Save");
TextView formManager = new TextView(this);
formManager.setId(11);
formManager.setText("Form Manager");
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
fm.addView(formManager, lp);
lp.removeRule(RelativeLayout.CENTER_IN_PARENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
fm.addView(done, lp);
lp.removeRule(RelativeLayout.ALIGN_PARENT_LEFT);
lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
fm.addView(save, lp);
lp.removeRule(RelativeLayout.ALIGN_PARENT_RIGHT);
mainLayout.addView(fm);
问题是......就是“保存”按钮会拉伸并占据整个布局并且非常薄。基本上这个代码没有像我想象的那样发生。关于如何实现这一目标的任何想法?
答案 0 :(得分:0)
试试这种方式
LinearLayout mainLayout = (LinearLayout) findViewById(R.id.mainLayout);
RelativeLayout fm = new RelativeLayout(this);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
fm.setLayoutParams(lp);
fm.setBackgroundColor(Color.CYAN);
Button done = new Button(this);
done.setId(10);
done.setText("Done");
Button save = new Button(this);
save.setId(12);
save.setText("Save");
TextView formManager = new TextView(this);
formManager.setId(11);
formManager.setText("Form Manager");
RelativeLayout.LayoutParams lpp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
formManager.setLayoutParams(lpp);
lpp.addRule(RelativeLayout.CENTER_IN_PARENT);
fm.addView(formManager, lpp);
RelativeLayout.LayoutParams doneLayoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
done.setLayoutParams(doneLayoutParams);
doneLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
fm.addView(done, doneLayoutParams);
RelativeLayout.LayoutParams saveLayoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
save.setLayoutParams(saveLayoutParams);
saveLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
fm.addView(save, saveLayoutParams);
mainLayout.addView(fm);