How to get context in getView of adapter for listview

sprocket12 picture sprocket12 · Nov 16, 2013 · Viewed 9.4k times · Source

I have three questions:

  1. I am using getApplicationContext unlike all the examples I have seen which just say context. How do I get the context here? Or is the application context fine?

  2. Is there any performance penalty for me overriding the getView instead of letting it handle it by itself (I am only doing it to set a custom font)

  3. Is there anything I should be aware of while using this approach (as I am just copy and pasting without understanding what it will do if I have 250 items in my list). Any potential leaks I can cause?

My Code:

private Typeface arabicFont;
arabicFont = Typeface.createFromAsset(getAssets(), "arabicfont.ttf");

...

_arabicAdapter = new SimpleCursorAdapter(this,
                                          R.layout.book_list_item_arabic,
                                          _cursor,
                                          new String[] {"NumberArabic", "Arabic"},
                                          new int[] {R.id.txtNumber, R.id.txtBookName},
                                          CursorAdapter.NO_SELECTION)
{
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        if(convertView == null)
        {
            LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.book_list_item_arabic, parent, false);
        }

        TextView txtBookName = (TextView)convertView.findViewById(R.id.txtBookName);
        txtBookName.setTypeface(arabicFont);

        txtBookName.setText("\"العربية\"");
        return convertView;
    };
};

Answer

sky picture sky · Nov 16, 2013
public View getView(int position, View convertView, ViewGroup parent)

ViweGroup parent is certainly not null,so, parent.getContext() maybe the best way for fetch context