编码-
package myusic.app.activity;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MyusicActivity extends Activity {
ArrayList<String> listItems=new ArrayList<String>();
ArrayAdapter<String> adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
listItems);
ListView myList=(ListView)findViewById(android.R.id.list);
myList.setAdapter(adapter);
}
public void addItems(View v) {
listItems.add("Clicked");
adapter.notifyDataSetChanged();
}
}
XML 布局代码-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Myusic player"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/b1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:onClick="addItems"
/>
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
我在手机上运行它时显示的错误是:
The application Myusic(process myusic.app.activity) has stopped unexpectedly. Please try again.
我认为错误在该行中,myList.setAdapter(adapter)
因为我已经尝试删除该行,并且它没有显示任何错误,但显然当我按下按钮时它确实如此。请帮我解决这个问题。提前致谢。:)