Android Studio 无法识别“setAdapter()”方法

Posted

技术标签:

【中文标题】Android Studio 无法识别“setAdapter()”方法【英文标题】:Android Studio cannot recognize "setAdapter()" method 【发布时间】:2015-08-20 02:10:35 【问题描述】:

我一直在尝试了解如何填充 ListView 并为此尝试制作一个简单的应用程序,该应用程序采用字符串数组并将其放在列表视图上。我创建了一个 ListView 对象“myListView”并尝试为此对象调用“setAdapter()”函数。但是 'setAdapter' 部分变成红色,它给了我一条错误消息说, “无法解析符号‘setAdapter’”

以下是MainActivity.java的源码:

import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.AbsListView;

public class MainActivity extends Activity 

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


String[] myArray = "biscuits", "laptops", "mice", "headphones", "macBook", "bottles", "something", "also something",
                    "this list is stupid", "and", "dumb", "and", "useless", "okay", "here it ends";

    ListAdapter myListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, myArray);

    ListView myListView = (ListView) findViewById(R.id.myListView);

    myListView.setAdapter(myListAdapter);

【问题讨论】:

【参考方案1】:

请在 setContentView 后删除 并在代码末尾添加新的

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


String[] myArray = "biscuits", "laptops", "mice", "headphones", "macBook", "bottles", "something", "also something",
                    "this list is stupid", "and", "dumb", "and", "useless", "okay", "here it ends";

    ListAdapter myListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, myArray);

    ListView myListView = (ListView) findViewById(R.id.myListView);

    myListView.setAdapter(myListAdapter);


【讨论】:

@SumodKulkarni,我犯了同样的错误 =)

以上是关于Android Studio 无法识别“setAdapter()”方法的主要内容,如果未能解决你的问题,请参考以下文章

Android Studio 无法识别“setAdapter()”方法

三星 Galaxy 手机在 Android Studio 上无法识别

Android Studio 无法识别最低 SDK

Android Studio 无法识别三星 Galaxy S8

Android Studio 无法识别 Facebook 库

Android Studio 无法识别我的设备