gpt4 book ai didi

java - 有没有办法在Android上并行创建 View ?

转载 作者:行者123 更新时间:2023-12-02 09:03:01 25 4
gpt4 key购买 nike

我正在开发一个应用程序,在其执行的某个部分,用户将能够以图形的形式查看文本文件中的数据。但是,由于文本文件可以有多个列(并且旨在为每个列创建一个图表),因此仅使用 UI 线程可能会阻塞应用程序一段时间。所以我的问题是:Android 上是否有任何类允许我并行创建这些图形(View),并在所有图形准备好后将它们添加到父布局中?

我的第一个想法是使用 ExecutorService 如下(为了简单起见,使用 TextView 而不是 GraphView,来 self 在项目中使用的库):

  • createTextsInParallel 实现:
public void createTextsInParallel(){
ExecutorService executor = (ExecutorService) Executors.newFixedThreadPool(3);

List<TextBuilderTask> taskList = new ArrayList<>();
for (int i = 0; i < arrays.size(); i++){ // arrays is an ArrayList<ArrayList<Double>>
if (arrays.get(i) == null) continue;
taskList.add(new TextBuilderTask(this, arrays.get(i), i));
}

List<Future<TextView>> futureList = null;
try {
futureList = executor.invokeAll(taskList);

} catch (InterruptedException e){
e.printStackTrace();
}

executor.shutdown();

if (futureList != null){
for (int i = 0; i < futureList.size(); i++){
TextView tv = futureList.get(i).get();
parentLayout.addView(tv); // parentLayout is a LinearLayout
}
}
}
  • TextBuilderTask 实现:
class TextBuilderTask implements Callable<TextView> {
protected MyActivity activity;
protected ArrayList<Double> array;
protected int pos;

public TextBuilderTask(MyActivity activity, ArrayList<Double> array, int pos){
this.activity = activity;
this.array = array;
this.pos = pos;
}

@Override
public TextView call() throws Exception {
TextView tv = new TextView(this.activity);
tv.setText(String.format("%d: %s", this.pos, Arrays.toString(this.array)));
return tv;
}
}

但是上面抛出了以下异常:

Caused by: java.lang.RuntimeException: Can't create handler inside thread Thread[pool-1-thread-1,5,main] that has not called Looper.prepare()

那么我应该在哪里调用Looper.prepare()?基于之前的SO问题,每当我调用Looper.prepare()时,我应该调用Looper.loop()Looper.quit()某处也有。但由于我使用 ExecutorService 来完成这项工作,我不确定应该在哪里调用它们。如有任何帮助,我们将不胜感激。

最佳答案

我无法运行你的代码,因为它包含一些错误并且不能立即编译,但我怀疑问题在于你在辅助线程中实例化 View (这是调用 call())。我知道这正是您的目标,但这可能不是一个好主意,因为它取决于您正在实例化的 View 的实现。例如,如果它们的构造函数创建一些处理程序,它们将要求准备循环器。您可以尝试在 call() 方法中执行此操作,但事实上,此时它们的处理程序可能正在意外线程上运行。

它似乎也是特定于平台的,因此它可能适用于某些手机,而不适用于其他手机,具体取决于该特定 View 的实际实现。我建议在这里查看这篇文章,也许您可​​以尝试遵循其中一些建议(例如使用 AsyncLayoutInflater): Inflate a view in a background thread

关于java - 有没有办法在Android上并行创建 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60030939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com