【问题标题】:Logcat error: "addView(View, LayoutParams) is not supported in AdapterView" in a ListViewLogcat 错误:ListView 中的“AdapterView 中不支持 addView(View, LayoutParams)”
【发布时间】:2011-01-01 23:04:38
【问题描述】:

我正在为 Android 做一个应用程序,我需要的是它显示 SD 卡中所有文件和目录的列表,并且它必须能够在不同的目录中移动。我找到了a good tutorial in anddev。我修改了一些东西,使应用程序在 SD 卡中移动,而不是在 Android 根目录中,但其余部分基本相同。

这是我的活动 xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@id/android:list"       
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</ListView>

这是 Activity 的代码:

import hackreatorz.cifrador.R;
import java.io.File;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ArchivosSD extends ListActivity {

    private ArrayList<String> directoryEntries = new ArrayList<String>();
    private File currentDirectory = new File("/sdcard/");

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        browseToSD();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    private void browseToSD() {
        browseTo(new File("/sdcard/"));
    }

    private void upOneLevel() {
         if(this.currentDirectory.getParent() != null)
             this.browseTo(this.currentDirectory.getParentFile());
    }

    private void browseTo(final File directory) {
        if (directory.isDirectory()) {
                this.currentDirectory = directory;
                fill(directory.listFiles());
        } else {
                Toast.makeText(ArchivosSD.this, this.directoryEntries.get(this.getSelectedItemPosition()), Toast.LENGTH_SHORT).show();
                }
    }

    private void fill(File[] files) {
        this.directoryEntries.clear();
        this.directoryEntries.add(getString(R.string.current_dir));
        if(this.currentDirectory.getParent() != null)
            this.directoryEntries.add(getString(R.string.up_one_level));
            int currentPathStringLength = (int) this.currentDirectory.getAbsoluteFile().length();
            for (File file : files) {
                this.directoryEntries.add(file.getAbsolutePath().substring(currentPathStringLength));           
            }
        setListAdapter(new ArrayAdapter<String>(this, R.layout.archivos_sd, this.directoryEntries));
    }   

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        int selectionRowID = (int) this.getSelectedItemPosition();
        String selectedFileString = this.directoryEntries.get(selectionRowID);
        if (selectedFileString.equals(".")) {
            this.browseToSD();
        } else if(selectedFileString.equals("..")) {
            this.upOneLevel();
        } else {
            File clickedFile = null;
            clickedFile = new File(this.currentDirectory.getAbsolutePath() + this.directoryEntries.get(selectionRowID));
            if(clickedFile != null)
                this.browseTo(clickedFile);
            }
    }
}

我在 Eclipse 中没有收到任何错误,但在手机上运行应用程序时出现强制关闭,当我查看 Logcat 时,我看到以下内容:

01-01 23:30:29.858: ERROR/AndroidRuntime(14911): FATAL EXCEPTION: main 01-01 23:30:29.858: 错误/AndroidRuntime(14911): java.lang.UnsupportedOperationException: addView(View, LayoutParams) AdapterView 不支持

我不知道该怎么做,我在 Google 中查找过,但没有找到任何东西,我在 stackoverflow 上也做了同样的事情。这是我在 Java 和 Android 中的第一个应用程序,所以我是一个真正的 n00b,如果答案在那里,我不明白,所以如果你能解释我应该做什么来修复这个错误以及为什么,我将不胜感激。

提前感谢您提供的一切。

