我是android新手。每当我按下后退按钮进入主要活动然后再次返回第二个活动时,我的动态按钮会自动复制。
以下是我的代码:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void food_btn_handler(View v) {
Intent intent = new Intent(this, FoodActivity.class);
startActivity(intent);
}
}
//第二次活动
public class FoodActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
loadFoodStatic();
createButtonsForFoods();
}
}
public class FoodActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
loadFoodStatic();
createButtonsForFoods();
}
private void createButtonsForFoods() {
ArrayList<Food> foods = Food.getFoods();
LinearLayout layout = (LinearLayout) findViewById(R.id.layout_food);
for (final Food f : foods) {
Button b = new Button(this);
b.setText(f.getTitle());
layout.addView(b);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(FoodActivity.this, DetailedActivity.class);
intent.putExtra("rid", f.getResid());
intent.putExtra("title", f.getTitle());
intent.putExtra("desc", f.getDescription());
intent.putExtra("moreinfo", f.getMoreinfo_url());
intent.putExtra("lat", f.getLatitude());
intent.putExtra("lng", f.getLongitude());
intent.putExtra("mark", f.getMarker());
intent.putExtra("temp", f.getTemperature());
intent.putExtra("cond", f.getCondition());
intent.putExtra("weather", f.getWeather_url());
startActivity(intent); //start activity
}
});
}
}
private void loadFoodStatic() {
Food.getFoods().add(new Food(R.drawable.pic1, "Food Title1","Food Description1","http://www.food1.com",-34.0,151.0,"Marker1",11.1,"Text1", "http://www.weather1.com"));
Food.getFoods().add(new Food(R.drawable.pic2, "Food Title2", "Food Description2","http://www.food2.com",2.222222,222.222222,"Marker2",22.2,"Text2", "http://www.weather2.com"));
Food.getFoods().add(new Food(R.drawable.pic3, "Food Title3", "Food Description3","http://www.food3.com",3.333333,333.333333,"Marker3",33.3,"Text3", "http://www.weather3.com"));
Food.getFoods().add(new Food(R.drawable.pic4, "Food Title4", "Food Description4","http://www.food4.com",4.444444,444.444444,"Marker4",44.4,"Text4", "http://www.weather4.com"));
}
}
答案 0 :(得分:0)
那是因为你每次都通过调用loadFoodStatic来添加Foods。由于ArrayList / Foods是静态/单一的,它保持在调用之间,每次创建第二个活动时,每次都会添加四个相同类型的食物。
获取fixit的一种简单方法是先在loadFoodStatic
中添加空列表检查:
if (Foods.getFoods().isEmpty) {
... //add foods here only
}