Skip to content

Instantly share code, notes, and snippets.

@Classy-Bear
Created February 17, 2020 18:56
Show Gist options
  • Save Classy-Bear/0f9ccef364444789db018244bd9b382a to your computer and use it in GitHub Desktop.
Save Classy-Bear/0f9ccef364444789db018244bd9b382a to your computer and use it in GitHub Desktop.
/**
* {@link WordAdapter} is an {@link ArrayAdapter} that can provide the layout for each list
* based on a data source, which is a list of {@link Word} objects.
*
*/
public class WordAdapter extends ArrayAdapter<Word> {
WordAdapter(@NonNull Context context, ArrayList<Word> wordArrayList) {
// Here, we initialize the ArrayAdapter's internal storage for the context and the list.
// the second argument is used when the ArrayAdapter is populating a single TextView.
// Because this is a custom adapter, the adapter is not
// going to use this second argument, so it can be any value. Here, we used 0.
super(context, 0, wordArrayList);
}
/**
* Provides a view for an AdapterView (ListView, GridView, etc.)
*
* @param position The position in the list of data that should be displayed in the
* list item view.
* @param convertView The recycled view to populate.
* @param parent The parent ViewGroup that is used for inflation.
* @return The View for the position in the AdapterView.
*/
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
/// Check if the existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext())
.inflate(R.layout.list_item, parent, false);
}
/// Get the {@link Word} object located at this position in the list
Word currentAndroidFlavor = getItem(position);
// Find the TextView in the list_item.xml layout with the ID version_name
TextView nameTextView = listItemView.findViewById(R.id.miwokWord);
// Get the text from the current object and
// set this text on the name TextView
nameTextView.setText(currentAndroidFlavor.getMiwokWord());
// Find the TextView in the list_item.xml layout
TextView numberTextView = listItemView.findViewById(R.id.englishWord);
// Get the version number from the current object and
// set this text on the number TextView
numberTextView.setText(currentAndroidFlavor.getEnglishWord());
// Return the whole list item layout (containing 2 TextViews)
// so that it can be shown in the ListView
return listItemView;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment