如何同时加载多个按钮?

How do I load multiple buttons in at the same time?

我想避免回答这个问题并自己弄清楚,但是在浪费了整个下午之后,我来了。我正在尝试在我的应用程序启动时加载 3 个按钮。我尝试使用多个 startActivities,但一次只能加载一个,我不确定为什么。我也尝试过使用 AsyncTasks,但它们对于我尝试做的事情来说似乎过于复杂。例如,其中一个按钮用于打开 Google 地图应用程序。我已经有了代码并且可以正常工作,但我想要一个按钮可以执行此操作,而其他 2 个按钮可以执行不同的操作。

您将不得不像这样使用 AsyncTask:

当您单击按钮时,它将执行 AsyncTask:

public void ThirtySecVideoPlayer(){
    ThirtySecondImageButton =     (ImageButton)findViewById(R.id.ThirtySecAdImageButton);
    ThirtySecondImageButton.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    String Category = "Cleaninig";

                    String ProductUploadMethod = "ProductUploadMethod";
                    ProductUpload ProductUpload = new ProductUpload();
                    ProductUpload.execute(ProductUploadMethod, Category);
                }
            }
    );

}

然后在您的 AsyncTask 中获取参数并在 AsyncTask 中使用它:

    private class ProductUpload extends AsyncTask<String, Void, String> {

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected String doInBackground(String... params) {

        String Category = params[1];

    }

        @Override
        protected void onPostExecute (String result){

            }
        }

        @Override
        protected void onProgressUpdate (Void...values){
        }
}

可以对每个按钮使用按钮代码,然后调用同一个AsyncTask,但是需要确保变量category在DoInBackround中用If语句执行正确的代码!

您可以在 onCreate 方法中动态创建按钮。

// this is the text to put in the created button
String[] btnText = ["Button 1", "Button 2","Button 3"];
// the ID allows to determine witch button was pressed
int btnID = 0;
// in the for web be created the 3 button dynamically
for(int i = 0; i<3; i++){
final Button Btn = new Button(this);
Btn.setText(btnText[]);

//This is to give the button the size he need to wrap the text in it
LinearLayout.LayoutParams LayoutParams = new LinearLayout.LayoutParams(LayoutParams.wrap_content, LayoutParams.wrap_content);
Btn.setLayoutParams(LayoutParams);

Btn.setId(btnID);

btnID ++;

Btn.setOnClickListener(new OnClickListener(){

//This returns the Id of the clicked button
// the Id of each button was set by the  "Btn.setId(btnID);"
DetectclickedButton(Btn.getId());
    }); 
}

public void DetectclickedButton(id){

switch(id){
case 1:
// Do something in the click of the 1 button
break;
case 2:
// Do something in the click of the 2 button
break;
case 3:
// Do something in the click of the 3 button
break;
}

}