尝试在Fragment

时间:2018-04-25 14:21:50

标签: java android android-fragments nullpointerexception imagebutton

尝试在片段(SessionsFragment.java)中的ImageButton上设置onClickListener,并且我不断获得空指针异常。尝试了所有不同的解决方案,仍然得到相同的错误。该按钮位于ExpandableListView中的项目中,因此我添加了list_item.xml。看到一些评论说它是空的,因为它不属于主要活动或类似的东西。无论如何,我怎么能克服这个?

SessionsFragment.java

public class SessionsFragment extends Fragment {

ExpandableListAdapter expandableListAdapter;
ExpandableListView expandableListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
ImageButton addButton;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_sessions, container, false);

    // Get the ListView
    expandableListView = view.findViewById(R.id.sessionsExpandableListView);

    // Prepare the list data
    prepareListData();

    expandableListAdapter = new ExpandableListAdapter(getContext(), listDataHeader, listDataChild);

    // Set the list adapter and expand lists by default
    expandableListView.setAdapter(expandableListAdapter);
    expandableListView.expandGroup(0);

    // Get button values
    addButton = view.findViewById(R.id.addButton);
    addButton.setOnClickListener(new ImageButton.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getActivity(), "Session added", Toast.LENGTH_SHORT).show();
        }
    });

    return view;
}

list_item.xml

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="55dp">

<TextView
    android:id="@+id/listItem"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="16sp"
    android:paddingTop="5dp"
    android:paddingBottom="5dp" />
    <!--android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft"/>-->

<ImageButton
    android:id="@+id/addButton"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:src="@drawable/ic_add_black_24dp"
    android:layout_alignParentRight="true" />

logcat的

  

04-25 15:12:04.053 11894-11901 /? E / zygote64:发送回复失败   调试器:管道坏了       04-25 15:12:04.578 11894-11894 /? E / AndroidRuntime:致命异常:主要                                                          过程:com.example.android.engineeringweek,PID:11894                                                          java.lang.RuntimeException:无法启动活动   ComponentInfo {com.example.android.engineeringweek / com.example.android.engineeringweek.SessionsActivity}:   java.lang.NullPointerException:尝试调用虚方法&#39; void   android.widget.ImageButton.setOnClickListener(android.view.View $ OnClickListener)&#39;   在null对象引用上                                                              在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)                                                              在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3046)                                                              在android.app.ActivityThread.-wrap11(未知来源:0)                                                              在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1688)                                                              在android.os.Handler.dispatchMessage(Handler.java:105)                                                              在android.os.Looper.loop(Looper.java:164)                                                              在android.app.ActivityThread.main(ActivityThread.java:6809)                                                              at java.lang.reflect.Method.invoke(Native Method)                                                              在com.android.internal.os.Zygote $ MethodAndArgsCaller.run(Zygote.java:240)                                                              在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)                                                           引起:java.lang.NullPointerException:尝试调用虚方法&#39; void   android.widget.ImageButton.setOnClickListener(android.view.View $ OnClickListener)&#39;   在null对象引用上                                                              在com.example.android.engineeringweek.SessionsFragment.onCreateView(SessionsFragment.java:47)                                                              在android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)                                                              在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419)                                                              在android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)                                                              在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)                                                              在android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)                                                              在android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)                                                              在android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)                                                              在android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)                                                              在android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)                                                              在android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3221)                                                              在android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3171)                                                              在android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:192)                                                              在android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:560)                                                              在android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)                                                              在android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1412)                                                              在android.app.Activity.performStart(Activity.java:7015)                                                              在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2909)

修改

ExpandableListAdapter.java

public class ExpandableListAdapter extends BaseExpandableListAdapter {
    private Context _context;
    private List<String> _listDataHeader;
    private HashMap<String, List<String>> _listDataChild;

    public ExpandableListAdapter(Context context, List<String> listDataHeader, HashMap<String, List<String>> listDataChild) {
        this._context = context;
        this._listDataHeader = listDataHeader;
        this._listDataChild = listDataChild;
    }

    @Override
    public int getGroupCount() {
        return this._listDataHeader.size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return this._listDataHeader.get(groupPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        String headerTitle = (String) getGroup(groupPosition);
        if(convertView == null) {
            LayoutInflater layoutInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(R.layout.list_group, null);
        }

        TextView listHeader = convertView.findViewById(R.id.listHeader);
        listHeader.setTypeface(null, Typeface.BOLD);
        listHeader.setText(headerTitle);

        return convertView;
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosition);
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        final String childText = (String) getChild(groupPosition, childPosition);

        if(convertView == null) {
            LayoutInflater layoutInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(R.layout.list_item, null);
        }

        TextView textListChild = convertView.findViewById(R.id.listItem);

        textListChild.setText(childText);

        return convertView;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return this._listDataChild.get(this._listDataHeader.get(groupPosition)).size();
    }

    @Override
    public boolean isChildSelectable(int i, int i1) {
        return true;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }
}

1 个答案:

答案 0 :(得分:1)

看来你的findViewById找不到id addButton。 查看完代码后,我发现您正在查看R.layout.fragment_sessions作为您的视图,但会搜索您的listitem中包含的ID。

如果要将clicklistener添加到列表项,则需要在创建/绑定视图符时在适配器类中执行此操作。