2012-03-21 68 views
3

我希望你能幫助我。 我想創建動態表(截圖)。我通過代碼創建它下面:Android動態創建表 - 性能不佳

TableLayout tl = (TableLayout) findViewById(R.id.main_table); 

    FOR. 1-300......... 
    TableRow tr_head = new TableRow(this); 
    tr_head.setId(10); 
    tr_head.setBackgroundColor(Color.CYAN); 
    tr_head.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT)); 
    RelativeLayout rl = new RelativeLayout(this); 
    rl.setId(20); 


    ImageButton xyz = new ImageButton(this); 
    xyz.setId(21); 
    xyz.setPadding(5, 5, 5, 5); 
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
    params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 20); 
    rl.addView(xyz,params); 

    tr_head.addView(rl); 
    tl.addView(tr_head, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT)); 
    END OF FOR....... 

通過類似的代碼,我很好地創建2種類型的項目之一爲類別(3個視圖),一個用於類別項(10個視圖)的。 然後我使用代碼波紋管分配按鈕和整個項目:

int count = tl.getChildCount(); 
    for(int i = 0; i < count; i++){ 
     TableRow v = (TableRow)tl.getChildAt(i); 

     if(v.getChildAt(0) instanceof RelativeLayout){ 
      RelativeLayout relativ = (RelativeLayout)v.getChildAt(0); 

     if(relativ.getChildCount()>5) 
      relativ.setOnClickListener(new MyClickListener()); 
        ........... 

的onclick監聽但是,當我想創建表包含300項,它需要30秒。在模擬器上渲染這個視圖。這真的很慢。所以我想問你如何渲染這個視圖。一些示例或教程將非常有用。

很多預先感謝。

I want to create this

回答

7

的Android是在內存中的許多意見很慢。要解決這個問題,我建議使用帶有自定義ListAdapter的默認Andoird ListView。

視圖是在用戶滾動列表時動態創建的,因此只有當前可見的視圖必須位於內存中。

本示例使用CursorAdapter,但您也可以使用ArrayAdapter。

private class ExtendCursorAdapter extends CursorAdapter { 

    public ExtendCursorAdapter(Context context, Cursor c) { 
     super(context, c); 
    } 

    @Override 
    public int getItemViewType(int position) { 
     if (position == 0) { //Determine if it's a category or an item 
      return 0; // category 
     } else { 
      return 1; // item 
     } 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     if (getItemViewType(position) == 0) { 
      View v; 
      if (convertView != null) 
       v = convertView; 
      else 
       v = inflater.inflate(R.id.listcategory); 
      // Set title, ... 
      return v; 
     } else{ 
      // the same for the item 
     } 
    } 
} 

額外的性能提升來自convertView的使用。滾動時,您不需要創建任何額外的視圖,因爲Android會重用那些看不見的視圖。你只需要確保重置convertView的所有數據。

+0

謝謝,它有很大的幫助。 – 2012-03-22 08:59:49

1

我碰到類似的性能問題,除了我想要做的只是以格式化的表格形式顯示文本(列自動大小等)。在這種情況下,您可能希望完全放棄TableLayout並使用類似java.util.Formatter的方法將文本轉換爲表格形狀並將其提供給單個TextView。對我來說,這導致了很大的性能提升(大約2秒即可將活動加載到幾乎即時)。

查看更多detials here