在我的应用程序中使用 viewpager [英] Using viewpager in my application

查看:17
本文介绍了在我的应用程序中使用 viewpager的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的应用程序中使用 viewpager.我试图在一个月内每天都这样做,但我无法实现解决方案.我想创建具有相同列表视图概念但不同数据的页面.这是我的代码:

public final class TestFragment 扩展 ListFragment {私有静态最终字符串 KEY_CONTENT = "TestFragment:Content";ArrayList<HashMap<字符串,对象>>imageliste = new ArrayList<HashMap<String, Object>>();公共类 MyCustomAdapter 扩展 ArrayAdapter<HashMap<String, Object>>{//位图bm;公共 MyCustomAdapter(上下文上下文,int textViewResourceId,ArrayList<HashMap<String,Object>>图像列表){超级(上下文,textViewResourceId,imageliste);//TODO 自动生成的构造函数存根}@覆盖public View getView(int position, View convertView, ViewGroup parent) {//TODO 自动生成的方法存根//return super.getView(position, convertView, parent);查看行 = 转换视图;如果(行==空){LayoutInflater inflater=LayoutInflater.from(getActivity());行=inflater.inflate(R.layout.list,父级,假);}TextView 标签=(TextView)row.findViewById(R.id.text1);label.setText((CharSequence) imageliste.get(position).get("Baslik"));TextView label2=(TextView)row.findViewById(R.id.text2);int boyut =imageliste.get(position).get("Desc").toString().length();label2.setText((CharSequence) imageliste.get(position).get("Desc").toString().substring(0, (boyut/3)*2)+"...");ImageView 图标=(ImageView)row.findViewById(R.id.img);icon.setImageDrawable((Drawable) imageliste.get(position).get("Resim"));返回行;}}公共字符串 getURLContent(字符串 url){尝试 {DefaultHttpClient httpClient = new DefaultHttpClient();HttpGet httpGet = new HttpGet(url);ResponseHandler<字符串>resHandler = new BasicResponseHandler();字符串页面 = httpClient.execute(httpGet, resHandler);返回页面;} 捕捉(ClientProtocolException e){返回 "";} 捕捉(IOException e){返回 "";}}public ArrayList<HashMap<String, Object>>getImageLinks(字符串字符串){ArrayList<HashMap<String, Object>>myBooks2 = new ArrayList<HashMap<String, Object>>();字符串 html = getURLContent(strng);文档 doc = Jsoup.parse(html);元素 divs = doc.getElementsByClass("postBox");for (元素 div : divs) {Element masthead = div.select("img[src].attachment-post-thumbnail").first();String linkHref = masthead.attr("src");元素 masthead2 = div.select("h1").first().select("a").first();String baslik = masthead2.text();元素 masthead3 = div.select("div.textPreview").first().select("p").first();字符串 desc = masthead3.text();//Drawable drawable = LoadImageFromWebOperations();HashMap<字符串,对象>hm = new HashMap<字符串,对象>();hm.put("Resim", LoadImageFromWebOperations(linkHref));hm.put("Baslik", baslik);hm.put("Desc", desc);myBooks2.add(hm);}返回 myBooks2;}私人可绘制 LoadImageFromWebOperations(字符串 url){尝试{InputStream = (InputStream) new URL(url).getContent();Drawable d = Drawable.createFromStream(is, "src name");返回 d;}catch(异常 e){System.out.println("Exc="+e);返回空值;}}公共类 backgroundLoadListView 扩展 AsyncTask<String, Void, Void>{私有 ProgressDialog 对话框 = new ProgressDialog(getActivity());@覆盖受保护的无效onPostExecute(无效结果){//TODO 自动生成的方法存根//适配器 = new MyCustomAdapter(getActivity().getApplicationContext(), R.layout.list, imageliste);//adapter.notifyDataSetChanged();dialog.dismiss();}@覆盖受保护的无效onPreExecute(){//TODO 自动生成的方法存根dialog.setMessage("Yükleniyor...");对话框.show();}@覆盖受保护的无效doInBackground(字符串... arg){//TODO 自动生成的方法存根imageliste=getImageLinks(arg[0]);返回空值;}}公共类 backgroundLoadListView2 扩展 AsyncTask<Void, Void, Void>{@覆盖受保护的无效onPostExecute(无效结果){//TODO 自动生成的方法存根LayoutInflater inflater = LayoutInflater.from(getActivity());查看视图 = inflater.inflate(R.layout.customslidingtabhost, null);ListView listView1=(ListView)view.findViewById(R.id.list);//MyCustomAdapter 适配器 = new MyCustomAdapter(getActivity(), R.layout.list, imageliste);//listView1.setAdapter(适配器);int[] 颜色 = {0xFFFFFFFF, 0xFF87CEEB, 0xFFFFFFFF};//红色的例子listView1.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));listView1.setDividerHeight(2);listView1.setBackgroundColor(Color.WHITE);((PullToRefreshListView) listView1).onRefreshComplete();}@覆盖受保护的无效onPreExecute(){//TODO 自动生成的方法存根}@覆盖受保护的无效doInBackground(无效...参数){//TODO 自动生成的方法存根imageliste=getImageLinks("http://www.teknoinfo.net/kategoriler/haberler/teknoloji-haberleri");返回空值;}}公共静态TestFragment newInstance(字符串内容){TestFragment 片段 = 新的 TestFragment();返回片段;}私有字符串 mContent = "???";@覆盖public View onCreateView(LayoutInflater inflater, ViewGroup 容器, Bundle savedInstanceState) {if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {mContent = savedInstanceState.getString(KEY_CONTENT);}//new backgroundLoadListView().execute("http://www.teknoinfo.net/haberler");MyCustomAdapter 适配器 = new MyCustomAdapter(getActivity().getApplicationContext(), R.layout.list, imageliste);查看视图 = inflater.inflate(R.layout.customslidingtabhost, null);最终 ListView v=(ListView)view.findViewById(R.id.list);/*((PullToRefreshListView) v).setOnRefreshListener(new OnRefreshListener() {公共无效 onRefresh() {//在这里刷新列表.新背景LoadListView2().execute();}});*/int[] 颜色 = {0xFFFFFFFF, 0xFF87CEEB, 0xFFFFFFFF};//红色的例子v.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));v.setDividerHeight(2);v.setBackgroundColor(Color.WHITE);v.setAdapter(适配器);((PullToRefreshListView) v).setOnRefreshListener(new OnRefreshListener() {公共无效 onRefresh() {//在这里刷新列表.//new backgroundLoadListView2().execute();//new backgroundLoadListView().execute("http://www.teknoinfo.net/haberler");}});返回视图;}@覆盖public void onActivityCreated(Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);}@覆盖公共无效 onSaveInstanceState(捆绑 outState){super.onSaveInstanceState(outState);outState.putString(KEY_CONTENT, mContent);}

}

解决方案

很难处理您发布的所有代码(其中大部分与您的问题无关),但据我所知,您有甚至没有从您的代码中设置 ViewPager,或者它隐藏在您未发布的某些 XML 文件中.

您需要做的是创建一个 ViewPager 实例.例如在您的片段的 XML 布局文件中,例如:

现在,在您的 Fragment 中,您创建一个适配器来指定您想要的页面(类似于 ListAdapter 如何将项目指定给 ListView).为此,创建一个继承自 PagerAdapter 的类(您可以在 Fragment 代码中内联执行该操作).例如,类似:

私有类 MyPagerAdapter 扩展 PagerAdapter 实现 TitleProvider {私有 ListView 寻呼机ListView1;私有 ListView 寻呼机ListView2;公共 MyPagerAdapter() {LayoutInflater inflater = getActivity().getLayoutInflater();pagerListView1 = (ListView) inflater.inflate(R.layout.fragment_pagerlist, null);pagerListView2 = (ListView) inflater.inflate(R.layout.fragment_pagerlist, null);}@覆盖公共 int getCount() {返回 2;}@覆盖public Object instantiateItem(View container, int position) {开关(位置){案例0:((ViewPager) 容器).addView(pagerListView1, 0);返回pagerListView1;情况1:((ViewPager) 容器).addView(pagerListView2, 0);返回pagerListView2;}返回空值;}@覆盖public void destroyItem(View container, int position, Object object) {((ViewPager) 容器).removeView((View) 对象);}@覆盖public boolean isViewFromObject(View view, Object object) {返回视图 == (视图) 对象;}@覆盖公共无效完成更新(查看容器){}@覆盖公共 Parcelable saveState() {返回空值;}@覆盖公共无效开始更新(查看容器){}@覆盖public void restoreState(Parcelable state, ClassLoader loader) {}}

请注意,我在此寻呼机中硬编码了 2 个页面/列表.您可以像使用任何其他 ListView 一样填充它们.页面的布局只是一个简单的 ListView,它是从 fragment_pagerlist XML 文件扩展而来的,看起来像:

<?xml version="1.0" encoding="utf-8"?><ListView xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/list"android:layout_height="match_parent"android:layout_width="match_parent"android:cacheColorHint="@color/BackgroundLight"/>

最后,在 onActivityCreated 方法的某个地方绑定 ViewPager 的适配器:

@Overridepublic void onActivityCreated(Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);ViewPager pager = (ViewPager) getView().findViewById(R.id.pager);pager.setAdapter(new MyPagerAdapter());}

