【问题标题】:How do I load multiple buttons in at the same time?如何同时加载多个按钮?
【发布时间】:2016-04-09 23:36:20
【问题描述】:
我想避免回答这个问题并自己弄清楚,但是在浪费了整个下午之后,我来了。当我的应用程序启动时,我正在尝试加载 3 个按钮。我尝试使用多个 startActivities,但一次只能加载一个,我不知道为什么。我也尝试过使用 AsyncTasks,但对于我想要做的事情来说,它们似乎过于复杂。例如,其中一个按钮将打开 Google Maps 应用程序。我已经有了代码并且可以正常工作,但我想要一个按钮来执行此操作,而另外两个按钮执行不同的操作。
【问题讨论】:
标签:
android
android-layout
button
android-button
【解决方案1】:
您将不得不像这样使用 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,但您需要确保变量类别使用 If 语句执行 DoInBackround 中的正确代码!
【解决方案2】:
您可以在 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;
}
}