2009-04-21 42 views
14

我有一個應用程序將有5-15個按鈕,具體取決於後端可用的按鈕。如何定義合適的GridView佈局文件以包含一組按鈕,每個按鈕都有不同的文本和其他屬性?每個按鈕基本上都會將商品添加到購物車,因此除了添加到購物車的商品之外,onClick代碼將保持不變。在Android應用程序的GridView中添加按鈕數組

我該如何定義一個數組,以便可以添加可變數量的按鈕,但是仍然通過唯一ID引用每個按鈕?我看過arrays.xml的例子,但他們創建了一組預先設置的字符串。我需要一種方法來創建一個對象,而不是在佈局或數組xml文件中定義文本。 。

更新 - 增加了信息有關添加到GridView

我想要將它添加到GridView,所以調用一個UnsupportedOperationException的[addView方法(http://developer.android.com/reference/android/widget/AdapterView.html#addView(android.view.View,%20int)結果我可以做到以下幾點:

ImageButton b2 = new ImageButton(getApplicationContext()); 
b2.setBackgroundResource(R.drawable.img_3); 
android.widget.LinearLayout container = (android.widget.LinearLayout) findViewById(R.id.lay); 
container.addView(b2); 

但這並不佈局的按鈕在網格狀,我想這可以在GridView進行

回答

8

如果您使用的是的GridView,或ListView控件(ETC),併產生意見通過適配器來填充他們getView(POS,convertView,ViewGroup中),你可能會遇到的困惑(我做一旦)。

如果您決定重新使用convertView參數,則必須重置其中的所有內容。這個框架傳遞給你的是一種古老的觀點,目的是爲了節省膨脹佈局的成本。它幾乎從來沒有與位置有關,它在佈局之前。

class GridAdapter extends BaseAdapter // assigned to your GridView 
{ 
    public View getView(int position, View convertView, ViewGroup arg2) { 
     View view; 
     if (convertView==null) 
     { 
      view = getLayoutInflater().inflate(R.layout.gd_grid_cell, null); 
     } 
     else 
     { 
      // reusing this view saves inflate cost 
      // but you really have to restore everything within it to the state you want 
      view = convertView; 
     } 


     return view; 
    } 
    // other methods omitted (e.g. getCount, etc) 
} 

我認爲這代表對Android的東西,其中的概念是有點困難首先要把握一個,直到你意識到有內部可用一個顯著優化(必須是不錯的CPU一點點移動設備上)

23

在下面的代碼中,您應該將for, 的上限更改爲變量。

public class MainActivity 
     extends Activity 
     implements View.OnClickListener { 

     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 

      TableLayout layout = new TableLayout (this); 
      layout.setLayoutParams(new TableLayout.LayoutParams(4,5)); 

      layout.setPadding(1,1,1,1); 

      for (int f=0; f<=13; f++) { 
       TableRow tr = new TableRow(this); 
       for (int c=0; c<=9; c++) { 
        Button b = new Button (this); 
        b.setText(""+f+c); 
        b.setTextSize(10.0f); 
        b.setTextColor(Color.rgb(100, 200, 200)); 
        b.setOnClickListener(this); 
        tr.addView(b, 30,30); 
       } // for 
       layout.addView(tr); 
      } // for 

      super.setContentView(layout); 
     } //() 

     public void onClick(View view) { 
      ((Button) view).setText("*"); 
      ((Button) view).setEnabled(false); 
     } 
    } // class 
相關問題