Created
September 21, 2018 21:31
-
-
Save shibbirweb/290d5305b88b9b0f8d1f4cd95e89463d to your computer and use it in GitHub Desktop.
[Android] Custom Array Adapter for ListView with ViewHolder class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CustomArrayAdapter extends ArrayAdapter { | |
// declare your custom list with type; | |
private List<YourModelClass> allData = new ArrayList<YourModelClass>(); | |
public CustomArrayAdapter(@NonNull Context context, List<YourModelClass> allData) { | |
super(context, R.layout.your_layout, allData); // add your_layout.xml | |
this.allData = allData; | |
} | |
class ViewHolder { | |
TextView name, phone; // declare your your_layout.xml view type | |
} | |
@NonNull | |
@Override | |
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { | |
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); | |
ViewHolder holder = new ViewHolder(); | |
if (convertView == null) { | |
convertView = inflater.inflate(R.layout.your_layout, parent, false); // inflate your_layout.xml | |
//initialize your your_layout.xml view | |
holder.name = convertView.findViewById(R.id.tv_item_name); | |
holder.phone = convertView.findViewById(R.id.tv_item_phone); | |
convertView.setTag(holder); | |
} else { | |
holder = (ViewHolder) convertView.getTag(); | |
} | |
//set value into your_layout.xml | |
holder.name.setText(allData.get(position).getName()); | |
holder.phone.setText(allData.get(position).getNumber()); | |
return convertView; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment