Create custom ArrayAdapter




step - 1 create a listview in activity.xml.

            create rootview as linerlayout

step - 2 create a customview for listview.

             here we are doing this because we have created a listview but what will be in that list view is                   decided by the custom view

step - 3 create a custom class for custom layout.

step - 4 create custom array adapter.

public class NumbersViewAdapter extends ArrayAdapter<NumbersView> {
  
    // invoke the suitable constructor of the ArrayAdapter class
    public NumbersViewAdapter(@NonNull Context context, ArrayList<NumbersView> arrayList) {
        
          // pass the context and arrayList for the super 
          // constructor of the ArrayAdapter class
        super(context, 0, arrayList);
    }
  
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
  
        // convertView which is recyclable view
        View currentItemView = convertView;
  
        // of the recyclable view is null then inflate the custom layout for the same
        if (currentItemView == null) {
            currentItemView = LayoutInflater.from(getContext()).inflate(R.layout.custom_list_view, parent, false);
        }
  
        // get the position of the view from the ArrayAdapter
        NumbersView currentNumberPosition = getItem(position);
  
        // then according to the position of the view assign the desired image for the same
        ImageView numbersImage = currentItemView.findViewById(R.id.imageView);
        assert currentNumberPosition != null;
        numbersImage.setImageResource(currentNumberPosition.getNumbersImageId());
  
        // then according to the position of the view assign the desired TextView 1 for the same
        TextView textView1 = currentItemView.findViewById(R.id.textView1);
        textView1.setText(currentNumberPosition.getNumberInDigit());
  
        // then according to the position of the view assign the desired TextView 2 for the same
        TextView textView2 = currentItemView.findViewById(R.id.textView2);
        textView2.setText(currentNumberPosition.getNumbersInText());
  
        // then return the recyclable view
        return currentItemView;
    }
}

step -5 now we create declare or initiate the listview in the mainactivity.

         // Now create the instance of the NumebrsViewAdapter and pass 
          // the context and arrayList created above
        NumbersViewAdapter numbersArrayAdapter = new NumbersViewAdapter(this, arrayList);
  
        // create the instance of the ListView to set the numbersViewAdapter
        ListView numbersListView = findViewById(R.id.listView);
  
        // set the numbersViewAdapter for ListView
        numbersListView.setAdapter(numbersArrayAdapter);
    }
}

Comments