简体   繁体   中英

How to listen click action of the button which is from Activity on fragment?

i have an activity that has a Fragment.I want to listen my button which in my activity from my fragment. Sample Code is here;

MainActivity

  OnSearchClickListener searchListener;


@Override
protected void onCreate(Bundle savedInstanceState){
......
}


myButton.setOnclickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            searchListener.OnSearchClick();
        }
    });

myFragment

public class MyFragment extends Fragment implements OnSearchClickListener{
........
 @Override
public void OnSearchClick() {

   Toast.makeText(context,"This message from fragment",......
}

Listener

public interface OnSearchClickListener {
public void OnSearchClick();

}

i used this structure. but it gave me nullpointerexception. Do you tell me how can i listen a button which in an Activity from a fragment ?

Do you tell me how can i listen a button which in an Activity from a fragment ?

Doing in right way but forget to initialize searchListener object using Fragment object which currently adding in FragmentManager. do it as:

MyFragment  mFragment = new MyFragment();
...
ft.add(R.id.content, mFragment).commit();
searchListener=(OnSearchClickListener)mFragment;

Now use searchListener object for calling OnSearchClick from Activity on Button click.

You just have to initialize OnSearchClickListener searchListener; inside your onCreate method from the MainActivity.

You should have something like this in you onCreate:

MyFragment frag = new MyFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.main_activity_container, frag);
            ft.commit();

before beginning the transaction, you do this:

searchListener = (OnSearchClickListener) frag;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM