在我的应用程序中使用viewpager我的、应用程序、viewpager

2023-09-12 09:58:07 作者:深意

我想用viewpager在我application.I'm试图每天都这样做一个月,但我不能达到solution.I希望创建具有相同的列表视图概念的网页,但不同的datas.Here是我的code:

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

}

推荐答案

这是很难c您发布工作,通过所有$ C $(其中大部分还没有做你的问题),但据我可以告诉你还没有成立了ViewPager从code或它隐藏在一些XML文件,你没有张贴。

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.

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

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" />

现在,在你的片段,你创建一个适配器,指定你想要的页面(类似于如何ListAdapter指定项目到ListView)。为此,创建一个类(你可以做的片段code内联),它继承自PagerAdapter。例如,是这样的:

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

}

请注意,我在这个寻呼机硬codeD 2页/列表。您可以填补这些,你会与任何其他的ListView。页面的布局仅仅是一个简单的ListView从fragment_pagerlist XML文件充气,它看起来是这样的:

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" />

最后,你的地方绑定ViewPager的适配器在onActivityCreated方式:

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

请注意,这并没有给你一个ViewPagerIndicator。检查杰克沃顿商学院的优秀库的。

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

如果你想在code到全面实施,工作版本,与多个列表(和其他视图)在ViewPager和ViewPagerIndicator,看看开源RateBeer的Andr​​oid项目;特别是http://$c$c.google.com/p/ratebeerforandroid/source/browse/RateBeerForAndroid/src/com/ratebeer/android/gui/fragments/SearchFragment.java#486对现实世界的PagerAdapter

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.