我想在java中定義3個彼此相鄰的edittext。無法在java中正確定義edittexts
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// LinearLayout
mainLayout=(LinearLayout)findViewById(R.id.linearLayout);
// LinearLayout -> RelativeLayout
main=new RelativeLayout(this);
mainParams=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
main.setLayoutParams(mainParams);
mainLayout.addView(main);
// LinearLayout -> RelativeLayout -> EditText1
EditText item1=new EditText(this);
item1.setHint("Enter the item");
item1.setId(5);
RelativeLayout.LayoutParams etParams=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
etParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
item1.setLayoutParams(etParams);
main.addView(item1);
// LinearLayout -> RelativeLayout -> EditText2
EditText quantity1=new EditText(this);
item1.setHint("Quantity");
item1.setId(6);
RelativeLayout.LayoutParams qparams=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
etParams.addRule(RelativeLayout.ALIGN_LEFT, 5);
item1.setLayoutParams(qparams);
main.addView(quantity1);
// LinearLayout -> RelativeLayout -> EditText3
EditText rate1=new EditText(this);
item1.setHint("rate");
item1.setId(7);
RelativeLayout.LayoutParams rparams=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
etParams.addRule(RelativeLayout.ALIGN_RIGHT, 6);
item1.setLayoutParams(rparams);
main.addView(rate1);
`
我知道你可能會想,我也能做到這一點的XML,但事情是,我有在運行時創造更多edittexts。
問題是,所有的editText都互相重疊。 PLZ幫助
這是因爲您將它們添加到RelativeLayout。如果您希望它們呈現在另一個之下,請使用LinearLayout。如果你在運行時定義了很多視圖,你應該考慮將它們放在一些適配器視圖中,也就是ListView –