我正在尝试在relativelayout中添加一个tablelayout,但是我讨厌将这个tablelayout放在现有按钮之上的一些问题,我只能在它下面。
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:stretchColumns="0,1"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="Button" />
lp.addRule(RelativeLayout.ABOVE,idx); 无效
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the size of the screen to set the size of the buttons according
// to the level
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int level = 3;
int width = size.x - (size.x / level);
int btsize = width / level;
// Get the main Layout
RelativeLayout rLayout = (RelativeLayout) findViewById(R.id.main);
//
TableLayout tLayout = new TableLayout(this);
int id = 0;
for (int i = 0; i < level; i++) {
// Create the TableRow
TableRow tRow = new TableRow(this);
for (int j = 0; j < level; j++) {
id++;
Button bt = new Button(this);
bt.setId(id);
bt.setWidth(btsize);
bt.setHeight(btsize);
bt.setMinimumWidth(0);
bt.setMinimumHeight(0);
tRow.addView(bt); // add button into the row
}
tLayout.addView(tRow);// add row into the table
}
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
int idx = findViewById(R.id.button1).getId();
lp.addRule(RelativeLayout.ABOVE, idx);
rLayout.addView(tLayout,lp);// add table into the relativelayout
}
答案 0 :(得分:0)
你可以尝试这个...... 把这段代码放在你的oncreate()方法
中protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relay = (RelativeLayout)findViewById(R.id.rlayout);
LayoutParams layoutprams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
TableLayout table=new TableLayout(this);
relay.addView(table);