Implementing buttons inside fragments - how to create the interface to communicate the fragments with activity

I find a nice layout with fragments here

I add buttons to the xml fragments but I do not know how to implement the buttons, I mean, I do not know how to do for the buttons work.

The problem is that I need to create a callback interface inside the fragment and require that the host activity implement it and than the activity receives a callback through the interface:

Fragments in Android

Unfortunately, it is not clear how to do it with buttons.

In short, I have my buttons and I do not know how to make it work.


I have the same problem. Well i can make the button click and do a simple Toast but nothing more with the Fragment. This model is really killing me here.

For adding in the button, create them on your fragment.xml files, then call them in your fragment class on the onCreate method. I use the simple code like this :

Button btn = (Button)getActivity().findViewById(;
btn.setOnClickListener(new View.OnClickListener() {                       
    public void onClick(View v) {
        Log.i("FragmentsTab1", "++ ON BUTTONCLICK 1 ++ ");

I usually wrap it in a try/catch as well. The button works, and will call my local private method (showFrag()) which can be a Toast or Dialog box but doing anything more doesn't work for me. I can't get access to the TextView on the Fragment.xml or make calls to the Activity. Really weird.

I think this might be relevant: for trivial cases

I found this post useful for complex designs: Restoring object references of fragments after configuration changes

Need Your Help

Use javascript to add a letter in css?

javascript html css css3

I'm having issues with my noggin... Please help me answer this question:

How can I specify Hadoop XML configuration variables via the Hadoop shell scripts?

hadoop environment-variables hdfs

I'm writing code to create a temporary Hadoop cluster. Unlike most Hadoop clusters, I need the location for logs, HDFS files, etc, to be in a specific temporary network location that is different e...