我正在构建一个数独游戏,但我在这里遇到了性能问题。
我有这个网格,我想用 81 个单元格填充网格。 这些单元格是自定义 View ,因为我希望它们有 10 个标签和一些函数 blabla。
我现在的问题是我必须创建 81 个 subview (没问题),用我的模型中的数据填充它们(没问题),然后将整个网格添加到我的布局(biiiig 问题)。
整个构建是在这样的异步任务中完成的:
protected Void doInBackground(Void... params) {
Model.Cell[][] sudoku = Controller.getInstance().startNewGame(); //call model for a new game
ArrayList<TableRow> rows = ga.generateTable(sudoku); //generate the table
tl = new TableLayout(ga); //create tablelayout
//add the rows to the layout
for (TableRow v : rows) {
tl.addView(v);
}
return null;
}
完成后:
protected void onPostExecute(Void result) {
super.onPostExecute(result);
RelativeLayout rl = (RelativeLayout) ga.findViewById(R.id.gridContainer); //get the container
//create layout rules
android.widget.RelativeLayout.LayoutParams params = new android.widget.RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_HORIZONTAL);
//add the table to the container with the layout
rl.addView(tl, params); //this is slow as hell.
//stop loading indicator
this.loading.dismiss();
}
我不介意暂时获得加载栏。但是我的加载栏停止了,因为 rl.addView(tl, params) 太慢了。
有人可以帮助我如何使我的主线程保持快速吗?
最佳答案
我认为问题在于您正在向 View 中添加大量 TableLayout。它必须通过每个单元格的 measure
和 layout
以使其适合布局。
您可以做的一件事是在 onPreExecute
中创建单个 TableLayout
并将其添加到布局中。然后,您可以创建每个面板并将其添加到 TableLayout
中。这将在单个单元格上完成所有布局工作,而不是在一个大块中完成所有布局工作。
我想指出的可能相关也可能不相关的一件事是您在后台线程中创建了一个 TableLayout
。 Inflating Views in a background thread has been known to cause problems on some devices.你没有膨胀。您正在创建一个 View
对象,所以它很可能 不一样,但我想没有保证。因此,我可能会使用后台线程来创建和收集每个单元格的数据,然后在 onProgressUpdate
中创建并添加单元格,它在 UI 线程上运行。
关于android - 自定义 View 很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12585772/