添加子片段父片段withing在Android上ViewPager [英] Adding child Fragment to Parent Fragment withing a ViewPager in Android

查看:255
本文介绍了添加子片段父片段withing在Android上ViewPager的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发,有一些标签的应用程序,像这样

I'm developing an app that has some tabs,something like this

每个标签是一个片段,每个片段显示的文章,类别和其他的一些信息列表视图。 我试图做的是,当我在一个项目挖掘从列表视图中的片段,打开一个新的片段与完整的文章或更多信息即可。我读过,这与嵌套的片段做的,我必须使用的方法 getChildFragmentManager()。我使用的是ViewPager,以显示我的标签片段,这是我的主要活动:

Each tab is a Fragment, and each fragment displays a listview of articles, categories and some other information. What I'm trying to do is to when I tap in an item from the listview in a fragment, open a new Fragment with the full article or more info. I've read that this has to do with nested Fragments, and that I have to use the method getChildFragmentManager(). I am using a ViewPager to display my fragments in the tabs, this is my main Activity:

public class MainActivity extends FragmentActivity{
    private String tabs[]={"Tab1, Tab2,.<other Fragments>..,VideosFragment"};
    ViewPager viewPager=null;
    FragmentManager fragmentManager=getSupportFragmentManager();
    android.support.v4.app.FragmentTransaction ft=fragmentManager.beginTransaction();
    AdapterView adapterView;
    public static final int TIME_ENTRY_REQUEST_CODE=1;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewPager=(ViewPager)findViewById(R.id.pager);
        viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
        public void onPageSelected(int position){
            getActionBar().setSelectedNavigationItem(position);
        }
    });
    viewPager.setAdapter(new AdapterView(fragmentManager));
    viewPager.setOffscreenPageLimit(tabs.length);
    adapterView=new AdapterView(getSupportFragmentManager());
    /*initialization of the action bar: color, icon & title.*/
    final android.app.ActionBar actionbar=getActionBar();
    ColorDrawable color=new ColorDrawable(Color.parseColor("#cd853f"));
    actionbar.setBackgroundDrawable(color);
    actionbar.setTitle("Title");
    ActionBar.TabListener tabListener=new ActionBar.TabListener() {
        @Override
        public void onTabUnselected(Tab tab, FragmentTransaction ft) {

        }   


        @Override
        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            viewPager.setCurrentItem(tab.getPosition());
            ft=getFragmentManager().beginTransaction();
            //ft.replace(layouts[tab.getPosition()], (adapterView.getItem(tab.getPosition()));
            ft.commit();

        }

        @Override
        public void onTabReselected(Tab tab, FragmentTransaction ft) {  

        }
    };
    /*Displaying Tabs for the app */
    for(int i=0;i<tabs.length;i++)
        actionbar.addTab(actionbar.newTab().setText(tabs[i]).setTabListener(tabListener));
    actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            actionbar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });
}

}
修改,当我在ListView的项目挖掘,我想开一个新的片段,这是我的适配器为ListView:

} and when I tap in an item of a listview, I want to open a new Fragment, this is my adapter for the listView:

public class ItemAdapter extends BaseAdapter implements OnItemClickListener{
Item item=new Item();
private ArrayList<Item> news=new ArrayList<Item>();
private static final int NO_PICTURE_VIEW=0;
private static final int PICTURE_VIEW=1;

public ItemAdapter(Context context,ArrayList<Item> items) {
    super();
    news.addAll(items);
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return news.size();

}

@Override
public Item getItem(int index) {
    // TODO Auto-generated method stub
    return getItem(index);
}

@Override
public long getItemId(int index) {
    // TODO Auto-generated method stub
    return index;
}

public int getViewTypeCount() {
    return 2;
}

public int getItemViewType(int position) {
    Item article=news.get(position);
    //  if(article.getImageUrl()!=null&&!article.getImageUrl().equals("")&&article.getImageUrl().indexOf("no_pic.png")==-1)//if there's no pic    
    if(article.getImage()!=null)      
        return PICTURE_VIEW;
      else
          return NO_PICTURE_VIEW;
}
@Override
public View getView(int index, View view, ViewGroup parent) {
    item=news.get(index);
    int type=getItemViewType(index);
        if(view==null){
            LayoutInflater inflater=LayoutInflater.from(parent.getContext());
            if(type==NO_PICTURE_VIEW){
                view=inflater.inflate(R.layout.item_no_picture_list,parent,false);
                TextView titleView=(TextView)view.findViewById(R.id.titleNoPicture);
                titleView.setText(item.getTitle());
            }
            else{
                view=inflater.inflate(R.layout.item_picture_list,parent,false);
                TextView titleView=(TextView)view.findViewById(R.id.titleArticle);
                ImageView image=(ImageView)view.findViewById(R.id.imageItem);
                titleView.setText(item.getTitle());
                image.setImageBitmap(item.getImage());
            }
    }

    return view;
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
    Log.d("ItemAdapter","clicked on "+position);
}

}

