Button Listener for button in fragment in android

后端 未结 9 2103
北恋
北恋 2020-12-02 11:04

I am new to Android and trying to learn on my own. But I am having a tough time with Fragments. I am creating a simple application to learn fragments. I think it may seem si

9条回答
  •  醉梦人生
    2020-12-02 11:29

    Fragment Listener

    If a fragment needs to communicate events to the activity, the fragment should define an interface as an inner type and require that the activity must implement this interface:

    import android.support.v4.app.Fragment;
    
    public class MyListFragment extends Fragment {
      // ...
      // Define the listener of the interface type
      // listener is the activity itself
      private OnItemSelectedListener listener;
    
      // Define the events that the fragment will use to communicate
      public interface OnItemSelectedListener {
        public void onRssItemSelected(String link);
      }
    
      // Store the listener (activity) that will have events fired once the fragment is attached
      @Override
      public void onAttach(Activity activity) {
        super.onAttach(activity);
          if (activity instanceof OnItemSelectedListener) {
            listener = (OnItemSelectedListener) activity;
          } else {
            throw new ClassCastException(activity.toString()
                + " must implement MyListFragment.OnItemSelectedListener");
          }
      }
    
      // Now we can fire the event when the user selects something in the fragment
      public void onSomeClick(View v) {
         listener.onRssItemSelected("some link");
      }
    }
    

    and then in the activity:

    import android.support.v4.app.FragmentActivity;
    
    public class RssfeedActivity extends FragmentActivity implements
      MyListFragment.OnItemSelectedListener {
        DetailFragment fragment;
    
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_rssfeed);
          fragment = (DetailFragment) getSupportFragmentManager()
                .findFragmentById(R.id.detailFragment);
      }
    
      // Now we can define the action to take in the activity when the fragment event fires
      @Override
      public void onRssItemSelected(String link) {
          if (fragment != null && fragment.isInLayout()) {
              fragment.setText(link);
          }
      }
    }
    

提交回复
热议问题