ListView не отображается на экране - PullRequest
0 голосов
/ 08 мая 2019

Я недавно начал использовать ListView в приложении для Android, и я не заставляю его отображаться на экране.

Я видел много уроков о том, как сделать пользовательский Adapter, и следовал за ним построчно, но в конце я не смог отобразить ListView на своем экране, я даже позволил фиксированный текст в один TextView для отображения на ListView, но он все еще не отображал его.

Это конструктор кода моей сущности:

 public Classificacao(int colocacao, int time, int pontos) {
        this.colocacao = colocacao;
        this.time = time;
        this.pontos = pontos;
    }

Это мой пользовательский адаптер, расширяющий "ArrayAdapter"

private Context context;
private ArrayList<Classificacao> classificacaoList;

ClassificacaoAdapter(Context context, ArrayList<Classificacao>         classificacaoList) {
    super(context, R.layout.layout_classificacao, classificacaoList);
    this.context = context;
    this.classificacaoList = classificacaoList;
}

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

    LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    if(convertView == null){
        convertView = layoutInflater.inflate(R.layout.layout_classificacao, parent, false);
    }

    TextView colocacao = convertView.findViewById(R.id.texto1);
    colocacao.setText(Integer.toString(classificacaoList.get(position).getColocacao()));

    ImageView imagem = convertView.findViewById(R.id.imagem1);
    imagem.setImageResource(classificacaoList.get(position).getImagem());

    TextView nome = convertView.findViewById(R.id.texto2);
    nome.setText(classificacaoList.get(position).getTime());

    TextView pontos = convertView.findViewById(R.id.texto3);
    pontos.setText(Integer.toString(classificacaoList.get(position).getPontos()));

    return convertView;
}

Это макет "activity_atividade02", который имеет ListView и некоторые другие текстовые представления, которые я не буду отображать здесь.

<ListView
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

Это макет "layout_classificacao", который будет заполнен adapter

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="20dp">

    <TextView
        android:id="@+id/texto1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:gravity="center"
        android:textColor="@android:color/black"
        android:textSize="30sp" />

    <ImageView
        android:id="@+id/imagem1"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:contentDescription="imagem do time"
        app:srcCompat="@drawable/flamengo" />

    <TextView
        android:id="@+id/texto2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:textColor="@color/colorPrimary"
        android:textSize="30sp" />

    <TextView
        android:id="@+id/texto3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:gravity="center"
        android:textColor="@android:color/black"
        android:textSize="30sp" />
</LinearLayout>

А это основной класс "Atividade02" которые начинают все

public class Atividade02 extends AppCompatActivity {

    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_atividade02);

        listView = findViewById(R.id.listView);

        ArrayList<Classificacao> classificacaoArrayList = new ArrayList<>();

        classificacaoArrayList.add(new Classificacao(1, 2,46));
        classificacaoArrayList.add(new Classificacao(2, 1,42));
        classificacaoArrayList.add(new Classificacao(3,0,38));
        classificacaoArrayList.add(new Classificacao(4,3,35));
        classificacaoArrayList.add(new Classificacao(5,5,33));
        classificacaoArrayList.add(new Classificacao(6,4,33));

        ArrayAdapter classificacaoAdapter = new ClassificacaoAdapter(this, classificacaoArrayList);

        listView.setAdapter(classificacaoAdapter);

    }
}

Продолжая, ListView не отображает "ClassificacaoAdapter", и я хочу, чтобы это было сделано.

Ответы [ 4 ]

0 голосов
/ 09 мая 2019

пожалуйста, добавьте метод getCount () в ваш класс ClassificacaoAdapter, это метод переопределения. Он вернет размер списка, если вы не переопределите его, он вернет 0 в качестве размера списка.

public int getCount() {
        return classificacaoList .size();
    }
0 голосов
/ 08 мая 2019

Ну ... это была довольно очевидная проблема, в основном макете activity_atividade02 было LinearLayout над ListView, что layout_height было установлено на match_parent и занимало весь макети не позволяя отображать ListView.

0 голосов
/ 08 мая 2019

Я проверяю ваш код во время написания и обнаружил здесь ошибку, и она работает нормально, но я комментирую строку imageView, потому что вы не определяете ее в классе Classificacao

ошибка здесь

TextView nome = convertView.findViewById(R.id.texto2);
nome.setText(classificacaoList.get(position).getTime());

setText () принимает только строку ... но вы передаете целое число, а не строку вы можете сделать это

nome.setText(""+classificacaoList.get(position).getTimee());

или используйте

Integer.toString( classificacaoList.get(position).getTimee() )

как вы используете в других строках

0 голосов
/ 08 мая 2019

Убедитесь, что у адаптера есть метод getItemcount() и он возвращает classificacaoList.size().Не должно return 0;

...