How to get context in getView of adapter for listview
-
21-12-2019 - |
Question
I have three questions:
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?
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)
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;
};
};
Solution
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
OTHER TIPS
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?
You are passing this
to your constructor here
_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)
which would be your Context
so you should have a variable in your Adapter
that is of type Context
which you assign in your constructor.
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)
Not that I'm aware of but if it is just a font then you could assign this in a style
for the TextView
that you use for your ListView
items.
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?
Yes, you should be aware that copy/paste code without understanding it is always trouble. Go through line by line and make sure you understand what everything is doing.