android listview无法正常工作

时间:2014-08-14 16:44:51

标签: android listview android-arrayadapter

我是Android开发的新手,我刚刚了解了列表视图和数组适配器等。我在android studio中有一个项目,有多个活动,在一个我有一个数组适配器和列表视图,但每次我运行应用程序并切换到其中包含列表视图的活动,应用程序不响应并关闭。我检查了代码,它与我见过的几个教程中的代码相同。我认为这与我的多项活动有关,有人可以帮助我吗?

public class StoreActivity extends ActionBarActivity {

String[] storeList = {"Ship 1", "Ship 2", "Ship 3"};


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

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

    ArrayAdapter<String> adapter = new ArrayAdapter(this, R.layout.row_layout, storeList);
    store.setAdapter(adapter);
}

2 个答案:

答案 0 :(得分:0)

如果你没有使用ArrayAdapter,这是初始化它的正确方法:

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

例如:

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

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

    //ArrayAdapter<String> adapter = new ArrayAdapter(this, R.layout.row_layout, storeList);
     ArrayAdapter<String> adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, storeList);
    store.setAdapter(adapter);
}

但是想要在自定义行布局(row_layout.xml)中加载数据,添加textView的id(我认为这就是你需要的):

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

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

    //ArrayAdapter<String> adapter = new ArrayAdapter(this, R.layout.row_layout, storeList);
     ArrayAdapter<String> adapter = new ArrayAdapter(this, android.R.layout.row_layout,  R.id.myTextView, storeList);
    store.setAdapter(adapter);
}

答案 1 :(得分:0)

更改此行

    ArrayAdapter<String> adapter = new ArrayAdapter(this, R.layout.row_layout, storeList);

到此:

ArrayAdapter<String> adapter = new ArrayAdapter(this, R.layout.row_layout, R.id.TextViewofRow_layoutstoreList, storeList);

你需要说明你将把数据放在哪个textview中。