Android Display a list using ListView
I am trying to display a list after clicking a button on Android.
This is my code:
//Button after clicking should display a list
final Button button4 = (Button) findViewById(R.id.widget30);
button4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(v.getContext(), TestListActivities.class);
startActivity(myIntent);
}
public class TestListActivities extends Activity {
String[] listItems = {"Game1", "Game2",
"Game3", "Game4"};
public ListView la;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
la=(ListView)findViewById(R.id.widget50);
la.setAdapter(new ArrayAdapter<String>(this,
R.layout.main2, listItems));
}
}
My XML file is:
?xml version="1.0" encoding="utf-8"?
AbsoluteLayout
android:id="@+id/widget28"
android:layout_width="fill_par开发者_高级运维ent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
ListView
android:id="@+id/widget50"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
AbsoluteLayoute
But when I click the button, the application is forced to close and it crashes.
Manifest file
<application android:icon="@drawable/icon" android:label="BAM! Pong" android:debuggable="true">
<activity android:name=".GUI" android:label="@string/app_name" android:screenOrientation="portrait"><intent-filter><action android:name="android.intent.action.MAIN"></action>
It's difficult to know without seeing the stacktrace. Run "adb logcat" from the command line while running your app or watch the logs in the DDMS perspective in Eclipse. The stacktrace will give you the location of the bug or reason for the FC.
You seem to use the R.layout.main2 both as the activity layout (setContentView(R.layout.main2);) and as the ListView layout. (a.setAdapter(new ArrayAdapter(this, R.layout.main2, listItems));) and that is not the right way to use the ListView, the Activity layout should be a layout that contains a ListView, while the layout you are giving to the ArrayAdapter should be a different layout containing the views you would like to be repeated for each entry in your list.
Take a look at the API demos in the android sdk, there are several ListView examples that show you how to use the ListView.
Have you declared Activity in AndroidManifest?
精彩评论