如何在单独的类中使用自定义ArrayAdapter?

时间:2011-08-05 14:53:37

标签: android android-arrayadapter

我有一个扩展ArrayAdapter的内部类,以便自定义ListView。我想将这个内部类分解为一个单独的文件,以便其他类可以使用它,但是在getLayoutInflater()方面遇到了一些麻烦。

基本上,我的getView()方法不知道getLayoutInflater()是什么,即使我正在扩展ArrayAdapter。任何人都知道如何正常工作?

谢谢!

public class myDynAdap extends ArrayAdapter<String>
{
    String [] list;


   public myDynAdap (Context context, int textViewResourceId, String [] objects)
   {
       super (context, textViewResourceId, objects);
       mCtx = context;
       list = objects;
   }

    @Override
    public View getView (int position, View convertView, ViewGroup parent)
    {
        View row = convertView;

        if (row == null)
        {

            LayoutInflater inflater = getLayoutInflater ();  // <--- "The method getLayoutInflater() is undefined for the type myDynAdap"
            row = inflater.inflate (R.layout.main_listitem, parent, false);
        }

        TextView tv1 = (TextView) row.findViewById (R.id.tv_item);
        tv1.setBackgroundColor (Color.BLUE);

        // change background of 0th list element only
        if (position == 0)
            tv1.setBackgroundColor (Color.CYAN);

        return row;

    }
}

2 个答案:

答案 0 :(得分:13)

如何在传入的上下文中调用getLayoutInflater()

LayoutInflater inflater = ((Activity)context).getLayoutInflater();

答案 1 :(得分:11)

我会将编辑作为评论:

public class myDynAdap extends ArrayAdapter<String>
{
    String [] list;
    Context mContext; //ADD THIS to keep a context

   public myDynAdap (Context context, int textViewResourceId, String [] objects)
   {
       super (context, textViewResourceId, objects);
       mCtx = context; // remove this line! I don't think you need it
       this.mContext = context;
       list = objects;
   }

    @Override
    public View getView (int position, View convertView, ViewGroup parent)
    {
        View row = convertView;

        if (row == null)
        {

            LayoutInflater inflater = ((Activity)mContext).getLayoutInflater ();  // we get a reference to the activity
            row = inflater.inflate (R.layout.main_listitem, parent, false);
        }

        TextView tv1 = (TextView) row.findViewById (R.id.tv_item);
        tv1.setBackgroundColor (Color.BLUE);

        // change background of 0th list element only
        if (position == 0)
            tv1.setBackgroundColor (Color.CYAN);

        return row;

    }
}