2014-01-14 149 views
4

我創建了2個coloumns的gridview。 我需要在運行時在每列中動態創建一個按鈕和一個textview。 我無法編寫它的baseadapter類。 我應該如何誇大我的看法在gridview。如何以編程方式將視圖添加到gridview,android?

這是我的適配器類

public class Adapter extends BaseAdapter { 
    Context con; 
    Integer[] m; 

    public Adapter(Context c) { 
     con = c; 
    } 

    public Adapter(Integer[] x) { 
     m = x; 
    } 

    @Override 
    public int getCount() { 
     // TODO Auto-generated method stub 
     return m.length; 
    } 

    @Override 
    public Object getItem(int position) { 
     // TODO Auto-generated method stub 
     return m[position]; 
    } 

    @Override 
    public long getItemId(int position) { 
     // TODO Auto-generated method stub 
     return 0; 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     // TODO Auto-generated method stub 
     Button btn = new Button(con); 
     TextView textview =new TextView(con); 


     return null; 
    } 

} 
+1

爲什麼不能有一個xml佈局按鈕和文本infalte佈局並在getView – Raghunandan

+0

中更新ui在視圖中添加您在getView()中膨脹的按鈕和textview。 –

+0

@Raghunandan不能使用xml – WISHY

回答

7

你可以這樣做:

public class Adapter extends BaseAdapter { 
Context con; 
Integer[] m; 

public Adapter(Context c, Integer[] x) { 
    con = c; 
    m = x; 
} 



@Override 
public int getCount() { 
    // TODO Auto-generated method stub 
    return m.length; 
} 

@Override 
public Object getItem(int position) { 
    // TODO Auto-generated method stub 
    return m[position]; 
} 

@Override 
public long getItemId(int position) { 
    // TODO Auto-generated method stub 
    return 0; 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    LinearLayout layout = new LinearLayout(mContext); 
    layout.setLayoutParams(new GridView.LayoutParams(
      android.view.ViewGroup.LayoutParams.FILL_PARENT, 
      android.view.ViewGroup.LayoutParams.FILL_PARENT)); 
    layout.setOrientation(LinearLayout.HORIZONTAL); 

    Button btn = new Button(mContext); 
    btn.setLayoutParams(new LinearLayout.LayoutParams(
      android.view.ViewGroup.LayoutParams.WRAP_CONTENT, 
      android.view.ViewGroup.LayoutParams.WRAP_CONTENT)); 
    btn.setText("Btn " + position); 

    TextView textview = new TextView(mContext); 
    textview.setLayoutParams(new LinearLayout.LayoutParams(
      android.view.ViewGroup.LayoutParams.WRAP_CONTENT, 
      android.view.ViewGroup.LayoutParams.WRAP_CONTENT)); 
    textview.setText("TV " + position); 
    textview.setTextColor(Color.RED); 

    layout.addView(textview); 
    layout.addView(btn); 

    return layout; 
} 

} 

將工作:)

相關問題