1

В моем приложении я хочу поместить ListView в первый фрагмент, и я хочу перейти к новому фрагменту, когда я нажал на элемент, чтобы каждый элемент имел свои собственные данные в моем коде.как перейти к новому фрагменту на OnItemClickListener()

Я реализовал его для перехода на другую активность, но теперь мой менеджер говорит, что он должен перейти к другому фрагменту вместо другого действия. Я новичок в мире фрагментов, и я не знаю, как это сделать. Менеджер говорит, что я могу использовать фрагмент списка, но я не нашел полезного кода.

Это мой код:

public class MainActivity extends FragmentActivity { 

    SectionsPagerAdapter mSectionsPagerAdapter; 
    static ProgressDialog pd ; 
    ViewPager mViewPager; 
    List<Fragment> fragments ; 

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

     // Create the adapter that will return a fragment for each of the three 
     // primary sections of the app. 
     fragments = new Vector<Fragment>(); 

     fragments.add(Fragment.instantiate(this, FragmentOne.class.getName())); 
     fragments.add(Fragment.instantiate(this, FragmentTwo.class.getName())); 
     fragments.add(Fragment.instantiate(this, FragmentThree.class.getName())); 
     fragments.add(Fragment.instantiate(this, FragmentFour.class.getName())); 
     fragments.add(Fragment.instantiate(this, FragmentFive.class.getName())); 
     fragments.add(Fragment.instantiate(this, FragmentSix.class.getName())); 

     mSectionsPagerAdapter=new SectionsPagerAdapter(super.getSupportFragmentManager()); 

     // Set up the ViewPager with the sections adapter. 
     mViewPager = (ViewPager) findViewById(R.id.pager); 
     pd = new ProgressDialog(this); 

     mViewPager.setAdapter(mSectionsPagerAdapter); 

     // 


    } 

    public class SectionsPagerAdapter extends FragmentPagerAdapter { 

     public SectionsPagerAdapter(FragmentManager fm) { 

      super(fm); 
     } 

     @Override 
     public Fragment getItem(int position) { 
      int _pos = position % 6; 
      return fragments.get(_pos); 

     } 

     @Override 
     public int getCount() { 
      // Show 3 total pages. 
      return 6; 
     } 

     @Override 
     public CharSequence getPageTitle(int position) { 
      final String title_section4="Section4"; 
      final String title_section5="Section5"; 
      final String title_section6="Section6"; 
      final String title_section1="Section1"; 
      final String title_section2="Section2"; 
      final String title_section3="Section3"; 

      Locale l = Locale.getDefault(); 
      switch (position) { 


       case 0: 
        return title_section1.toUpperCase(l); 

       case 1: 
        return title_section2.toUpperCase(l); 

       case 2: 
        return title_section3.toUpperCase(l); 

       case 3: 
        return title_section4.toUpperCase(l); 
       case 4: 
        return title_section5.toUpperCase(l); 
       case 5: 
        return title_section6.toUpperCase(l); 

      } 
      return null; 
     } 
    } 


    public static class FragmentOne extends Fragment { 

     ArrayList<String> ar; 
     ArrayAdapter<String> ad ; 
     ListView lv ; 
     TextView tv; 


     public FragmentOne() { 
     } 

     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
      View rootView = inflater.inflate(R.layout.one, container, false); 
      tv = (TextView) rootView.findViewById(R.id.mywidget); 

      tv.setSelected(true); 
      ar = new ArrayList<String>(); 
      lv = (ListView) rootView.findViewById(R.id.listView1); 
      for (int i = 0 ; i< 10 ; i++){ 

       ar.add("My Item " + String.valueOf(i)); 

      } 
      ad = new ArrayAdapter<String> 
        (getActivity().getApplicationContext(), android.R.layout.simple_dropdown_item_1line, 
          ar); 

      lv.setAdapter(ad); 
      lv.setOnItemClickListener(new OnItemClickListener() { 
       public void onItemClick(AdapterView<?> parent, View view, 
             int position, long id) { 
        Toast t = Toast.makeText(getActivity(), "Message", 
          Toast.LENGTH_SHORT); 
        t.show(); 

        Intent i = new Intent(getActivity(), tst.class); 


        startActivity(i); 

       } 
      }); 


      return rootView; 
     } 
    } 


    public static class FragmentTwo extends Fragment { 


     public FragmentTwo() { 
     } 

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

      View rootView = inflater.inflate(R.layout.two, container, false); 

      return rootView; 
     } 
    } 


    public static class FragmentThree extends Fragment { 

     public FragmentThree() { 
     } 

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

      View rootView = inflater.inflate(R.layout.three, container, false); 

      return rootView; 
     } 
    } 



    public static class FragmentFour extends Fragment { 


     public FragmentFour() { 
     } 

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

      View rootView = inflater.inflate(R.layout.four, container, false); 
      return rootView; 
     } 
    } 



    public static class FragmentFive extends Fragment { 


     public FragmentFive() { 
     } 

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

      View rootView = inflater.inflate(R.layout.five, container, false); 
      return rootView; 
     } 
    } 


    public static class FragmentSix extends Fragment { 



     public FragmentSix() { 
     } 

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

      View rootView = inflater.inflate(R.layout.six, container, false); 
      return rootView; 




     } 
    } 
} 
+1

Я не вижу никаких ListFragments здесь. Вы посмотрели [Документацию разработчика Android для ListFragment] (http://developer.android.com/reference/android/app/ListFragment.html))? Кроме того, в будущем, пожалуйста, сделайте ваши образцы кода следуйте [Руководствам SSCCE] (http://sscce.org/). Например, в том числе 6 фрагментов фрагментов не помогаете вашему вопросу. –

+0

@ Tanis.7x Я не хочу иметь список фрагментов, которые я хочу добавить к новому фрагменту, когда меня щелкнули по любому элементу из списка, обратите внимание, что каждый элемент в виде списка имеет свою собственную информацию, но новый фрагмент должен показать детали в соответствии с нажатым –

ответ

0

Использование пейджера и дают целочисленный индекс для каждого фрагмента затем используйте следующий код в itemclick

ViewPager pager; 
pager.setCurrentItem(index, true); 
0

Вы должны заменить фрагмент с помощью транзакции

Посмотреть здесь:

http://developer.android.com/guide/components/fragments.html#Example

Проверьте ShowDetails метод (индекс ИНТ) класса TitlesFragment:

FragmentTransaction ft = getFragmentManager().beginTransaction(); 
if (index == 0) { 
ft.replace(R.id.details, details); 
} else { 
ft.replace(R.id.a_item, details); 
} 
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); 
ft.commit();