带有 ConstraintLayout 的 ListView 和 ArrayAdapter 使应用程序崩溃

ListView and ArrayAdapter with ConstraintLayout crashes the app

它与线性布局完美配合,但当我选择 ConstraintLayout 它不起作用,我不知道为什么应用程序崩溃

NumbersActivity.java

package com.example.bharat.learnmiwok;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;  

public class NumbersAct extends AppCompatActivity {

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

    ArrayList<String> words = new ArrayList<String>();
    words.add("one");
    words.add("two");
    words.add("three");
    words.add("four");
    words.add("five");
    words.add("six");
    words.add("seven");
    words.add("eight");
    words.add("nine");
    words.add("ten");

            ArrayAdapter<String> itemsAdapter =
            new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, words);

    ListView listView = (ListView) findViewById(R.id.list);



    listView.setAdapter(itemsAdapter);
  }
}

activity_numbers.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.bharat.learnmiwok.MainActivity"
android:id="@+id/list"
android:orientation="vertical">
</android.support.constraint.ConstraintLayout>

谢谢

您的布局中需要有一个 ID 为 listListView。 Remove/Change 来自您的 ConstraintLayout 的 id,添加一个列表视图并重试。

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

您的 ConstraintLayout 不是 ListView。

可能在这条线上你遇到了崩溃

ListView listView = (ListView) findViewById(R.id.list);

您试图将 ConstraintLayout 转换为 ListView

您正在使用这个:

ListView listView = (ListView) findViewById(R.id.list);

找到一个ConstraintLayout。试试这个:

ConstraintLayout listView = (ConstraintLayout) findViewById(R.id.activity_main);

这只会解决您的崩溃问题,但最好使用 listView 或将其包含在 ConstraintLayout 中以实现您的目标。