请注意,这还没有为您提供 ViewPagerIndicator.查看 Jake Wharton 的优秀图书馆.

如果您希望代码成为完全实现且工作的版本,在 ViewPager 和 ViewPagerIndicator 中有多个列表(和其他视图),请查看用于 Android 项目的开源 RateBeer;特别是 http://code.google.com/p/ratebeerforandroid/source/browse/RateBeerForAndroid/src/com/ratebeer/android/gui/fragments/SearchFragment.java#486 用于现实世界的 PagerAdapter.p>

I want to use viewpager in my application.I'm tried to do this everyday in one month but i can't achieve the solution.I want to create pages with same listview concept but different datas.Here is my code:

public final class TestFragment extends ListFragment {
private static final String KEY_CONTENT = "TestFragment:Content";
ArrayList <HashMap<String, Object>> imageliste = new ArrayList<HashMap<String, Object>>();


public class MyCustomAdapter extends ArrayAdapter<HashMap<String, Object>> {
     //Bitmap bm;

     public MyCustomAdapter(Context context, int textViewResourceId,
       ArrayList<HashMap<String,Object>> imageliste) {
      super(context, textViewResourceId,imageliste);
      // TODO Auto-generated constructor stub


     }

     @Override
     public View getView(int position, View convertView, ViewGroup parent) {
      // TODO Auto-generated method stub
      //return super.getView(position, convertView, parent);

      View row = convertView;


      if(row==null){
       LayoutInflater inflater=LayoutInflater.from(getActivity());
       row=inflater.inflate(R.layout.list, parent, false);
      }

      TextView label=(TextView)row.findViewById(R.id.text1);
      label.setText((CharSequence) imageliste.get(position).get("Baslik"));

      TextView label2=(TextView)row.findViewById(R.id.text2);
      int boyut =imageliste.get(position).get("Desc").toString().length();
      label2.setText((CharSequence) imageliste.get(position).get("Desc").toString().substring(0, (boyut/3)*2)+"...");

      ImageView icon=(ImageView)row.findViewById(R.id.img); 
      icon.setImageDrawable((Drawable) imageliste.get(position).get("Resim"));


      return row;
     }

    }

public String getURLContent(String url)
{
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        ResponseHandler<String> resHandler = new BasicResponseHandler();
        String page = httpClient.execute(httpGet, resHandler);
        return page;
    } catch (ClientProtocolException e) {
        return "";
    }  catch (IOException e) {
        return "";
    }
}
public ArrayList<HashMap<String, Object>> getImageLinks(String strng){

    ArrayList<HashMap<String, Object>> myBooks2 = new ArrayList<HashMap<String, Object>>();


    String html = getURLContent(strng);
    Document doc = Jsoup.parse(html);
    Elements divs = doc.getElementsByClass("postBox");


    for (Element div : divs) {
        Element masthead = div.select("img[src].attachment-post-thumbnail").first();
        String linkHref = masthead.attr("src");

        Element masthead2 = div.select("h1").first().select("a").first();
        String baslik = masthead2.text();

        Element masthead3 = div.select("div.textPreview").first().select("p").first();
        String desc = masthead3.text();

      //Drawable drawable = LoadImageFromWebOperations();
        HashMap<String, Object> hm = new HashMap<String, Object>();
        hm.put("Resim", LoadImageFromWebOperations(linkHref));
        hm.put("Baslik", baslik);
        hm.put("Desc", desc);

        myBooks2.add(hm);



    }

    return myBooks2;
}
private Drawable LoadImageFromWebOperations(String url){
        try{
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "src name");
            return d;
        }catch (Exception e) {
            System.out.println("Exc="+e);
            return null;
        }
    }

