【问题标题】:Problem when One listview uses different Layouts一个列表视图使用不同布局时的问题
【发布时间】:2013-10-14 21:42:08
【问题描述】:

我在尝试根据一个列表视图上的查询扩展不同类型的布局时遇到问题。我正在使用这种类型,以便可以将整个 Activity 包装到一个 listView 中,它看起来像一个可滚动的网页。我更喜欢 AdapterView 类型的布局,因为我必须在两者之间放置一些巨大的表格,如果我使用其他类型的布局进行膨胀,可能会延迟加载。

我在 CursorAdapter 类中使用了类似的东西

public View newView(Context arg0, Cursor cur, ViewGroup parent) {
            final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            View view = null;
            int viewIndex = cur.getInt(1);
            if (viewIndex == 0)
               view = inflater.inflate(com.sayka.ordergadget.R.layout.takheader, parent, false);
            else if (viewIndex == 1)  {
                view = inflater.inflate(com.sayka.ordergadget.R.layout.activity_order_items2, parent, false);
                if (isNew) passFocus2Name((AutoCompleteTextView)view.findViewById(R.id.tak_itemName));
            }
            else if (viewIndex == 2)
                view = inflater.inflate(com.sayka.ordergadget.R.layout.tak_footer, parent, false);
            return view;
        }

问题是 AdapterView 似乎只膨胀了一次视图。所以当我查询游标时,空指针异常被 BindView 方法捕获。 Cauz 这次适配器尝试从 Layout2 访问 Layout1 项目,因为之前 Layout2 在 Layout1 的位置存在。如果遇到这样的错误,我会尝试更改视图本身

public void bindView(View view, Context cont, Cursor cur) {
if (cur.getInt(1) == 2) {
                    TextView totItems_L, totItems_C, totItems, totQty_L, totQty_C, totQty, totAmt_L, totAmt_C, totAmt;
                    TextView testC;

                    try {
                        testC = (TextView)view.findViewById(com.sayka.ordergadget.R.id.totalItemsL);
                        testC.setText("Salim");
                    } catch (NullPointerException exp) {
                        ViewGroup parent = (ViewGroup)view.getParent();
                        final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
                        view = inflater.inflate(com.sayka.ordergadget.R.layout.tak_footer, parent, false);
                }

我正在尝试重新分配视图。但它不起作用。任何帮助,将不胜感激。我是安卓新手。

【问题讨论】:

    标签: android android-listview nullpointerexception


    【解决方案1】:

    您的适配器中的getItemViewType() 正是为此目的而创建的。

    @Override
    public int getViewTypeCount(){
        return NUMBER_OF_TYPES;
    }
    
    
    @Override
    public int getItemViewType(int pos){
        // get your item type
        // return type int, must be less than NUMBER_OF_TYPES
    }
    

    http://developer.android.com/reference/android/widget/Adapter.html#getItemViewType(int)

    【讨论】:

    • 重新查询时引发异常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多