Dimebag
Dimebag

Reputation: 843

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.

Upvotes: 1

Views: 82

Answers (3)

George Mulligan
George Mulligan

Reputation: 11903

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;
}

Upvotes: 3

Biswajit Karmakar
Biswajit Karmakar

Reputation: 9897

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);
            }
        });

    }

Upvotes: 0

F43nd1r
F43nd1r

Reputation: 7749

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.

Upvotes: 2

Related Questions