public class backgroundLoadListView extends  AsyncTask<String, Void, Void> {
     private ProgressDialog dialog = new ProgressDialog(getActivity());

     @Override
     protected void onPostExecute(Void result) {
      // TODO Auto-generated method stub



        // adapter = new MyCustomAdapter( getActivity().getApplicationContext(), R.layout.list, imageliste);
         //adapter.notifyDataSetChanged();




      dialog.dismiss();
     }


    @Override
     protected void onPreExecute() {
      // TODO Auto-generated method stub
        dialog.setMessage("Yükleniyor...");
        dialog.show();
     }

     @Override
     protected Void doInBackground(String... arg) {
      // TODO Auto-generated method stub

      imageliste=getImageLinks(arg[0]);

      return null;
     }


}
public class backgroundLoadListView2 extends  AsyncTask<Void, Void, Void> {


     @Override
     protected void onPostExecute(Void result) {
      // TODO Auto-generated method stub
      LayoutInflater inflater = LayoutInflater.from(getActivity());
      View view = inflater.inflate(R.layout.customslidingtabhost, null);
      ListView listView1=(ListView)view.findViewById(R.id.list);

      //MyCustomAdapter adapter = new MyCustomAdapter(getActivity(), R.layout.list, imageliste);
      //listView1.setAdapter(adapter);

      int[] colors = {0xFFFFFFFF, 0xFF87CEEB, 0xFFFFFFFF}; // red for the example
      listView1.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
      listView1.setDividerHeight(2);
      listView1.setBackgroundColor(Color.WHITE);

      ((PullToRefreshListView) listView1).onRefreshComplete();

     }