这是在ViewPager的片段之一:

This is one of the fragments in the ViewPager:

public class VideosFragment extends Fragment{

static ListView listvideo;
ItemAdapter itemAdapter;
Context context;
Activity activity;
FragmentManager fm=getChildFragmentManager();
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
       super.onCreateView(inflater, container, savedInstanceState);
       View view=inflater.inflate(R.layout.videos_activity, container,false);
       listvideo=(ListView)view.findViewById(R.id.videoslist);
       context=getActivity();
       setRetainInstance(true); 
       return view;
    }

public void onViewCreated(View view, Bundle savedInstanceState){
    super.onViewCreated(view, savedInstanceState);
    ViewPager vp=(ViewPager)view.findViewById(R.id.pager);
    vp.setAdapter(new AdapterView(fm));
}

public void displayVideos(final List<Item> videos){
    try {        
         if(videos==null || videos.size()==0){
            Log.d("videos activity","the list is null!!");          
         }  
     } catch (Exception e) {
         e.printStackTrace();
     }
    for(int i=0;i<videos.size();i++){

    }
    itemAdapter=new ItemAdapter(context,(ArrayList<Item>) videos);
    listvideo.setAdapter(itemAdapter);
    listvideo.setOnItemClickListener(new OnItemClickListener(){
        @Override
        public void onItemClick(android.widget.AdapterView<?> parent,
                View view, int position, long id) {
            Log.d("HomeActivity","Tapped on "+position);
            //FragmentTransaction ft=fm.beginTransaction();
            //Fragment vp=new VideoPlayer();
            //ft.add(R.id.videoview, vp);
            ///ft.addToBackStack("VideosActivity");
            //ft.commit();
        }
    });
}   

public static class MyAdapter extends FragmentPagerAdapter {

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

    @Override
    public int getCount() {
        return 4;
    }

    @Override
    public Fragment getItem(int position) {

        return new VideoPlayer();//ChildFragment
    }
}
}

注释行的fragmenttransaction,之后给了我一个NPE的线条,所以我想我失去了一些东西。的VideoPlayer是ChildFragment,在那一刻我只希望能够显示片段没有的信息,只知道它是如何工作。这是我的适配器的片段:

The commented lines for fragmenttransaction and the lines after that gave me a NPE, so I guess I'm missing something. VideoPlayer is the ChildFragment, and at the moment I only want to be able to display the fragment without info, just to know how it works. This is my adapter for the fragments:

class AdapterView extends FragmentPagerAdapter{
public static int NUM_ITEMS=3;
Tab1 tab1=new Tab1();
    Tab2 tab2=new Tab2();
VideoFragment va=new VideoFragment();

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

@Override
public Fragment getItem(int i) {
    Log.d("FRAGMENT","EN: "+i);
    switch(i){
    case 0:
        return tab1;
    case 1:
        return tab2;
    case 2:
            return va;
    default:
        return null;
    }
}

@Override
public int getCount() {
    return  NUM_ITEMS;
}

}

我还没有发现什么,我正在寻找一个教程,所以我希望你们中的一些可以帮助我理解它是如何工作的。我知道这是可能的,因为在Android 4.2 API允许它。我只是想知道嵌套的片段是如何工作的,以及如何使用它们我的应用程序需要它的方式。任何信息都是AP preciated,谢谢。

I haven't found a tutorial for what I'm looking for, so I hope some of you can help me understand how it works. I know it's possible, since the Android API 4.2 allows it. I just want to know how the nested fragments work, and how to use them the way my apps needs it. Any information is appreciated, thanks.

推荐答案

如果你想要的是更换一个片段与另一片段viewpager里面,看一看的这个。不过我建议你创建另一个片段(容器),并移动viewpager和片段这个新的片段里面:

If what you want is replace a fragment inside the viewpager with another fragment, take a look at this. However I would suggest you to create another Fragment (a container), and move your viewpager and fragments inside of this new fragment:

当用户点击列表中的项目通过这种方式,可以取代 MainFragment 详细信息片段

This way when the user clicks an item of a list, you can replace the MainFragment with a Details Fragment.

关于 ChildFragmentManager(),当你嵌套片段使用它。如果你改变你的执行情况我建议,你需要一个ChildFragmentManager传递到您的PagerAdapter:

About the ChildFragmentManager(), it is used when you have nested fragments. If you change your implementation as I suggested, you would need to pass a ChildFragmentManager to your PagerAdapter:

viewPager.setAdapter(new AdapterView(getChildFragmentManager()));

VideosFragment 约code你的注释行另一件事。让你的活动提交的,而不是做它里面的片段片段交易。为了更好的说明,请参阅这个

Another thing about your commented lines of code inside VideosFragment. Make your activity commit the fragment transaction instead of doing it inside the Fragment. For a better explanation, read this.

这篇关于添加子片段父片段withing在Android上ViewPager的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