【问题标题】:AsyncTask LayoutInflater InflateException on EditTextEditText 上的 AsyncTask LayoutInflater InflateException
【发布时间】:2013-01-10 11:55:27
【问题描述】:

我基本上有代码

new AsyncTask<Integer, Void, View>() {
@Override
protected View doInBackground(Integer... tabIds) {
    return mInflater.inflate(R.layout.layout_name, null);
}
@Override
protected void onPostExecute(View result) {
    super.onPostExecute(result);
            root_layout.addView(result);
}
}.execute(tabId);

layout_name.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@android:color/white" >


<EditText
    android:id="@+id/text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="text" />

<Button
    android:id="@+id/do_stuff"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

</LinearLayout>

我得到InflateException: Binary XML file line #x: Error inflating class &lt;unknown&gt;。 如果我删除EditText,它可以在没有problems 的情况下使用。

我找不到原因(花了 2 小时)。

有人知道这是什么原因吗? 并希望有一个解决方案

【问题讨论】:

  • 在工作线程上膨胀视图不是最好的主意,为什么需要这样做?
  • 因为加载所有内容都需要一段时间。即使我从服务器得到了我需要的东西
  • 无论如何,这行不通,因为Android UI框架不是线程安全的。
  • 找到这个stackoverflow.com/questions/6691311/… 猜想我不得不限制显示的数量

标签: android android-asynctask android-edittext layout-inflater inflate-exception


【解决方案1】:

例如,不要使用 AsynTask,而是使用 AsyncLayoutInflater:

  MyClass extends Fragment implements  AsyncLayoutInflater.OnInflateFinishedListener {

        @Override
        public void onCreate(Bundle savedInstanceState) {
         new AsyncLayoutInflater(context).inflate(childViewId, parent, this);
         //show progress..
        }
        @Override
        public void onInflateFinished(View view, int resid, ViewGroup parent){
            if (view != null) {
             //You have inflated view to use in UI Thread.
            }
        }
    }

除此之外,它还有一些陷阱: AsyncLayoutInflater 类还将处理无法异步膨胀的视图的情况。此类视图类没有处理程序实现,如果您尝试在 AsyncTask 或 Thread 类中对它们进行膨胀(如您的情况),则会引发异常。例如 EditText 只能在 UI 线程中膨胀。将要求 looper.loop();称呼。 AsyncLayoutInflater 将在 UI 线程中对此类视图进行膨胀并异步休息。

最终你不能在单独的线程中膨胀 EditText。这只是您要实现的目标的解决方法。 此外,您可以尝试同样的 HandlerThread,但效果不大。

【讨论】:

    【解决方案2】:

    两个都改

     android:layout_width="match_parent"
    

     android:layout_width="wrap_content"
    

    它可能会帮助你。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-07
      • 1970-01-01
      • 2018-06-05
      相关资源
      最近更新 更多