    @Override
     protected void onPreExecute() {
      // TODO Auto-generated method stub

     }

     @Override
     protected Void doInBackground(Void... params) {
      // TODO Auto-generated method stub

      imageliste=getImageLinks("http://www.teknoinfo.net/kategoriler/haberler/teknoloji-haberleri");
      return null;
     }

}
public static TestFragment newInstance(String content) {
    TestFragment fragment = new TestFragment();



    return fragment;
}

private String mContent = "???";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
        mContent = savedInstanceState.getString(KEY_CONTENT);
    }



    //new backgroundLoadListView().execute("http://www.teknoinfo.net/haberler");


    MyCustomAdapter adapter = new MyCustomAdapter( getActivity().getApplicationContext(), R.layout.list, imageliste);
    View view = inflater.inflate(R.layout.customslidingtabhost, null);
    final ListView v=(ListView)view.findViewById(R.id.list);
    /*((PullToRefreshListView) v).setOnRefreshListener(new OnRefreshListener() {
        public void onRefresh() {
            // Do work to refresh the list here.
            new backgroundLoadListView2().execute();

        }
    });*/


    int[] colors = {0xFFFFFFFF, 0xFF87CEEB, 0xFFFFFFFF}; // red for the example
    v.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
    v.setDividerHeight(2);
    v.setBackgroundColor(Color.WHITE);
    v.setAdapter(adapter);

    ((PullToRefreshListView) v).setOnRefreshListener(new OnRefreshListener() {
        public void onRefresh() {
            // Do work to refresh the list here.
            //new backgroundLoadListView2().execute();
        //  new backgroundLoadListView().execute("http://www.teknoinfo.net/haberler");

        }
    });
    return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);






}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString(KEY_CONTENT, mContent);
}

}

解决方案

It is hard to work through all that code you posted (most of which has not to do with your question), but as far as I can tell you have not even set up a ViewPager from your code or it is hidden in some XML file that you didn't post.

What you need to do is create a ViewPager instance. For example in your fragment's XML layout file, like:

<android.support.v4.view.ViewPager
    android:id="@+id/pager" 
    android:layout_width="fill_parent"
    android:layout_height="0dp" 
    android:layout_weight="1" />

Now, in your Fragment you create an adapter that specifies the pages that you want (similarly to how a ListAdapter specifies items to a ListView). For that, create a class (you can do that inline in the Fragment code) that inherits from PagerAdapter. For example, something like:

private class MyPagerAdapter extends PagerAdapter implements TitleProvider {

    private ListView pagerListView1;
    private ListView pagerListView2;

    public MyPagerAdapter() {
        LayoutInflater inflater = getActivity().getLayoutInflater();
        pagerListView1 = (ListView) inflater.inflate(R.layout.fragment_pagerlist, null);
        pagerListView2 = (ListView) inflater.inflate(R.layout.fragment_pagerlist, null);
    }

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

    @Override
    public Object instantiateItem(View container, int position) {
        switch (position) {
        case 0:
            ((ViewPager) container).addView(pagerListView1, 0);
            return pagerListView1;
        case 1:
            ((ViewPager) container).addView(pagerListView2, 0);
            return pagerListView2;
        }
        return null;
    }

    @Override
    public void destroyItem(View container, int position, Object object) {
        ((ViewPager) container).removeView((View) object);
    }

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

    @Override
    public void finishUpdate(View container) {
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

    @Override
    public void startUpdate(View container) {
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {
    }

}

Note that I hard-coded 2 pages/lists in this pager. You can fill those as you would with any other ListView. The layout of the pages is just a simple ListView that is inflated from the fragment_pagerlist XML file, which looks something like:

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/list"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:cacheColorHint="@color/BackgroundLight" />

Finally, you bind the ViewPager's adapter somewhere in your onActivityCreated method:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    ViewPager pager = (ViewPager) getView().findViewById(R.id.pager);
    pager.setAdapter(new MyPagerAdapter());
}

Note that this does not yet give you a ViewPagerIndicator. Check Jake Wharton's excellent library for that.

If you want the code to a fully implemented and working version, with multiple lists (and other views) in a ViewPager and a ViewPagerIndicator, take a look at the open source RateBeer for Android project; specifically http://code.google.com/p/ratebeerforandroid/source/browse/RateBeerForAndroid/src/com/ratebeer/android/gui/fragments/SearchFragment.java#486 for a real-world PagerAdapter.

这篇关于在我的应用程序中使用 viewpager的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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