I have a custom listview that displays approx. 114 items, and in it I have a TextView (use as a link) so when the user clicks on the link it takes to another activity something like “read more…” kinda of link within a listview.
my question: Is the code below is optimized? in other words following the best practices? or horrible? since I will be creating around 114 activities, layouts and adding in AndroidManifest.xml
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_row_custom_listview, null);
final TextView artist = (TextView)vi.findViewById(R.id.artist);
TextView link = (TextView)vi.findViewById(R.id.txtLink);
link.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (position == 0) {
Intent intent_01 = new Intent(v.getContext(), more_01_Activity.class);
v.getContext().startActivity(intent_01);
}
if (position == 1) {
Intent intent_02 = new Intent(v.getContext(), more_02_Activity.class);
v.getContext().startActivity(intent_02);
}
if (position == 3) {
Intent intent_03 = new Intent(v.getContext(), more_03_Activity.class);
v.getContext().startActivity(intent_03);
}
...........
............
...........
//goes upto 114
}
});
return vi;
}
is a very expensive call which should be avoided as much as possible, fortunately there’s this idea of a
ViewHolder, which you can use like this:create an inner class called ViewHolder
then inside your getView,
After that, it’s just a matter of using the holder items instead of the TextView
linkvariable.so
Also, instead of creating hundreds of different activities, you can code a more flexible activity that can adjust itself depending on the information it receives from the intent that launches it. example:
inside onClickListener,
To get the position in the receiving Activity, do
and work on that information to display what you’re trying to accomplish with different activities.
If you have more questions, feel free to ask in the comments.
(update: string array example, from this page)
on your strings.xml, instead of just one string per item, you can have a string array:
Mercury
Venus
Earth
Mars
to use it,