带有constrsint布局的ListView和ArrayAdapter会使应用程序崩溃

时间:2017-11-24 13:52:23

标签: android listview

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

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>

谢谢

2 个答案:

答案 0 :(得分:0)

可能在这条线上你会崩溃

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

您尝试将ConstraintLayout强制转换为ListView

答案 1 :(得分:0)

你正在使用这个:

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

找到ConstraintLayout。试试这个:

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

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