自定义ArrayAdapter初始化item项

最近 项目中需要在初始化界面的时候使listview中的特定item项变为灰色状态,而用listview.getChildAt(int index),初始化界面会报空指针异常。最后解决方法是重新写arrayadapter,在getview方法中设置属性,代码如下

1.写一个MyAdapter继承ArrayAdapter类,重写getview方法

class myAdapter extends ArrayAdapter{
        CheckedTextView checkedTextView;
        int resource;
        LayoutInflater mInflater;
       
        boolean b;
        public myAdapter(Context context, int textViewResourceId) {
            super(context, textViewResourceId);
            // TODO Auto-generated constructor stub
            this.resource=textViewResourceId;
            mInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            b=totalSwitch.isChecked();
            Log.i("debug", "---------"+b);
        }
       

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return item.length;
        }


        @Override
        public String getItem(int position) {
            // TODO Auto-generated method stub
            return item[position];
        }


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


        @Override
        public int getPosition(String item) {
            // TODO Auto-generated method stub
            return super.getPosition(item);
        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            if (convertView == null) {
                checkedTextView =(CheckedTextView) mInflater.inflate(resource, parent, false);
            } else {
                checkedTextView = (CheckedTextView)convertView;
            }
            checkedTextView.setText(item[position]);
            checkedTextView.setEnabled(b);//设置不可用状态
          
            return checkedTextView;
        }
       
       
    }

2.使用自己定义的adapter

   list.setAdapter(new myAdapter(getApplicationContext(), android.R.layout.simple_list_item_single_choice));

OK,搞定初始界面问题

 

你可能感兴趣的:(自定义ArrayAdapter初始化item项)