I have a question about ArrayAdapter.

Asked 2 years ago, Updated 2 years ago, 115 views

adapter = new ArrayAdapter<InspectorItem>
                (this, R.layout.test_list, strs);

If you run it with the above code, ArrayAdapter needs the resource ID to be a TextView error.

adapter = new ArrayAdapter<InspectorItem>
                (this, R.layout.test_list, R.id.testItem, strs);

So, when I added the id of row to the list view called testItem to the parameter, there was no error. The testItem is TextView. I have a feeling why I should put it in, but I don't know why.

arrayadapter listview adapter

2022-09-22 15:05

1 Answers

ArrayAdapter has enabled Array Items to display results in TextView by default. This is an error that occurs when there are multiple target layouts other than TextView (or even when the layout includes a view), because you do not know which view to display.

To resolve...

Example : res/layout/item.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent" >
    <TextView
      android:id="@+id/name"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Name" />
   <TextView
      android:id="@+id/email"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Email" />
</LinearLayout>

Example : CardAdapter.java

public class CardAdapter extends ArrayAdapter<Card> {
    public CardAdapter(Context context, ArrayList<Card> cards) {
       super(context, 0, cards);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
       // Import data (items) located in position from an array
       Card card = getItem(position);    
       // Check the contents of the item for reuse of the picture convertView
       // If it is null, make a new one, and if it is not null, reuse it.
       if (convertView == null) {
          convertView = LayoutInflater.from(getContext()).inflate(R.layout.item, parent, false);
       }
       // Find the view to which you want to apply the contents of the Card in the ConvertView
       TextView name = (TextView) convertView.findViewById(R.id.name);
       TextView email = (TextView) convertView.findViewById(R.id.email);
       // Specify a value for the view.
       name.setText(card.name);
       email.setText(card.email);
       // Return the completed view (to be displayed on the screen). )
       return convertView;
   }
}


2022-09-22 15:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.