android:如何在列表视图顶部添加按钮

问题描述

| 在我的应用程序中,我想在“列表”视图的顶部添加一个按钮。这意味着继续该列表视图后,顶部按钮在那里。 以下是我的代码。使用这个我越来越   05-23 11:44:34.407:   错误/ AndroidRuntime(1348):   java.lang.RuntimeException:无法执行   开始活动   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\"
    };
}
性别.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>
谢谢。     

解决方法

您应该在super下方首先写setContentView(R.layout.gender),而xml中的ListView应该具有这样的id android:id = \“ @ + id / android:list \” not android:id = \“ @ + id / list \”,因为您的课程扩展了ListView。     ,
    super.onCreate(savedInstanceState);

   lv=(ListView) findViewById(R.id.list);
膨胀之前,您无法搜索任何视图。首先在布局中调用setContentView(),然后再对其进行修改。     ,您必须先设置setContentView才能使用任何视图。 所以,尝试这个
super.onCreate(savedInstanceState);
 setContentView(R.layout.gender);
 lv=(ListView) findViewById(R.id.list);
        b1=new Button(this);
        b1.setText(\"Done\");
.
.
.
etc
而且您还没有定义GENDER变量。 所以先定义为
String GENDER = new String{\"Male\",\"Female\"};