android – ViewPager指标与自定义ListView

首先,我为我的英语道歉,因为它不是很好.谢谢.
我的应用程序包含很少的带适配器的ListWiews. ListView的数据来自位于Internet中的已解析XML文件.
现在我有一个TabHost,每个选项卡中有三个选项卡和不同的ListView.
我想将TabHost更改为新的和轻微的方法–Jake Wharton的ViewPager指标(https://github.com/JakeWharton/Android-ViewPagerIndicator),因为有很棒的滑动效果.

我试图在示例项目中包含此代码,并且运行良好.
现在我在ViewPager的一个片段中有一个ListView,在另外两个片段中有一个简单的TextView.它正在发挥作用.

ViewPagerAdapter代码如下所示:

package com.formatbce.pager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.viewpagerindicator.TitleProvider;

public class ViewPagerAdapter extends PagerAdapter
implements TitleProvider
{
    private int[] scrollPosition = new int[titles.length];
private static String[] titles = new String[]
{
    "News",
    "Bio",
    "Music"
};
private final Context context;

public ViewPagerAdapter( Context context )
{
    this.context = context;
    for ( int i = 0; i < titles.length; i++ )
    {
        scrollPosition[i] = 0;
    }
}

@Override
public String getTitle( int position )
{
    return titles[ position ];
}

@Override
public int getCount()
{
    return titles.length;
}

@Override
public Object instantiateItem( View pager, final int position )
{
    if (position == 0) {
     ListView v = new ListView( context );
        String[] from = new String[] { "str" };
        int[] to = new int[] { android.R.id.text1 };
        List<Map<String, String>> items =
            new ArrayList<Map<String, String>>();
        for ( int i = 0; i < 20; i++ )
        {
            Map<String, String> map =
                new HashMap<String, String>();
            map.put( "str", String.format( "Item %d", i + 1 ) );
            items.add( map );
        }
        SimpleAdapter adapter = new SimpleAdapter( context, items,
            android.R.layout.simple_list_item_1, from, to );
        v.setAdapter( adapter );
        ( (ViewPager) pager ).addView( v, 0 );
        v.setOnScrollListener( new OnScrollListener()
        {

            @Override
            public void onScroll( AbsListView view,
                int firstVisibleItem,
                int visibleItemCount,
                int totalItemCount )
            {
                scrollPosition[ position ] = firstVisibleItem;
            }



            @Override
            public void onScrollStateChanged(AbsListView view,
                    int scrollState) {
                // TODO Auto-generated method stub

            }
        } );
        return v;}
    else {
        TextView v = new TextView( context );
        v.setText( titles[ position ] );
        ((ViewPager)pager).addView( v, 0 );
        return v;
    }
}

@Override
public void destroyItem( View pager, int position, Object view )
{
    if (position == 0){
    ( (ViewPager) pager ).removeView( (ListView) view );}
    else {
    ( (ViewPager) pager ).removeView( (TextView) view );}

}

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

@Override
public void finishUpdate( View view ) {}

@Override
public void restoreState( Parcelable p, ClassLoader c ) {}

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

@Override
public void startUpdate( View view ) {}
}

因此,使用ListView示例一切都很好.

但是当我尝试将自定义ListView放在那里时,我的问题就开始了.在我的旧项目中,这个ListView有代码:

package com.formatbce.mdrive;

import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;

public class Concerts extends ListActivity {

private ArrayList<Rss_PostItem> messages;
private Rss_PostAdapter adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        messages = savedInstanceState.getParcelableArrayList("messages");
        adapter = new Rss_PostAdapter(Concerts.this, R.layout.post_entry,
                messages);
        setListAdapter(adapter);
    } else
        new GetParserResult().execute();
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    Intent postActivity = new Intent(this, Rss_PostActivity.class);
    Bundle store = new Bundle();
    store.putString("title", messages.get(position).title);
    store.putString("description", messages.get(position).description);
    store.putString("link", messages.get(position).link);
    postActivity.putExtras(store);
    startActivity(postActivity);
}

protected void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putParcelableArrayList("messages", messages);
}

private class GetParserResult extends
        AsyncTask<Context, Integer, ArrayList<Rss_PostItem>> {
    private ProgressDialog loadingDialog;
    private Concerts_Parser parser;

    protected void onPreExecute() {
        parser = new Concerts_Parser();
        loadingDialog = ProgressDialog.show(Concerts.this, "",
                "Loading concerts list...", true);
    }

    @Override
    protected ArrayList<Rss_PostItem> doInBackground(Context... arg0) {
        return parser.parse();
    }

    protected void onPostExecute(ArrayList<Rss_PostItem> result) {
        if (result == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    Concerts.this);
            builder.setMessage(
                    "Cannot load list... \nIs Internet ON?")
                    .setCancelable(false)
                    .setPositiveButton("Ok",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    dialog.cancel();
                                    loadingDialog.dismiss();
                                }
                            });
            AlertDialog alert = builder.create();
            alert.show();
        } else {
            messages = result;
            loadingDialog.dismiss();
            adapter = new Rss_PostAdapter(Concerts.this,
                    R.layout.post_entry, messages);
            setListAdapter(adapter);
        }
    }
}
   }

所以我不明白,如何在ViewPager代码中正确使用它.
我尝试设置ListFragment,但对我来说这是一个非常新的,所以我无法让它工作.

Google也无法帮助我,就像各种开发人员论坛一样.

确实,问题是:如何在ViewPager中显示自定义ListView?

谢谢,我希望你能得到帮助.

UPD:

感谢第一个答案,我尝试将我的一个活动转换为片段,使用本教程:http://www.e-nature.ch/tech/?p=55.

首先,这是一个我无法通过的错误:这个变量没有转换,我不知道,如何让它工作.

dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

现在另外一件事:当我试图将结果片段放到FragmentPagerAdapter时 – 我在这里找不到正确的代码:

@Override
public Fragment getItem(int arg0) {
    // TODO Auto-generated method stub
    return ?????????;
}

请告诉我,这种方法必须返回什么?
谢谢!

最佳答案
你说

i have one TabHost with three tabs, and different ListView in each tab

我假设你有三个不同的listActivity,它传递给tabHost.所以将三个活动转换为三个碎片.

根据以下示例代码更改您的ViewPagerAdapter

class GoogleMusicAdapter extends FragmentPagerAdapter implements
        TitleProvider {
    public GoogleMusicAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
                    if(position ==0 )
        // return your Fragment1 
                    else if(position==1)
                    // return your Fragment2
                    else
                    // return fragment3
    }

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

    @Override
    public String getTitle(int position) {
        if(position ==0 )
                    return "One"
                    else if(position ==1)
                    return "two"
                    else
                    return "three"
    }
}

转载注明原文:android – ViewPager指标与自定义ListView - 代码日志