在我的应用程序中使用viewpager

时间:2011-12-05 22:03:30

标签: android android-viewpager

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

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);
}

}

1 个答案:

答案 0 :(得分:6)

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

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

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

现在,在Fragment中创建一个适配器,指定所需的页面(类似于ListAdapter如何指定ListView的项目)。为此,创建一个继承自PagerAdapter的类(您可以在Fragment代码中内联)。例如,像:

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) {
    }

}

请注意,我在此寻呼机中硬编码了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" />

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

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

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

请注意,这还没有为您提供ViewPagerIndicator。查看杰克沃顿的优秀图书馆。

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