1

我正在尝试在 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

}
4

1 回答 1

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); 
于 2013-04-05T20:25:02.030 回答