【问题讨论】:

    标签: android listview adapter android-adapterview


    【解决方案1】:

    对于遇到此问题并在ArrayAdaptergetView 中扩展布局的其他人,请将parent 参数设置为null,如view = inflater.inflate(R.layout.mylayout, null); 中一样

    【讨论】:

    • 很棒的评论!我为此挣扎了好几个小时……有人知道为什么吗?
    • 这也解决了我的问题。我认为这与需要布局参数的 listview 父级有关。
    • 这绝对是一个错误的答案,你应该总是在膨胀时传递一个父视图组,有一些例外,但这不是其中之一,有关更多信息,请参见此处:doubleencore.com/2013/05/layout-inflation-as-intended。人们遇到的普遍问题是 xml 配置错误。
    • 这是一个解决方案,但你用错了:)。将 parent 传递为 null 会在没有适当容器的情况下实例化对象,并且应该稍后重新调整,这既费时又会影响您的性能。相反,使用 inflate (R.layout.mylayout, parent,false)。所以你说的是使用父级进行测量但不要附加到它,因为它将在返回视图后完成
    【解决方案2】:

    经验法则

    在膨胀视图时,您应该始终尝试传入父级,否则框架将无法识别用于该膨胀视图的布局参数。

    处理异常的正确方法是通过false作为第三个参数,这个标志表示是否应该直接将视图添加到是否通过容器。

    在适配器的情况下,适配器本身会在您从getview 方法返回视图后添加视图:

    view = inflater.inflate(R.layout.mylayout, parent, **false**);
    

    BaseAdapter 示例,来自just-for-us DevBytes

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View result = convertView;
        if (result == null) {
            result = mInflater.inflate(R.layout.grid_item, parent, false);
        }
    
        // Try to get view cache or create a new one if needed
        ViewCache viewCache = (ViewCache) result.getTag();
        if (viewCache == null) {
            viewCache = new ViewCache(result);
            result.setTag(viewCache);
        }
    
        // Fetch item
        Coupon coupon = getItem(position);
    
        // Bind the data
        viewCache.mTitleView.setText(coupon.mTitle);
        viewCache.mSubtitleView.setText(coupon.mSubtitle);
        viewCache.mImageView.setImageURI(coupon.mImageUri);
    
        return result;
    }
    

    CursorAdapter 示例:

    @Override
    public View newView(final Context context, final Cursor cursor, final ViewGroup root)          {
        return mInflater.inflate(R.layout.list_item_ticket, root, false);
    }
    

    更多关于视图膨胀的信息可以在article找到。

    【讨论】:

    • ViewCache 不作为一个类存在,而且我在很多论坛都找到了相同的代码,是复制粘贴吗?你有没有试过让它编译?
    【解决方案3】:

    在创建像您这样的 ArrayAdapter 时,ArrayAdapter 需要一个布局资源只包含一个 TextView。 尝试更改您的 ArrayAdapter 创建:

    setListAdapter(new ArrayAdapter<String>(this, 
          android.R.layout.simple_list_item_1, 
          this.directoryEntries));
    

    看看它是否有效。

    【讨论】:

    • 太棒了!非常感谢!我对您的回答有疑问,“android.R.layout.simple_list_item_1”包括什么?如果我使用“android.R.layout.simple_list_item_1”,我对 Listview 和 textview 所做的布局会发生什么?非常感谢!
    • 当您创建一个 ArrayAdapter 时,您会传递一个布局资源以用于每个列表项(而 ArrayAdapter 只需要一个 TextView)。设置“屏幕”的布局文件将在 onCreate 中使用,带有 setContentView(R.layout.your_layout)。
    • 如果该 xml 文件具有以下代码,我能否将“android.R.layout.simple_list_item_1”更改为 R.layout.myxml?:
    • 我不确定我是否明白。因此,在 OnCreate 中应该有 setContentView(R.layout.my_layout 只有一个 TextView 然后在适配器上我必须传递布局资源 android.R.layout.simple_list_item_1?
    • 您之前的评论是对的,您可以将自己的布局传递给 ArrayAdapter 构造函数。但是您的第二条评论是错误的,在 setContentView 上,您传递了整个活动的初始布局(标题、按钮、ListView 等)。虽然在 ListActivities 上已经有了 ListView 的默认布局。
    【解决方案4】:

    我的问题是:我在 arrayAdapter 中覆盖了 getView。然后当我放大视图时,我忘记将 attach to root 设置为 false,这导致了这个异常。

    必须这样做:

    convertView = LayoutInflater.from(getContext()).inflate(R.layout.market_search_product_view, parent,false);
    

    问题解决后!

    https://stacklearn.ir

    【讨论】:

      【解决方案5】:

      从 XML 文件中的 ListView 中删除 TextView

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-14
        • 2012-05-02
        • 1970-01-01
        • 1970-01-01
        • 2012-06-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多