您好我想点击一个按钮,每次点击它时都会向表格行添加一个新按钮。在行中添加了3个按钮后,我想动态创建一个新的表行并为其添加一个新按钮。
我知道如果单击按钮,如何在tableLayout中添加带按钮的行。我不知道每次点击时如何修改表格行,所以我可以添加一个额外的按钮。
任何建议都会非常有帮助和赞赏。
以下是我的代码,但这并不完美
public class DynamicTableView extends Activity {
TableLayout mTlayout;
String[] mTextofButton = { "Dipak", "E", "I", "J", "L",
"M", "G", "R", "N", "T", "H", "P",
"K", "Y", "V" };
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTlayout = (TableLayout) findViewById(R.id.mTlayout);
TableRow tr=new TableRow(this);
for(int i=0;i<mTextofButton.length;i++){
Button btn=new Button(this);
btn.setText(mTextofButton[i]);
tr.addView(btn);
}
mTlayout.addView(tr);
}
}
提前致谢。
答案 0 :(得分:10)
使用以下代码: -
public class DynamicButtonsActivity extends Activity {
TableLayout mTlayout;
TableRow tr;
String[] mTextofButton = { "D", "E", "I", "J", "L", "M", "G", "R", "N",
"T", "H", "P", "K", "Y", "V" };
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTlayout = (TableLayout) findViewById(R.id.mTlayout);
int i = 0;
while (i < mTextofButton.length) {
if (i % 3 == 0) {
tr = new TableRow(this);
mTlayout.addView(tr);
}
Button btn = new Button(this);
btn.setText(mTextofButton[i]);
btn.setId(i);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("v.getid is:- " + v.getId());
}
});
tr.addView(btn);
i++;
}
}
}
答案 1 :(得分:4)
int i=0;
while(i<mTextofButton.length){
if(i%3==0){
TableRow tr=new TableRow(this);
mTlayout.addView(tr);
}
Button btn=new Button(this);
btn.setText(mTextofButton[i]);
tr.addView(btn);
i++;
}
答案 2 :(得分:1)
他们会Button
的{{1}},说onClick()
并执行以下操作:
addNewButton()
但要注意你的public void addNewButton(View b)
{
for(int i=0; i<mTextofButton.length; i+=3){
TableRow tr=new TableRow(this);
Button btnOne=new Button(this);
btnOne.setText(mTextofButton[i]);
tr.addView(btnOne);
Button btnTwo =new Button(this);
btnTwo.setText(mTextofButton[i+1]);
tr.addView(btnTwo);
Button btnThree =new Button(this);
btnThree.setText(mTextofButton[i+2]);
tr.addView(btnThree);
mTlayout.addView(tr);
}
}
,意味着它应该被3分割,否则你会得到mTextofButton.length
。更好的方法是使用ArrayIndexOutOfBondException