在按钮点击视图符号时替换片段

时间:2015-03-03 07:04:26

标签: android android-viewholder

我想在视图中点击按钮上的片段。

viewholder

static class ViewHolder {
Button button;
TextView title;
}

由listview组成的FragmentA的适配器类

viewHolder.button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentA fragmentA = new FragmentA();
            fragmentA.nextFragment();
        }
    });

FragmentA

public void nextFragment(){
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new FragmentB()).commit();
}

在替换片段

时给出nullpointerexception

logcat的

java.lang.NullPointerException
            at com.example.testapp.fragment.FragmentA.nextFragment(FragmentA.java:75)
            at com.example.testapp.adapter.FragmentAListAdapter$1.onClick(FragmentAListAdapter.java:54)
            at android.view.View.performClick(View.java:4222)
            at android.view.View$PerformClick.run(View.java:17620)
            at android.os.Handler.handleCallback(Handler.java:800)
            at android.os.Handler.dispatchMessage(Handler.java:100)
            at android.os.Looper.loop(Looper.java:194)
            at android.app.ActivityThread.main(ActivityThread.java:5370)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
            at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

尝试在您的活动中创建nextfragment功能。 像这样: -

public static void nextfragment(FragmentManager activity,Fragment fragment) {
        if (fragment == null) {
            return;
        }
        try {
            activity.popBackStack();
            FragmentTransaction transaction = activity.beginTransaction();
            transaction.replace(R.id.fragment_container, fragment).addToBackStack(null);
            transaction.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

并在您需要使用getactivity实例时使用它。

((MainActivity)getActivity()).nextfragment();