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

时间:2016-10-10 08:09:45

标签: android interface communicator

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

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

}
}

MainActivity

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

2 个答案:

答案 0 :(得分:0)

与其他活动片段进行沟通

1&gt;。定义接口

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&gt;。将界面实现为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&gt;。主机活动可以通过使用findFragmentById()捕获Fragment实例来将消息传递给片段,然后直接调用片段的公共方法

答案 1 :(得分:0)

如果两个片段都在同一个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
     }
 }

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

 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方法的原因。