Android ListView扩展BaseAdapter在活动启动时崩溃

时间:2013-10-02 18:22:20

标签: android android-layout listview android-listview

我的MainActivity中有一个listview作为侧边栏。我想在listCreate()中将listview项颜色设置为自定义颜色。所以我使用BaseAdapter并覆盖其视图。我正在将listview设置为ArrayAdapter。 但我的应用程序在Launch上崩溃了。任何人都可以帮助我。

这是我的MainActivity代码

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

         ListView listview=(ListView)findViewById(R.id.listView);

            ArrayList<String > list = new ArrayList<String>();
            list.add("sohail");
            list.add("aziz");
            list.add("hassan");
            CustomAdapter adapter=new CustomAdapter(this,list);
            listview.setAdapter(adapter);


            listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {


                    // Show Alert




                }

            });      



         }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }



}

这是基础适配器,我在其中覆盖了我的观点。

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;

/**
 * Created by polak_000 on 10/2/13.
 */
public class CustomAdapter extends BaseAdapter{

    Context mycontext;
    ArrayList<String> contactsList;
    LayoutInflater minflater;

    public CustomAdapter(Context context, ArrayList<String> list)
    {
        this.mycontext=context;
        contactsList=list;
        minflater =LayoutInflater.from(context);

    }
@Override
    public int getCount()
{
    return contactsList.size();
}


    @Override
    public Object getItem(int position)
    {
        return contactsList.get(position);
    }


    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }


@Override
    public View getView(int position,View convertView,ViewGroup parent)
{
     if (convertView !=null)
    {
        if (position ==1)
        {
             convertView.setBackgroundColor(Color.BLUE);

        }
    }
    return  convertView;
}

}

这是我的MainActivity布局。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

     <ListView
         android:id="@+id/listView"
         android:layout_width="wrap_content"
          android:layout_height="wrap_content"
         android:layout_gravity="center"
         android:background="@android:color/holo_green_light"
         android:minHeight="50dp" 
        />

</RelativeLayout>

这是我的Catlog

  

10-02 14:11:22.125:D / AndroidRuntime(2036):关闭VM       10-02 14:11:22.125:W / dalvikvm(2036):threadid = 1:线程退出未捕获异常(组= 0x41465700)       10-02 14:11:22.215:D / dalvikvm(2036):GC_FOR_ALLOC释放80K,5%免费2940K / 3072K,暂停34ms,总计36ms       10-02 14:11:22.225:E / AndroidRuntime(2036):致命异常:主要       10-02 14:11:22.225:E / AndroidRuntime(2036):java.lang.NullPointerException       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.widget.AbsListView.obtainView(AbsListView.java:2179)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.widget.ListView.measureHeightOfChildren(ListView.java:1247)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.widget.ListView.onMeasure(ListView.java:1159)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.view.View.measure(View.java:15848)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.widget.RelativeLayout.measureChildHorizo​​ntal(RelativeLayout.java:728)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.widget.RelativeLayout.onMeasure(RelativeLayout.java:477)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.view.View.measure(View.java:15848)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.widget.FrameLayout.onMeasure(FrameLayout.java:310)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.view.View.measure(View.java:15848)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)       10-02 14:11:22.225:E / AndroidRuntime(2036):at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:302)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.view.View.measure(View.java:15848)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.widget.FrameLayout.onMeasure(FrameLayout.java:310)       10-02 14:11:22.225:E / AndroidRuntime(2036):at com.android.internal.policy.impl.PhoneWindow $ DecorView.onMeasure(PhoneWindow.java:2189)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.view.View.measure(View.java:15848)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1905)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1104)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1284)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.view.ViewRootImpl $ TraversalRunnable.run(ViewRootImpl.java:5481)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.view.Choreographer $ CallbackRecord.run(Choreographer.java:749)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.view.Choreographer.doCallbacks(Choreographer.java:562)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.view.Choreographer.doFrame(Choreographer.java:532)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.view.Choreographer $ FrameDisplayEventReceiver.run(Choreographer.java:735)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.os.Handler.handleCallback(Handler.java:730)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.os.Handler.dispatchMessage(Handler.java:92)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.os.Looper.loop(Looper.java:137)       10-02 14:11:22.225:E / AndroidRuntime(2036):在android.app.ActivityThread.main(ActivityThread.java:5103)       10-02 14:11:22.225:E / AndroidRuntime(2036):at java.lang.reflect.Method.invokeNative(Native Method)       10-02 14:11:22.225:E / AndroidRuntime(2036):at java.lang.reflect.Method.invoke(Method.java:525)       10-02 14:11:22.225:E / AndroidRuntime(2036):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:737)       10-02 14:11:22.225:E / AndroidRuntime(2036):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)       10-02 14:11:22.225:E / AndroidRuntime(2036):at dalvik.system.NativeStart.main(Native Method)

