Java 来自expandableListView内按钮的OnClickListeners的NullPointerException

Java 来自expandableListView内按钮的OnClickListeners的NullPointerException,java,android,Java,Android,问题是:我有一个活动,其中包含一个可扩展列表视图,在每个组中,我想显示明显的项目加上一个按钮,该按钮必须启动另一个活动,允许创建另一个项目并将其添加到列表中 我已经成功地创建了按钮(要做到这一点,将在每个组的最后一个位置放置一个空的子对象,并在getChildView中创建按钮的最后一个子对象(空的子对象)视图)。 代码如下: @Override public View getChildView(int groupPosition, int childPosition, boolean isLa

问题是:我有一个活动,其中包含一个可扩展列表视图,在每个组中,我想显示明显的项目加上一个按钮,该按钮必须启动另一个活动,允许创建另一个项目并将其添加到列表中

我已经成功地创建了按钮(要做到这一点,将在每个组的最后一个位置放置一个空的子对象,并在getChildView中创建按钮的最后一个子对象(空的子对象)视图)。 代码如下:

@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {

    if(isLastChild){
        LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.list_btn, null);
        Intent i = new Intent(_context,Menu.class);
        i.putExtra("WorkoutPosition", groupPosition);
        return convertView;
    }

    ...
}
这是按钮的XML代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical|center_horizontal">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="+ New Exercise"
        android:id="@+id/newExBtn"
        android:layout_gravity="center_vertical|center_horizontal"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"/>

</RelativeLayout>
以下是我得到的一个例外:

原因:java.lang.NullPointerException:
尝试在空对象引用上调用虚拟方法“void android.widget.Button.setOnClickListener(android.view.view$OnClickListener)”

似乎我正在尝试将侦听器设置在不存在的按钮上,但我不明白为什么以及由谁来修复此问题。
谢谢你的帮助

我猜您是在
活动中调用
findViewById()
,甚至可能是在将新的充气布局附加到它之前。由于
findViewById()
活动的根递归迭代(与
setContentView()
一起使用的布局),它将不会找到此按钮,直到您将其附加到
活动
(这就是为什么会得到
null

您的代码应该是:

Button newExBtn = (Button) convertView.findViewById(R.id.newExBtn);
newExBtn.setOnClickListener(new View.OnClickListener(){
    ...

请提供
列表\u btn
布局的XML。对不起,我不明白您建议做什么:(您的意思是将onClick方法的声明放在ExpandableListAdapter类中?但是这样我就不能让另一个活动以startActivity方法开始了?我很困惑。没有办法将布局附加到活动上,然后设置侦听器?
onClick
方法应该在适配器中。您可以n将
活动
传递给
可扩展列表适配器
Button newExBtn = (Button) convertView.findViewById(R.id.newExBtn);
newExBtn.setOnClickListener(new View.OnClickListener(){
    ...