繁体   English   中英

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

[英]android:How to add a button to the top of the list view

在我的应用程序中,我想在“列表”视图的顶部添加一个按钮。 这意味着继续该列表视图后,顶部按钮在那里。

以下是我的代码。 使用这个我越来越

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”而不是

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"};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM