我遇到了这个问题,因为我知道这有点合乎逻辑,但我无法解决。 这是问题
我从Web服务获得了n个值,例如5个值,并且基于此我在运行时创建了n个按钮。然后我将它们添加到我已放入xml的线性布局中。
以下是我的代码。
public void makeDynamicView() {
// ArrayList<RestaurantCatagory> menu = adapter.menuList;
// final RestaurantCatagory restaurantCategory;
button_layout = (LinearLayout) findViewById(R.id.tab_button_bar);
for (int i = 0; i < ResturantAdapter.menuList.size(); i++) {
Log.e("in the foodlist class", "menulist size is"
+ ResturantAdapter.menuList);
// Button myButton[] = new Button[i];
final RestaurantCatagory restaurantCategory = ResturantAdapter.menuList.get(i);
final Button button = new Button(this);
ImageView seperatorImage = new ImageView(this);
button.setTypeface(typeface);
button.setTextSize(20);
//Log.e("in the foodlist class", "i value is" + i);
button.setId(i);
if (i == 0) {
// button.setBackgroundResource(R.drawable.tab_leftside);
button.setBackgroundResource(R.drawable.tab_leftside_hover);
// Log.e("in the foodlist class", "in the left loop");
// button = myButton[i];
}
else if (i == ResturantAdapter.menuList.size() - 1) {
button.setBackgroundResource(R.drawable.tab_rightside);
//Log.e("in the foodlist class", "in the right loop");
}
else {
//Log.e("in the foodlist class", "in the center loop");
button.setBackgroundResource(R.drawable.tab_center);
}
seperatorImage.setBackgroundResource(R.drawable.divider);
//Log.e("in the foodlist class", "cattegory name is"
// + restaurantCategory.getCatName());
button.setText(restaurantCategory.getCatName());
// button_layout.addView(button);
button_layout.addView(button, new LayoutParams(
150, 40));
// button_layout.addView(button[i],new
// LayoutParams(LayoutParams.WRAP_CONTENT,
// LayoutParams.WRAP_CONTENT));
button_layout.addView(seperatorImage, new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
button.setOnClickListener(new OnClickListener() {
// int messageColor;
@Override
public void onClick(View v) {
int catagoryID = restaurantCategory.getCatdID();
String url = Urls.RESTAURANT_MENU_LIST+"restaurant_id="+restaurantID+"&catagory_id="+catagoryID;
Log.e("url to be hit is", "url="
+ url);
new FoodAsyncTask(FoodMenuActivity.this, url).execute();
//button_layout = (LinearLayout) findViewById(R.id.tab_button_bar);
//Toast.makeText(getApplicationContext(), "in the loop", 2000).show();
button_layout.removeAllViews();
makeNewViews(v);
}
});
}
}
现在从代码中你可以看到我在for循环中填充按钮,然后在我的线性布局中添加它们。现在,当我在for循环中添加它们时,我的视图添加了确切的次数,作为父视图中的按钮数量,e,以xml为单位。并且由于这个原因,我将不得不按下按钮n次以进行上一次活动。 请建议我如何使用代码,以便所有按钮在我的线性布局中只添加一次。