我在我的TableLayout
中放置了60个按钮,这些按钮超出了屏幕,所以我需要滚动来显示剩余的按钮。我试过这段代码,但应用程序无效。
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 :(得分:3)
有几个解决方案,主要问题是您多次调用setContentView()
,而super.
最好的方法是删除 ScrollView代码:
ScrollView sv = new ScrollView(this);
sv.addView(tableLayout);
super.setContentView(sv);
并将其直接添加到布局文件R.layout.activity_main
中,应该这样做。
答案 1 :(得分:1)
// 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