Android动态创建表 - 性能不佳

Mat*_*lak 3 android tablelayout android-layout

我希望你能帮助我.我想创建动态表(截图).我是通过以下代码创建的:

    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.......  
Run Code Online (Sandbox Code Playgroud)

通过类似的代码,我很好地创建了两种类型的项目,一种用于类别(3个子视图),一种用于类别项目(10个子视图).然后我使用代码bellow为按钮和整个项目分配onclick监听器:

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());
                     ...........
Run Code Online (Sandbox Code Playgroud)

但是当我想创建包含300个项目的表时,需要30秒.在模拟器上呈现此视图.这真的很慢.所以我想问你如何渲染这个视图.一些示例或教程将非常有用.

提前谢谢了.

我想创造这个

flo*_*flo 7

Android在内存中有很多视图很慢.要解决这个问题,我建议使用默认的Andoird ListView和自定义ListAdapter.

当用户滚动列表时,将立即创建视图,因此只有当前可见的视图必须在内存中.

此示例使用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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

使用convertView可以进一步提高性能.在滚动时,您不需要创建任何其他视图,因为Android会重用那些看不见的视图.您只需确保重置convertView的所有数据.