2015-02-07 79 views
0

我正在编写一个应用程序,它需要一个布局中的86个小方形按钮 - 最好是6列。我想参考按钮来显示不同的图像,这取决于按下的按钮。我使用相对布局>滚动视图(XML),然后使用86个单独的按钮进行编码,但它看起来像是一个业余解决方案。使用Eclipse的Android应用程序 - 创建按钮阵列

有人可以告诉我如何用正确的方式直接在Java类中用不同的id编码一个相同按钮的数组吗? (顺便说一下,我已经尽力找到谷歌这个答案,但是当我搜索这个问题的变体时,我总是得到关于JButton的教程,我相信这些教程不能用在android应用程序中)。

在此先感谢。

回答

0

这可能有助于

public class Test extends Activity{ 

List<Button> buttonList; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    buttonList=new ArrayList<Button>(); 
    Button doneButton=(Button)findViewById(R.id.your_final_button); 
    ScrollView view=(ScrollView)findViewById(R.id.your_scroll_view); 
    view.addView(tableLayout(20));//20 rows 
    doneButton.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      for(Button b : buttonList){ 
       b.getText();//whatever you wanna do 
      } 

     } 
    }); 

} 
private TableLayout tableLayout(int count) { 
    TableLayout tableLayout = new TableLayout(this); 
    tableLayout.setStretchAllColumns(true); 
    tableLayout.setBackgroundColor(Color.WHITE); 
    int noOfRows = count ; 
    for (int i = 0; i < (noOfRows+1); i++) { 
     int rowId = 3 * i; 
     tableLayout.addView(createOneFullRow(rowId)); 
    } 

    return tableLayout; 
} 

private TableRow createOneFullRow(int rowId) { 
    TableRow tableRow = new TableRow(this); 
    tableRow.setPadding(0, 10, 0, 0); 
    //6 columns 
    tableRow.addView(createButton("text1")); 
    tableRow.addView(createButton("text2")); 
    tableRow.addView(createButton("text3")); 
    tableRow.addView(createButton("text4")); 
    tableRow.addView(createButton("text5")); 
    tableRow.addView(createButton("text6")); 

    return tableRow; 
} 
private View createButton(String string) { 
    // TODO Auto-generated method stub 
    Button button = new Button(this); 

    button.setText(string); 
    buttonList.add(button); 

    return button; 
} 

}

+0

谢谢你这么多努力为您回答这个问题。我期待着尝试代码。我很抱歉,我不能投票,我还没有15分。 – cd141186 2015-02-07 22:37:28

+0

我认为你可以接受答案而不是投票。 – 2015-02-09 05:58:23

+0

太棒了。我会看看如果我可以得到它的工作。 – cd141186 2015-02-09 13:46:21