【问题标题】:Android App using Eclipse - Creating a button array使用 Eclipse 的 Android 应用程序 - 创建按钮数组
【发布时间】:2015-04-07 07:52:26
【问题描述】:

我正在编写一个应用程序,它需要在一个布局中包含 86 个小方形按钮 - 最好是 6 列。我想引用按钮以根据按下的按钮显示不同的图像。我使用相对布局>滚动视图(在 XML 中),然后是 86 个单独的按钮,对它进行了艰难的编码,但这似乎是一个业余的解决方案。

谁能告诉我如何以正确的方式直接在 Java 类中编写一组具有不同 ID 的相同按钮? (顺便说一句,我已经努力在谷歌上找到这个答案,但是当我搜索这个问题的变体时,我总是会得到关于 JButtons 的教程,我认为这些教程不能在 Android 应用程序中使用)。

提前致谢。

【问题讨论】:

    标签: android arrays eclipse button


    【解决方案1】:

    这可能会有所帮助

    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;
    }
    

    }

    【讨论】:

    • 非常感谢您为回答这个问题所做的努力。我期待着尝试代码。对不起,我不能投票,我还没有 15 分。
    • 我认为您可以接受答案而不是投票。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多