我想避免回答这个问题并自己解决,但在整整一个下午浪费之后,我就在这里。当我的应用程序启动时,我正在尝试加载3个按钮。我尝试使用多个startActivities,但一次只加载一个,我不知道为什么。我也尝试过使用AsyncTasks,但它们似乎过于复杂,我试图做的事情。例如,其中一个按钮将打开Google地图应用程序。我已经有了代码并且工作正常但是我想要一个按钮来执行该操作,另外两个按钮执行不同的操作。
答案 0 :(得分:0)
你将不得不像这样使用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中你得到params并将它们放在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中执行正确的代码!
答案 1 :(得分:0)
您可以在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;
}
}