Listener from fragment to activity

Listener from fragment to actvity

We need three things
– Interface
– Fragment
– Activity

Complete code in github

We create a simple Interface:

public interface InteractionListener {
    void onFragmentInteraction(String string);
}

Now in our fragment We need to use onAttach(Context context), called when a fragment is first attached to its context. In this method we init our listener

When the user click in button, we call our listener.

public class OurFragment extends Fragment implements View.OnClickListener{

    private EditText mEditText;
    private InteractionListener mListener;

    public OurFragment() {
        // Required empty public constructor
    }

    public static OurFragment newInstance() {
        OurFragment fragment = new OurFragment();
        return fragment;
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_our, container, false);
        mEditText = (EditText) view.findViewById(R.id.fragment_our_edit_text);
        Button button = (Button) view.findViewById(R.id.fragment_our_button);
        button.setOnClickListener(this);
        return view;
    }

    public void sentString() {
        mListener.onFragmentInteraction(mEditText.getText().toString());
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof InteractionListener) {
            //init the listener
            mListener = (InteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement InteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        sentString();
    }
}

Now in activity We implement the listener

implements InteractionListener

And then to put our method

onFragmentInteraction(String string)
 
public class MainActivity extends AppCompatActivity implements InteractionListener{
    private static final String TAG = "MainActivity";
    private MenuItem mSearchMenuItem;

    private SearchView mSearchView;
    private String mSearchString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        replaceFragment();

    }

    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);

        mSearchMenuItem = menu.findItem(R.id.menu_main_action_search);

        mSearchView = (SearchView) MenuItemCompat.getActionView(mSearchMenuItem);

        focusSearView();

        return super.onCreateOptionsMenu(menu);
    }

    public void focusSearView(){
        if (mSearchString != null && !mSearchString.isEmpty()) {
            mSearchMenuItem.expandActionView();
            mSearchView.setQuery(mSearchString, true);
            mSearchView.clearFocus();
        }
    }

    public void replaceFragment() {
        Fragment OurFragment = new OurFragment().newInstance();

        try {

            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.content_main, OurFragment, "tag").commit();

        } catch (Exception e) {
            Log.d(TAG, e.toString());
        }

    }

    @Override
    public void onFragmentInteraction(String string) {
        //listened
        mSearchString = string;
        focusSearView();
    }
}

Here activity layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.javier.customsearchview.MainActivity">

</RelativeLayout>

Now we create our SearchView. First we need to create new folder which name is menu.

After that we create new xml file, which name is “main”.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/menu_main_action_search"
        android:icon="@android:drawable/ic_menu_search"
        android:title="@string/menu_main_search_title"
        app:actionViewClass="android.support.v7.widget.SearchView"
        app:showAsAction="always|collapseActionView" />
</menu>

Finally fragment layout:

<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="com.example.javier.customsearchview.OurFragment">

    <EditText
        android:id="@+id/fragment_our_edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:gravity="center" />

    <Button
        android:id="@+id/fragment_our_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/fragment_our_edit_text"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Complete code in github

TextChangedListener Android

TextWatcher

You can do the addTextChangedListener() method one time.

 TextChangedListener Android

First step

implements TextWatcher

Then you have a error
add unimplemented method


	@Override
	public void afterTextChanged(Editable s) {

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {

	}

Now you can need declare you editText and to add listener in onCreate()

public class MainActivity extends ActionBarActivity implements OnClickListener,TextWatcher {

	EditText mEditText;
	Button mButtonSave;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mButtonSave = (Button) findViewById(R.id.activity_main_button_save);
		mEditText = (EditText) findViewById(R.id.activity_main_editText1);

		mEditText.setOnClickListener(this);

		mButtonSave.setEnabled(false);
		mEditText.addTextChangedListener(this);
	}

	@Override
	public void afterTextChanged(Editable s) {

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		if (mEditText.getText().length() == 0) {
			mButtonSave.setEnabled(false);
		}else{
			mButtonSave.setEnabled(true);
		}
	}

}

Donwload code

Listener in Android

The observer pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.

The object which is being watched is called the subject.The objects which are watching the state changes are calledobservers or listeners.

How to make in android is the same that in java.

The first

1) To Create a class which name is MyListener.
-Interface.
-Variable (listener).
-Void.
-To call the void if (listener!= null).

package com.thedeveloperworldisyours.simplelistener;

public class MyListener {
	public interface Listener {
        public void onStateChange(boolean state);
    }

    private Listener mListener = null;
    public void registerListener (Listener listener) {
        mListener = listener;
    }

    private boolean myBoolean = false;
    public void doYourWork() {
    	myBoolean = true;
        if (mListener != null)
            mListener.onStateChange(myBoolean);
    }
}

The second
2)To use the listener
-Declare the variable
-new Listener
-to use the listener’s void

package com.thedeveloperworldisyours.simplelistener;

import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;

public class TheDeveloperWorldIsYours extends Activity implements MyListener.Listener{

	private TextView mTextView;
	private MyListener mListener;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_the_developer_world_is_yours);

		mTextView = (TextView) findViewById(R.id.tvTheDeveloperWorldIsYours);
		mListener = new MyListener();
		mListener.registerListener(this);
		mListener.doYourWork();
	}
	@Override
	public void onStateChange(boolean state) {

		if (state) {
			mTextView.setText("on");
        } else {
        	mTextView.setText("off");
        }

	}

}

Download the example here