4 个答案:

答案 0 :(得分:0)

您正在从适配器中的getView函数返回null。您需要确保根据需要实现getView功能。以下是如何执行此操作的指南:http://www.androidhive.info/2011/10/android-listview-tutorial/

答案 1 :(得分:0)

更清楚的是,您需要在getView()中创建视图。

类似的东西:

        public View getView(int position, View convertView, ViewGroup parent) {
        try {
            View v = convertView;
            if (v == null) {
                v = layoutInflater.inflate(R.layout.yadda_yadda, null);
            }
        ...
        }

答案 2 :(得分:0)

// try this 

1. list item layout **list_item.xml**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:id="@+id/lnrListItem"
              android:layout_width="match_parent"
              android:padding="5dp"
              android:layout_height="wrap_content">

    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>


</LinearLayout>

2. list adapter
 public class CustomAdapter extends BaseAdapter {

        Context mycontext;
        ArrayList<String> contactsList;
        LayoutInflater minflater;

        public CustomAdapter(Context context, ArrayList<String> list)
        {
            this.mycontext=context;
            contactsList=list;
            minflater =LayoutInflater.from(context);

        }
        @Override
        public int getCount()
        {
            return contactsList.size();
        }


        @Override
        public Object getItem(int position)
        {
            return contactsList.get(position);
        }


        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }


        @Override
        public View getView(int position,View convertView,ViewGroup parent)
        {
            ViewHolder holder;
            if (convertView == null)
            {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(mycontext).inflate(R.layout.list_item,null,false);
                holder.lnrListItem = (LinearLayout) convertView.findViewById(R.id.lnrListItem);
                holder.textView = (TextView) convertView.findViewById(R.id.textview);

                convertView.setTag(holder);
            }else{
                holder = (ViewHolder)convertView.getTag();
            }
            if ((position%2)==0) 
            {
                holder.lnrListItem.setBackgroundColor(Color.CYAN); // odd item background are cyan

            }else{ 
                holder.lnrListItem.setBackgroundColor(Color.BLUE); // even item background are blue
            }
            holder.textView.setText(contactsList.get(position));

            return  convertView;
        }

        class ViewHolder{
            LinearLayout lnrListItem;
            TextView textView;
        }

    }

答案 3 :(得分:0)

如果要为列表视图创建自定义视图,则必须使用getView()LayoutInflater方法中设置自定义布局,并在getView()方法中返回该视图,然后才能使用设置该视图的颜色。否则getView将始终在convertView中重新返回null。请尝试使用getView()方法。

     @Override
    public View getView(int position,View convertView,ViewGroup parent)
    {
        ViewHolder holder;
         View m_view=convertView ;
        if (convertView == null)
        {
            holder = new ViewHolder();
            m_view= LayoutInflater.from(mycontext).inflate(R.layout.list_item,null,false);
            holder.item= (LinearLayout) m_view.findViewById(R.id.lnrListItem);
            holder.textView = (TextView) m_view.findViewById(R.id.textview);
            m_view.setTag(holder);
        }else{
            holder = (ViewHolder)m_view.getTag();
        }
        if (position==1) 
        {
            holder.item.setBackgroundColor(Color.CYAN); 
        }else{ 
            holder.item.setBackgroundColor(Color.BLUE); 
        }
        holder.textView.setText(contactsList.get(position));
        return  m_view;
    }
    class ViewHolder{
        LinearLayout item;
        TextView textView;
    }