2013-04-05 48 views
1

我試圖在relativelayout中添加一個tablelayout,但是我想要將這個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

你可以試試這個... 把這個代碼在你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); 
+0

但我已經做了,在我的代碼 – 2013-04-05 21:35:57

相關問題