单击列表片段上的项目时如何将信息传递给片段

How to pass information to a fragment when an item on a listfragment is clicked

我有一个包含项目列表的片段列表 SecondActivityListFragment。如果单击列表中的项目,我想将此单击项目的信息传递给另一个名为 ItemViewFragment 的片段。我创建了一个名为 Communicator 的接口 class,但我不知道如何传递信息。

SecondActivityListFragment

public class SecondActivityListFragment extends ListFragment {

Communicator communicator;

private ArrayList<SubNote> subNotes;
private SubNoteAdapter subNoteAdapter;

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

    communicator = (Communicator) getActivity();
    subNotes = new ArrayList<SubNote>();
    subNotes.add(new SubNote("Product X", "wow", "booo", new     BigDecimal(10212).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.HEALTHCARE));
    subNotes.add(new SubNote("Product Y", "wow", "booo", new BigDecimal(107866.23).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.DENTAL));
    subNotes.add(new SubNote("Product Y", "wow", "booo", new BigDecimal(107866.23).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.DENTAL));
    subNotes.add(new SubNote("Product Y", "wow", "booo", new BigDecimal(107866.23).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.DENTAL));
    subNotes.add(new SubNote("Product Y", "wow", "booo", new BigDecimal(107866.23).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.DENTAL));
    subNotes.add(new SubNote("Product Y", "wow", "booo", new BigDecimal(107866.23).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.DENTAL));
    subNotes.add(new SubNote("Product Y", "wow", "booo", new BigDecimal(107866.23).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.DENTAL));
    subNotes.add(new SubNote("Product Y", "wow", "booo", new BigDecimal(107866.23).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.DENTAL));

    subNoteAdapter = new SubNoteAdapter(getActivity(), subNotes);
    setListAdapter(subNoteAdapter);
}

@Override
public void onListItemClick(ListView l, View v, int position, long id){
    super.onListItemClick(l, v, position, id);



    launchNoteDetailActivity(position);

}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof Communicator) {
        communicator = (Communicator) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement Communicator");
    }
}

private void launchNoteDetailActivity(int position){


    ItemViewFragment itemViewFragment = new ItemViewFragment();
    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.content_main, itemViewFragment, itemViewFragment.getTag()).commit();

    //communicator.respond(position);

    // Grab the note information associated with whatever note item we clicked on
    //SubNote subNote = (SubNote) getListAdapter().getItem(position);

}
}

主要活动

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener, Communicator {

//public static final String SUB_NOTE_NAME_EXTRA = "com.example.khalid.myapplication2.SubNote Title";
//public static final String SUB_NOTE_BRIEFDESCRIPTION_EXTRA = "com.example.khalid.myapplication2.SubNote BriefDescription";
//public static final String SUB_NOTE_FULLDESCRIPTION_EXTRA = "com.example.khalid.myapplication2.SubNote FullDescription";
//public static final String SUB_NOTE_PRICE_EXTRA = "com.example.khalid.myapplication2.SubNote Price";
//public static final String SUB_NOTE_CATEGORY_EXTRA = "com.example.khalid.myapplication2.SubNote Category";

// ViewPager viewPager;
// CustomSwipeAdapter imgadapter;

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



    MainActivityListFragment mainActivityListFragment = new MainActivityListFragment();
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.content_main, mainActivityListFragment, mainActivityListFragment.getTag()).commit();



   // viewPager = (ViewPager) findViewById(R.id.viewpager1);
   // imgadapter = new CustomSwipeAdapter(this);
   // viewPager.setAdapter(imgadapter);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}



@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@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);

    SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
    SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    return true;
}


  /*  @Override
      public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
 }*/

  @SuppressWarnings("StatementWithEmptyBody")
  @Override
  public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_home) {
        MainActivityListFragment mainActivityListFragment = new MainActivityListFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_main, mainActivityListFragment, mainActivityListFragment.getTag()).commit();
        setTitle("ThimarAljazirah");
    } else if (id == R.id.nav_notification) {

        NotificationsFragment notificationsFragment = new NotificationsFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_main, notificationsFragment, notificationsFragment.getTag()).commit();
        setTitle("Notifications");

    } else if (id == R.id.nav_messages) {

    } else if (id == R.id.nav_categories) {

    } else if (id == R.id.nav_deals) {

    } else if (id == R.id.nav_settings) {
        SettingFragment settingFragment = new SettingFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_main, settingFragment, settingFragment.getTag()).commit();
        setTitle("Settings");
    } else if (id == R.id.nav_help_contact) {

    } else if (id == R.id.nav_profile) {
        MyProfile myProfile = new MyProfile();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_main, myProfile, myProfile.getTag()).commit();
        setTitle("My Profile");

    } else if (id == R.id.nav_signout) {
        SingOutFragment singOutFragment = SingOutFragment.newInstance("1", "2");
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_main,singOutFragment, singOutFragment.getTag()).commit();

    } else if (id == R.id.nav_about_us) {
        AboutUsFragment aboutUsFragment = new AboutUsFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_main,aboutUsFragment, aboutUsFragment.getTag()).commit();
        setTitle("About Thimar Aljazirah");
    }


    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}


@Override
public void respond(int position) {

    ItemViewFragment itemViewFragment = new ItemViewFragment();



}
}

ItemViewFragment

public class ItemViewFragment extends Fragment {


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


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {


    return inflater.inflate(R.layout.fragment_item_view, container, false);
}

}

通讯器

public interface Communicator {
public void respond (int position);
}

与 activity

的其他片段交流

1>.定义接口

public class HeadlinesFragment extends ListFragment {
OnHeadlineSelectedListener mCallback;

// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
    public void onArticleSelected(int position);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception
    try {
        mCallback = (OnHeadlineSelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnHeadlineSelectedListener");
    }
}

...

}

2>.将接口实现为Activity.

public static class MainActivity extends Activity
    implements HeadlinesFragment.OnHeadlineSelectedListener{
...

public void onArticleSelected(int position) {
    // The user selected the headline of an article from the HeadlinesFragment
    // Do something here to display that article
}

}

3>.主机activity可以通过findFragmentById()捕获Fragment实例来传递消息到一个片段,然后直接调用片段的public方法

如果两个片段都在同一个Activity,这个activity可以实现一个侦听器(接口)来监听来自片段A的点击并将数据传输到片段B。

 public interface Communicator{
     void onResponse(YourData data);
 }

 public class MainActivity extends AppCompatActivity implements Communicator {

     @Override
     public void onResponse(Your data) {
         // add data to other fragment
     }
 }

为了将数据传递给 activity,您必须从片段内部获取侦听器。

 YourFragment extends Fragment {
    private Communicator communicator;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Object host = getHost();
        if (host instanceof Communicator) {
            communicator= (Communicator) host;
        }
    }

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

然后当列表视图发生onClick 时。你必须做。

onClick {
    communicator.onResponse(//your data here);
}

在另一个片段 B 中,您必须像这样创建一个 newInstance(//您的数据) 方法。

public static YourFragment newInstance(String string) {
    Bundle args = new Bundle();
    args.putString(STRING_KEY, string);
    YourFragment fragment = new YourFragment ();
    fragment.setArguments(args);
    return fragment;
}

然后 onCreate 你可以检索给片段的数据

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String string = getArguments().getString(STRING_KEY);

}

由于 Android 重新创建片段和活动的方式,您不应使用默认构造函数来实例化片段。这就是我们创建 newInstance 方法的原因。