在findView中遇到问题(Android Studio)

时间:2019-05-18 19:03:53

标签: java android android-layout

我是Android Studio的新手,正在从事一个项目。 我遇到这个错误

enter image description here

我已经声明了listview,但是不知道为什么它不起作用。  代码:

package com.example.animation;

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

public class view_rooms extends AppCompatActivity {
    ListView listView;
    String mTitle[]={"Room1","Room2","Room3","Room4","Room5"};
    String mDescription[]={"Access Room1","Access Room2","Access Room3","Access Room4","Access Room5"};
    int images[]={R.drawable.lights_open,R.drawable.lights_open,R.drawable.lights_open,R.drawable.lights_open,R.drawable.lights_open};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_rooms);
        listView=findViewById(R.id.ListView);

    }

2 个答案:

答案 0 :(得分:2)

findViewById()按ID将视图搜索到布局文件中。在这种情况下,进入布局:R.layout.activity_view_rooms。您需要在此布局中定义一个ListView小部件,并分配一个ID以使用findViewById()进行搜索。

例如,在布局activity_view_rooms中,您需要包括以下视图:

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

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

    </ListView>
</LinearLayout>

然后,您可以通过finViewById()以这种方式获取view的实例:

package com.example.animation;

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

public class view_rooms extends AppCompatActivity {
    ListView listView;
    String mTitle[]={"Room1","Room2","Room3","Room4","Room5"};
    String mDescription[]={"Access Room1","Access Room2","Access Room3","Access Room4","Access Room5"};
    int images[]={R.drawable.lights_open,R.drawable.lights_open,R.drawable.lights_open,R.drawable.lights_open,R.drawable.lights_open};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_rooms);
        listView=findViewById(R.id.list_view_id);

    }

答案 1 :(得分:0)

您需要将此行android:id="@+id/ListView"添加到activity_view_rooms.xml

因此代码将如下所示:

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