10.Fragment与ViewPager

1.Fragment简单用法
建left和right的xml文件:



    

建立left和right的类:

public class Left extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inf, ViewGroup container, Bundle savedInstanceState) {
        View view = inf.inflate(R.layout.left,container,false);
        return view;
    }
}
public class Right1 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inf, ViewGroup container, Bundle savedInstanceState) {
        View view = inf.inflate(R.layout.right1,container,false);
        return view;
    }
}

修改activity_main.xml:




    

    


动态添加Fragment:
建Right1.xml:




    

建Right1类:

public class Right1 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inf, ViewGroup container, Bundle savedInstanceState) {
        View view = inf.inflate(R.layout.right1,container,false);
        return view;
    }
}

修改activity_main.xml:




    

    

    

修改MainActivity:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.button);
        replaceFragment(new Right());
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                replaceFragment(new Right1());
            }
        });
    }

    private void replaceFragment(Fragment fra) {
        FragmentManager fraMan = getSupportFragmentManager();
        FragmentTransaction tra = fraMan.beginTransaction();
        tra.replace(R.id.right_layout,fra);
        tra.commit();
    }
}

完成。

模拟返回栈:

tra.addToBackStack(null);

活动调用碎片中方法:

Right rigFra = (Right) getFragmentManager().findFragmentById(R.id.right);

碎片调用活动中方法:
在碎片中:

MainActivity act = (MainActivity) getActivity();

同时也可以使用这个方法获取Context。

fragment生命周期:onAttach(),onCreate(),onCreateView(),onActivityCreate(),onStart(),onResume(),onPause(),onStop(),onDestroyView(),onDestroy(),onDetach()

根据设备屏幕大小方向动态选择加载哪个布局:
修改activity_main.xml文件:


    

在res目录下新建layout_large文件夹,新建名为:activity_main.xml的布局:



    
    

最小宽度限定符:
新建layout-sw600dp文件夹。

综合应用——新闻应用:
1。build.gradle 中添加recyclerview支持
2.新建新闻类:News

public class News {
    private String title;
    private String content;
    public String getTitle(){
        return title;
    }
    public void setTitle(String title){
        this.title = title;
    }
    public String getContent(){
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
}

3.新建内容布局文件news_content_frag.xml




    
        

        

        

    

    

4.新建内容布局类NewsContentFragment,继承Fragment:

public class NewsContentFragment extends Fragment {
    private View view;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.news_content_frag,container,false);
        return view;
    }

    public void refresh(String newsTitle,String newsContent) {
        View visibilityLayout = view.findViewById(R.id.visibility_layout);
        visibilityLayout.setVisibility(View.VISIBLE);
        TextView newsTitleText = (TextView)view.findViewById(R.id.news_title);
        TextView newsContentText = (TextView)view.findViewById(R.id.news_content);
        newsTitleText.setText(newsTitle);
        newsContentText.setText(newsContent);
    }
}

5.对小屏模式支持,新建Activity:NewsContentAcitivty和相应布局文件news_content.xml:




    

public class NewsContentActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_content);
        String newsTitle = getIntent().getStringExtra("news_title");
        String newsContent = getIntent().getStringExtra("news_content");
        NewsContentFragment newsContentFragment = (NewsContentFragment) getSupportFragmentManager().findFragmentById(R.id.news_content_fragment);
        newsContentFragment.refresh(newsTitle,newsContent);
    }

    public static void actionStart(Context context,String newsTitle,String newsContent) {
        Intent intent = new Intent(context,NewsContentActivity.class);
        intent.putExtra("news_title",newsTitle);
        intent.putExtra("new_content",newsContent);
        context.startActivity(intent);
    }
}

6.新建用于显示新闻列表的布局,news_title_frag.xml:

?xml version="1.0" encoding="utf-8"?>


    

7.新建news_item.xml作为recyclerview的子布局:



8.新建NewsTitleFragment作为展示新闻列表的碎片:

public class NewsTitleFragment extends Fragment {
    private boolean isTwoPane;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.news_title_frag,container,false);
        RecyclerView newsTitleRecyclerView = (RecyclerView) view.findViewById(R.id.news_title_recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        newsTitleRecyclerView.setLayoutManager(layoutManager);
        NewsAdapter adapter = new NewsAdapter(getNews());
        newsTitleRecyclerView.setAdapter(adapter);
        return view;
    }

    private List getNews(){
        List newsList = new ArrayList<>();
        for(int i=1;i<=50;i++) {
            News news = new News();
            news.setTitle("This is news title" + i);
            news.setContent("content" + i);
            newsList.add(news);
        }
        return newsList;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getActivity().findViewById(R.id.news_content_layout) != null) {
            isTwoPane = true;
        } else {
            isTwoPane = false;
        }
    }

    class NewsAdapter extends RecyclerView.Adapter {
        private List mNewsList;

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView newsTitleText;
            public ViewHolder(View view) {
                super(view);
                newsTitleText = (TextView)view.findViewById(R.id.news_title);
            }
        }

        public NewsAdapter(List newsList) {
            mNewsList = newsList;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item,parent,false);
            final ViewHolder holder = new ViewHolder(view);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    News news = mNewsList.get(holder.getAdapterPosition());
                    if (isTwoPane) {
                        NewsContentFragment newsContentFragment = (NewsContentFragment)getFragmentManager().findFragmentById(R.id.news_content_fragment);
                        newsContentFragment.refresh(news.getTitle(),news.getContent());
                        news.getContent();
                    } else {
                        NewsContentActivity.actionStart(getActivity(),news.getTitle(),news.getContent());
                    }
                }
            });
            return holder;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder,int position) {
            News news = mNewsList.get(position);
            holder.newsTitleText.setText(news.getTitle());
        }

        @Override
        public int getItemCount() {
            return mNewsList.size();
        }
    }
}

9.修改activity_main.xml:




    

10.新建layout-sw600dp支持大屏,在此文件夹下新建activity_main:




    
    

        

    


2.ViewPager

简单用法,修改activity_main.xml,新建三个滑动页面:page0,page1,page2:



    






    

新建MyViewpager类和修改MainActivity:

public class MyViewpagerAdapter extends PagerAdapter {
    private List pageList;
    public MyViewpagerAdapter(List pageList) {
        this.pageList = pageList;
    }

    @Override
    public int getCount() {
        return pageList.size();
    }

    @Override
    public boolean isViewFromObject(View view,Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container,int position) {
        container.addView(pageList.get(position));
        return pageList.get(position);
    }

    @Override
    public void destroyItem(ViewGroup container,int position,Object object) {
        container.removeView(pageList.get(position));
    }
}

public class MainActivity extends AppCompatActivity {

    private View page0,page1,page2;
    private List pageList;
    private ViewPager mViewPager;
    private MyViewpagerAdapter mMyViewpagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LayoutInflater inflater = getLayoutInflater();
        page0 = inflater.inflate(R.layout.page0,null);
        page1 = inflater.inflate(R.layout.page1,null);
        page2 = inflater.inflate(R.layout.page2,null);
        pageList = new ArrayList<>();
        pageList.add(page0);
        pageList.add(page1);
        pageList.add(page2);
        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        mMyViewpagerAdapter = new MyViewpagerAdapter(pageList);
        mViewPager.setAdapter(mMyViewpagerAdapter);
    }
}

你可能感兴趣的:(10.Fragment与ViewPager)