Почему пользовательский ArrayAdapter не показывает TextView в ListView

Я сделал собственный ArrayAdapter и попытался добавить еще один TextView «Порода» животных, но когда я запускаю программу, она не показывает породу. Где я делаю неправильно? Ломаю голову давно. помогите пожалуйста где ошибка?

MainActivity.Java

public class MainActivity extends AppCompatActivity {

    ListView simpleList;
    ArrayList<Item> animalList=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        simpleList = (ListView) findViewById(R.id.simpleListView);


        animalList.add(new Item("Lion",R.drawable.lion,"Khatarnak"));
        animalList.add(new Item("Tiger",R.drawable.tiger,"Fudu"));
        animalList.add(new Item("Monkey",R.drawable.monkey,"Lallu"));
        animalList.add(new Item("Elephant",R.drawable.elephant,"Jabardast"));
        animalList.add(new Item("Dog",R.drawable.dog,"ItemDog"));
        animalList.add(new Item("Cat",R.drawable.cat,"MeeMee"));

        MyAdapter myAdapter=new MyAdapter(this,R.layout.list_view_items,animalList);
        simpleList.setAdapter(myAdapter);
    }
}

MyAdapter.Java

public class MyAdapter extends ArrayAdapter<Item> {

    ArrayList<Item> animalList = new ArrayList<>();

    public MyAdapter(Context context, int textViewResourceId, ArrayList<Item> objects) {
        super(context, textViewResourceId, objects);
        animalList = objects;
    }

    @Override
    public int getCount() {
        return super.getCount();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.list_view_items, null);

        TextView textView = (TextView) v.findViewById(R.id.textView);
        ImageView imageView = (ImageView) v.findViewById(R.id.imageView);
        TextView breedView = (TextView)v.findViewById(R.id.breed);

        textView.setText(animalList.get(position).getAnimalName());
        imageView.setImageResource(animalList.get(position).getAnimalImage());
        breedView.setText(animalList.get(position).getBreed());

        return v;

    }

}

Предмет.Java

public class Item {

    String animalName;
    int animalImage;
    String breedName;


    public String getBreed() {
        return breedName;
    }

    public void setBreed(String breed) {
        this.breedName = breedName;
    }

    public Item(String animalName,int animalImage,String breedName)
    {
        this.animalImage=animalImage;
        this.animalName=animalName;
        this.breedName = breedName;
    }
    public String getAnimalName()
    {
        return animalName;
    }
    public int getAnimalImage()
    {
        return animalImage;
    }
}

Activity_main.xml

<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
    xmlns:tools = "http://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    tools:context = ".MainActivity">

    <ListView
        android:id = "@+id/simpleListView"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:divider = "#000"
        android:dividerHeight = "2dp"/>

</RelativeLayout>

list_view_items.xml

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
    android:layout_width = "match_parent"
    android:layout_height = "wrap_content"
    android:orientation = "horizontal">

    <ImageView
        android:id = "@+id/imageView"
        android:layout_width = "50dp"
        android:layout_height = "50dp"
        android:padding = "5dp" />

    <TextView
        android:id = "@+id/textView"
        android:layout_width = "fill_parent"
        android:layout_height = "wrap_content"
        android:layout_gravity = "center"
        android:text = "Demo"
        android:textColor = "#000" />

    <TextView
        android:id = "@+id/breed"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:layout_gravity = "center"
        android:text = "Breed"
        android:textColor = "#000" />


</LinearLayout>
2
0
73
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий

Это, скорее всего, проблема с линейной компоновкой для каждого элемента. Ориентация — horizontal, которая размещает каждый вид один за другим по горизонтали. Проблема в том, что текстовое представление для типа животных имеет ширину fill_parent, не оставляя места для представления breed. Если вы измените его на wrap_content, он, вероятно, будет работать в некоторых случаях, но не во всех.

В любом случае я думаю, что это проблема с позициями и размерами представлений. Попробуйте переместить их. Возможно, даже простым изменением будет размещение их вертикально:

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout
    xmlns:android = "http://schemas.android.com/apk/res/android"
   android:layout_width = "match_parent"
   android:layout_height = "wrap_content"
   android:orientation = "horizontal">

   <ImageView
    android:id = "@+id/imageView"
    android:layout_width = "50dp"
    android:layout_height = "50dp"
    android:padding = "5dp" />

  <LinearLayout
   android:layout_width = "match_parent"
   android:layout_height = "wrap_content"
   android:orientation = "vertical">

      <TextView
        android:id = "@+id/textView"
        android:layout_width = "fill_parent"
        android:layout_height = "wrap_content"
        android:layout_gravity = "center"
        android:text = "Demo"
        android:textColor = "#000" />

     <TextView
        android:id = "@+id/breed"
        android:layout_width = "fill_parent"
        android:layout_height = "wrap_content"
        android:layout_gravity = "center"
        android:text = "Breed"
        android:textColor = "#000" />
   </LinearLayout>
</LinearLayout>

Возможно, есть более эффективный способ сделать это, но это всего лишь пример. Внутренний линейный макет помещает одно текстовое представление на другое.

PS: ваш метод getCount на самом деле ничего не делает. Вы можете удалить его.

замените свой макет моим кодом, ваша проблема будет решена.

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
    android:layout_width = "match_parent"
    android:layout_height = "wrap_content"
    android:orientation = "horizontal">

    <ImageView
        android:id = "@+id/imageView"
        android:layout_width = "50dp"
        android:layout_height = "50dp"
        android:padding = "5dp" />

    <TextView
        android:id = "@+id/textView"
        android:layout_width = "0dp"
        android:layout_height = "wrap_content"
        android:layout_gravity = "center"
        android:layout_weight = "1"
        android:text = "Demo"
        android:textColor = "#000" />

    <TextView
        android:id = "@+id/breed"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:layout_gravity = "center"
        android:text = "Breed"
        android:textColor = "#000" />


</LinearLayout>

вы использовали fill_parent, поэтому он отображается в полноэкранном режиме.

VIISHRUT MAVANII 16.03.2019 05:05

Другие вопросы по теме