Skip to content

Instantly share code, notes, and snippets.

@TwiN
Forked from blackcj/ActivityEventListener.md
Created October 24, 2017 14:48
Show Gist options
  • Save TwiN/7c452ef11b2699fd22f37124f1c894f5 to your computer and use it in GitHub Desktop.
Save TwiN/7c452ef11b2699fd22f37124f1c894f5 to your computer and use it in GitHub Desktop.
Demonstrates how to call a function in the parent Activity from within a Fragment.

Step 1: Add any functions you want to call into the interface (EventListener).

Step 2: Implement those functions in your MainActivity.

Step 3: Create the listener in your Fragment and attach it to the Activity.

Step 4: Call any functions on the listener.

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by cblack on 8/15/13.
*/
public class DetailFragment extends Fragment {
private EventListener listener;
@Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
if(activity instanceof EventListener) {
listener = (EventListener)activity;
} else {
// Throw an error!
}
}
/**
*
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_detail, container, false);
listener.sendDataToActivity("Hello World!");
return v;
}
}
/**
* Created by cblack on 8/15/13.
*/
public interface EventListener {
public void sendDataToActivity(String data);
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends FragmentActivity implements EventListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.x_activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void sendDataToActivity(String data) {
Log.i("MainActivity", "sendDataToActivity: " + data);
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:name="com.example.listenerdemo.DetailFragment"
android:id="@+id/detail_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment