带有片段

时间:2017-03-03 12:49:45

标签: android listview android-fragments android-tablayout

所以,我有一个名为“Onglets”的标签活动。在那里我创建了2个片段(OngletCours和OngletNotes)。

在OngletCours中我有一个ListView,我希望能够交换到我的第二个片段(OngletNotes),即我点击的项目的名称(setonItemClickListener)。但是,当我点击一个项目时,它会转到我的第二个片段。它保留在第一个片段中,但第二个片段的内容出现在我当前的片段(OngletCours)中。我的意思是,当我在第一个标签中点击我的listView的项目

时,我想进入第二个标签

在点击项目之前,我的应用程序如下所示:

Before clicking on an Item

单击项目后,您可以看到文本“Ongletdesrésultats”插入顶部。但我不想那样。我想转到第二个标签“Notes”。 After clicking on an Item

这是我的TabbedActivity

中的代码

Onglets.java 公共类Onglet扩展了AppCompatActivity {

DatabaseHelper dbhelper = new DatabaseHelper(this);
/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);



}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_onglets, menu);
    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


    return super.onOptionsItemSelected(item);
}
/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

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

            View rootView = inflater.inflate(R.layout.ongletcours, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
            return rootView;

    }
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */

//méthode qui retourne une Fragment qui correspond à chacun des onglets
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        //switch qui retourne la position des différents Onglets
      switch (position){
          case 0:
              OngletCours onglet1 = new OngletCours();
              return onglet1;
          case 1:
              OngletNotes onglet2 = new OngletNotes();
              return onglet2;
          default:
              return null;
      }
    }

    //méthode qui retourne le nombre d'onglets disponibles
    @Override
    public int getCount() {
        // Show 3 total pages.
        return 2;
    }

    //méthode qui sert à définir un titre à chaque Onglet
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "COURS";
            case 1:
                return "NOTES";

        }
        return null;
    }
}

}

这是2个片段的代码。

OngletCours.java (我只向您展示setOnItemClickListener,因为它出现问题的地方)

ListView l1 = (ListView) rootView.findViewById(R.id.ListCours);
    //ce Listener permet de détecter si on clique sur un élément de la liste
    l1.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            OngletNotes targetFragment = OngletNotes.newInstance();
            FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
            transaction.addToBackStack(null);
            transaction.replace(R.id.fragment_holder, targetFragment)
                    .commit();
        }

    });

OngletNotes.java

public class OngletNotes extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.ongletnotes, container, false);
        return rootView;
    }

    public static OngletNotes newInstance() {
        OngletNotes fragment = new OngletNotes();
        // put values which you want to pass to fragment
        // Bundle args = new Bundle();
        // fragment.setArguments(args);
        return fragment;
    }
}

请帮我解决这个问题,并提前感谢你!

2 个答案:

答案 0 :(得分:0)

您可以参考此方法将数据从一个片段传送到另一个片段

   //Put the value
YourNewFragment ldf = new YourNewFragment ();
Bundle args = new Bundle();
args.putString("YourKey", "YourValue");
ldf.setArguments(args);

//Inflate the fragment
getFragmentManager().beginTransaction().add(R.id.container, ldf).commit();

在新片段的onCreateView中:

    //Retrieve the value
String value = getArguments().getString("YourKey");

答案 1 :(得分:0)

  

单击项目后,您可以看到文本“Onglet des   résultats“,插在顶部。但我不想那样。我想去   到第二个标签“注释”

您同时创建了2个片段,因此,您的片段OngletNotes已初始化,您可以将片段OngletCours中的数据传递到第二个片段。您创建方法changeData(String data)。    上面的代码创建了另一个片段,而不是当前片段,所以像你看到的图像2

public class OngletNotes extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.ongletnotes, container, false);
        return rootView;
    }

    public static OngletNotes newInstance() {
        OngletNotes fragment = new OngletNotes();
        // put values which you want to pass to fragment
        // Bundle args = new Bundle();
        // fragment.setArguments(args);
        return fragment;
    }

public void changeData(String data)
     //  DO something
}

现在,在处理片段OngletCours中的点击侦听器后,您可以将数据传递到片段OngletNotes

l1.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            OngletNotes fragment = ((Onglets)getActviity())getOngletNotes ();
            if(fragment != null) {
             fragment.changeData("Set you value to send here");
            }
           ((Onglets)getActviity()).goToFragment(1);
        }

    });

在你Onglets活动中

   public OngletNotes getOngletNotes () {
            return (OngletNotes ) getSupportFragmentManager().findFragmentByTag(
                    "android:switcher:" + R.id.viewPager + ":" + 1);
        }

public void goToFragment (int index) {
            mViewPager.setCurrentItem(index)
                    }