2014-05-02 111 views
0

我在我的TableLayout中放置了60個按鈕,這些按鈕超出了屏幕,因此我需要滾動才能顯示剩餘的按鈕。我試過這段代碼,但應用程序不工作。以編程方式滾動TableLayout

protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     TableLayout tableLayout; 
     tableLayout = (TableLayout) findViewById(R.id.table_layout); 
     TableRow tr; 
     int buttonNumber = 0; 
     for (int i =0;i<30;i++) 
     { 
     tr = new TableRow(this); 
     for (int j =0;j<2;j++) 
     { 
      buttonNumber++; 
      final Button btn = new Button(this); 
      btn.setText("Button" + (buttonNumber)); 
      btn.setTag(buttonNumber); 
      btn.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,TableRow.LayoutParams.MATCH_PARENT,1)); 
       btn.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 

       } 
      }); 
       tr.addView(btn); 

     } 
       tableLayout.addView(tr); 
    } 
      ScrollView sv = new ScrollView(this); 
      sv.addView(tableLayout); 
      super.setContentView(sv); 
} 

如何以編程方式創建可滾動的TableLayout

+0

你能不能添加R.layout.activity_main的xml代碼?所以我可以看到是否有錯誤 –

回答

2

有幾種解決方案,主要的問題是,你在呼喚setContentView()多次,有一次還用super.

來做到這一點是刪除了滾動碼的最好辦法:

ScrollView sv = new ScrollView(this); 
sv.addView(tableLayout); 
super.setContentView(sv); 

並直接將其添加到佈局文件R.layout.activity_main,應該這樣做。

0
// try this way,hope this will help you... 

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    TableLayout tableLayout = new TableLayout(this); 
    int buttonNumber = 0; 
     for (int i =0;i<30;i++) 
     { 
      TableRow tr = new TableRow(this); 
      for (int j =0;j<2;j++) 
      { 
       buttonNumber++; 
       final Button btn = new Button(this); 
       btn.setText("Button" + (buttonNumber)); 
       btn.setTag(buttonNumber); 
       btn.setLayoutParams(new TableRow.LayoutParams(0,TableRow.LayoutParams.MATCH_PARENT,1f)); 
       btn.setOnClickListener(new View.OnClickListener() { 
        @Override 
        public void onClick(View view) { 
         Toast.makeText(MainActivity.this,String.valueOf((Integer)view.getTag()),Toast.LENGTH_SHORT).show(); 
        } 
       }); 
       tr.addView(btn); 

      } 
      tableLayout.addView(tr); 
     } 
     ScrollView sv = new ScrollView(this); 
     sv.addView(tableLayout); 
     setContentView(sv); 
} 

![enter image description here][1] 
[1]: http://i.stack.imgur.com/3qLk1.png 
+0

我試過這個,但它不工作。 :/ 我在佈局層次結構的頂部有一個'LinearLayout'。我應該刪除它還是使用另一種佈局類型進行更改以使此代碼有效? – Blast

+0

不要忘記刪除這一行「setContentView(R.layout.activity_main);」 –

+0

只是嘗試用我的代碼替換你的onCreate(),看看會發生什麼? –