我有一個onClickListener
,其中我嘗試將兩個視圖動態添加到現有ViewGroup
。我只是想在另一個的右邊添加一個,但是不管我做什麼,它們都是正確的,它們的左邊對齊。其他方面的佈局是服從的。例如,我可以指定一個寬度爲MATCH_PARENT,視圖按照這種方式呈現。另外,我正在編程模仿我如何爲XML中的另一個ViewGroup
指定佈局,並且XML指定的佈局能夠正常工作。這裏是我的代碼:Android:以編程方式添加視圖並且不遵守佈局
Editable nodeName = nodeSelectView.getText();
View insertPoint = findViewById(R.id.insertionPoint);
//the two views to be added dynamically
EditText nodeView = new EditText(ManageDomainsActivity.this);
Button nodeButton = new Button(ManageDomainsActivity.this);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
lp.addRule(RelativeLayout.LEFT_OF, nodeButton.getId());
nodeView.setLayoutParams(lp);
nodeView.setGravity(Gravity.LEFT);
nodeView.setText(nodeName.toString());
lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
lp.addRule(RelativeLayout.RIGHT_OF, nodeView.getId());
lp.addRule(RelativeLayout.ALIGN_BASELINE, nodeView.getId());
lp.addRule(RelativeLayout.ALIGN_BOTTOM, nodeView.getId());
nodeButton.setLayoutParams(lp);
nodeButton.setText("Kill");
nodeButton.setGravity(Gravity.CENTER);
((ViewGroup) insertPoint).addView(nodeView, 0,
new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
((ViewGroup) insertPoint).addView(nodeButton, 1,
new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));