android:How to add a button to the top of the list view
In My application I want to add a button to the top of the List view. It means at the top button is there after that list view is continued.
Following is my code. using this I am getting
05-23 11:44:34.407: ERROR/AndroidRuntime(1348): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.Elgifto/com.Elgifto.Egender}: java.lang.NullPointerException.
Egender.java
package com.Elgifto;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class Egender extends ListActivity{
Button b1;
ListView lv;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lv=(ListView) findViewById(R.id.list);
b1=new Button(this);
b1.setText("Done");
lv.addHeaderView(b1);
lv.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice, GENDER));
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
开发者_开发知识库 setContentView(lv);
}
private static final String[] GENDER = new String[] {
"Male","Female"
};
}
gender.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">
<ListView
android:id="@+id/list"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1"/>
</LinearLayout>
Thanks.
your should write setContentView(R.layout.gender) first below super and ListView in xml should have the id like this android:id="@+id/android:list" not
android:id="@+id/list" because you class extends ListView .
super.onCreate(savedInstanceState);
lv=(ListView) findViewById(R.id.list);
You cannot search for any views until they are inflated. Call setContentView() within your layout first, and modify it after.
you must setContentView before use any view.. so, try this..
super.onCreate(savedInstanceState);
setContentView(R.layout.gender);
lv=(ListView) findViewById(R.id.list);
b1=new Button(this);
b1.setText("Done");
.
.
.
etc
and you alos missed to define GENDER variable..
so first define it like as
String GENDER = new String{"Male","Female"};
精彩评论