Home > OS >  How to open activity from fragment
How to open activity from fragment

Time:12-06

I am just learning programming and faced with such an error. I need to open activity ruki from home fragment. But when I run the emulator, my application crashes What am I doing wrong


    ImageButton ruki;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
      View view = inflater.inflate(R.layout.fragment_home, null);
      final ImageButton imageButton = (ImageButton) view. findViewById(R.id.ruki);
      View.OnClickListener onClickListener = new View.OnClickListener() {
          @Override
          public void onClick(View view) {
              switch (view.getId()){
                  case R.id.ruki:
                      Intent intent = new Intent( HomeFragment.this.getActivity(), ruki_activity.class);
                      startActivity(intent);
                      break;
              }
          }
      };
      ruki.setOnClickListener(onClickListener);
      return inflater.inflate(R.layout.fragment_home, container, false);

    }
} 

CodePudding user response:

you are never initiating ImageButton ruki;, you are obtainging reference to final ImageButton imageButton, which isn't even used. ruki.setOnClickListener(onClickListener); will cause NullPointerException (ALWAYS post exception stacktrace)

instead of creating new variable

final ImageButton imageButton = (ImageButton) view. findViewById(R.id.ruki);

just attach result of findViewById to declared one

ruki = (ImageButton) view. findViewById(R.id.ruki);
  • Related