更改listview项的textcolor时出现NullPointerException

时间:2015-04-13 12:35:30

标签: android listview nullpointerexception

覆盖getView方法以更改列表项的文本颜色 -

 aa = new ArrayAdapter(this,android.R.layout.simple_list_item_1, al) {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = super.getView(position, convertView, parent);
           TextView tv = (TextView)convertView.findViewById(android.R.id.text1);
            tv.setTextColor(Color.WHITE);
            tv.setVisibility(View.VISIBLE);
            return view;
        }
    } ;

Logcat:

-Process: com.example.sairav.app3, PID: 1470
    ***java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
            at com.example.sairav.app3.MainActivity$1.getView(MainActivity.java:38)***
            at android.widget.AbsListView.obtainView(AbsListView.java:2344)
            at android.widget.ListView.makeAndAddView(ListView.java:1864)
            at android.widget.ListView.fillDown(ListView.java:698)
            at android.widget.ListView.fillFromTop(ListView.java:759)
            at android.widget.ListView.layoutChildren(ListView.java:1673)
            at android.widget.AbsListView.onLayout(AbsListView.java:2148)
            at android.view.View.layout(View.java:15596)
            at android.view.ViewGroup.layout(ViewGroup.java:4966)
            at android.widget.AbsoluteLayout.onLayout(AbsoluteLayout.java:123)
            at android.view.View.layout(View.java:15596)
            at android.view.ViewGroup.layout(ViewGroup.java:4966)
            at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
            at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
            at android.view.View.layout(View.java:15596)
            at android.view.ViewGroup.layout(ViewGroup.java:4966)

2 个答案:

答案 0 :(得分:1)

第一次调用getView时,convertView为null。调用超级并将其返回值分配给视图,使convertView未初始化,从而导致崩溃。

 convertView = super.getView(position, convertView, parent);
 TextView tv = (TextView)convertView.findViewById(android.R.id.text1);
 tv.setTextColor(Color.WHITE);
 tv.setVisibility(View.VISIBLE);
 return convertView;

编辑:

android.R.layout.simple_list_item_1只包含TextView,因此要使用findViewById,您可以转换返回值super.getView

convertView = super.getView(position, convertView, parent);
((TextView)convertView).setTextColor(Color.WHITE);
((TextView)convertView).setVisibility(View.VISIBLE);
 return convertView;

答案 1 :(得分:0)

aa = new ArrayAdapter(this,android.R.layout.simple_list_item_1, al) {
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);

//使用view而不是convertview

       TextView tv = (TextView)view.findViewById(android.R.id.text1);
        tv.setTextColor(Color.WHITE);
        tv.setVisibility(View.VISIBLE);
        return view;
    }
} ;