Cannot startActivity from fragment button

Beginner in android; code looks fine to me but when testing, I click the button and nothing happens. I added a log.i in the onCreate method inside the activity to start (Act2 here) and it does not show, so I must have made a mistake somewhere.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    //startNFC Activity when button clicked
    View view = inflater.inflate(R.layout.fragment_find_book, container, false);
    Button button = (Button) view.findViewById(R.id.button1);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(getActivity(), Act2.class);
            startActivity(i);
        }
    });
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_find_book, container, false);
}

Is anything wrong with the above code? A checklist could also help. Maybe I'm missing some other obvious override method?

I'll gladly post more code; note that the app now basically contains only MainActivity with this fragment inside, fragment containing only this button.

Answers


You need to return view from the method. Currently you are re-inflating the layout which will create a whole new view hierarchy that has a button without your click listener set. This is why when you press the button nothing will happen.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    //...everything you currently have
    return view;
}

Replace

return inflater.inflate(R.layout.fragment_find_book, container, false);

with

return view;

You are inflating your layout twice. You assign the ClickListener to the first one, but use the second one.


Change your code like this.

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {       

        return inflater.inflate(R.layout.fragment_find_book, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        Button button = (Button) getView().findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getActivity(), Act2.class);
                startActivity(i);
            }
        });

    }

Need Your Help

The usage of named and unnamed semaphore

c linux posix shared-memory semaphore

I've read in this post regarding named and unnamed semaphore , which states that a named semaphore is used for 2 unrelated processes , and unnamed semaphore is used for 2 related processes .