android – 如何在ViewPager中使用cursorLoader?

前端之家收集整理的这篇文章主要介绍了android – 如何在ViewPager中使用cursorLoader?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
I have a `cursorLoader` which is working fine.

问题是我没有像我想的那样使用它,我将数据从cursorLoader加载到arrayLists然后使用列表.

我发现这个教程展示了如何将cursorLoader与viewPager一起使用,但我不明白如何实现它.

http://tumble.mlcastle.net/post/25875136857/bridging-cursorloaders-and-viewpagers-on-android

我有一个片段,看起来像这样:

public class FirstFragment extends Fragment {
    MapView mapView;
    GoogleMap map;
    // Store instance variables
    private String email,about,imagepath,latitude,longitude;
    Button getDirections;

    // newInstance constructor for creating fragment with arguments
    public static FirstFragment newInstance(String email,String about,String imagepath,String latitude,String longitude) {
        FirstFragment fragmentFirst = new FirstFragment();
        Bundle args = new Bundle();
        args.putString("email",email);
        args.putString("about",about);
        args.putString("imagepath",imagepath);
        args.putString("latitude",latitude);
        args.putString("longitude",longitude);
        fragmentFirst.setArguments(args);
        return fragmentFirst;
    }

    // Store instance variables based on arguments passed
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        email = getArguments().getString("email");
        about = getArguments().getString("about");
        imagepath = getArguments().getString("imagepath");
        latitude = getArguments().getString("latitude");
        longitude = getArguments().getString("longitude");
    }

    // Inflate the view for the fragment based on layout XML
    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container,final Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.zzfragment_pager_items,container,false);
        ImageView imageView = (ImageView) view.findViewById(R.id.listpager_imageView);
        TextView about = (TextView) view.findViewById(R.id.listpager_text);
        TextView emaill = (TextView) view.findViewById(R.id.listpager_title);
        about.setText(this.about);
        emaill.setText(this.email);

        ImageLoader imageLoader = ImageLoader.getInstance();
        DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
                .cacheOnDisc(true).resetViewBeforeLoading(true)
                .considerExifParams(true)
                .build();
        imageLoader.getInstance().displayImage(imagepath,imageView,options);

        getDirections = (Button) view.findViewById(R.id.getdirections);

        getDirections.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String strUri = "http://maps.google.com/maps?q=loc:" + latitude + "," + longitude + " (" + email + ")";
                Intent mapIntent = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse(strUri));

                mapIntent.setClassName("com.google.android.apps.maps","com.google.android.maps.MapsActivity");

                getActivity().startActivity(mapIntent);

            }
        });

//        View v = inflater.inflate(R.layout.listviewtopager,false);
        // Gets the MapView from the XML layout and creates it
        mapView = (MapView) view.findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);

        // Gets to GoogleMap from the MapView and does initialization stuff
        map = mapView.getMap();
        map.getUiSettings().setMyLocationButtonEnabled(false);
        map.setMyLocationEnabled(true);

        // Needs to call MapsInitializer before doing any CameraUpdateFactory calls
        MapsInitializer.initialize(this.getActivity());

        // Updates the location and zoom of the MapView
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(Double.parseDouble(latitude),Double.parseDouble(longitude)),10);
        map.animateCamera(cameraUpdate);

        return view;
    }

    @Override
    public void onResume() {
        mapView.onResume();
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }
}

而我在这堂课中称它为:

public class ViewPagerFragment extends FragmentActivity implements
        LoaderManager.LoaderCallbacks<Cursor>{

    ArrayList<String> e

mail = new ArrayList<String>();
ArrayList<String> about = new ArrayList<String>();

ArrayList<String> imagepath = new ArrayList<String>();

ArrayList<String> latitude = new ArrayList<String>();

ArrayList<String> longitude = new ArrayList<String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_pager_fragment);
    getLoaderManager().initLoader(1,null,this);
}

private SmartFragmentStatePagerAdapter adapterViewPager;

// Extend from SmartFragmentStatePagerAdapter now instead for more dynamic ViewPager items
public static class MyPagerAdapter extends SmartFragmentStatePagerAdapter {
    private final ArrayList<String> email;
    private final ArrayList<String> about;
    private final ArrayList<String> imagepath;
    private final ArrayList<String> latitude;
    private final ArrayList<String> longitude;
    private int listPosition;

    public MyPagerAdapter(FragmentManager fragmentManager,ArrayList<String> email,ArrayList<String> about,ArrayList<String> imagepath,ArrayList<String> latitude,ArrayList<String> longitude,int lPosition) {
        super(fragmentManager);
        this.imagepath=imagepath;
        this.email=email;
        this.about = about;
        this.latitude= latitude;
        this.longitude = longitude;
        listPosition = lPosition;
    }

// Returns total number of pages
@Override
public int getCount() {
    return email.size();
}



 // Returns the fragment to display for that page
    @Override
        public Fragment getItem(int position) {
//            return FirstFragment.newInstance(listPosition+position,email.get(listPosition+position));
            return FirstFragment.newInstance(email.get(position),about.get(position),imagepath.get(position),latitude.get(position),longitude.get(position));
    }

    // Returns the page title for the top indicator
    @Override
    public CharSequence getPageTitle(int position) {
        return "Page " + position;
    }

}

@Override
public Loader<Cursor> onCreateLoader(int id,Bundle args) {
    String[] projection =
            {
                    ActivitiesTable.KEY_EMAIL,ActivitiesTable.KEY_ABOUT,ActivitiesTable.KEY_IMAGEPATH,ActivitiesTable.KEY_LATITUDE,ActivitiesTable.KEY_LONGITUTDE

            };
    CursorLoader cursorLoader = new CursorLoader(this,NameContentProvider.NAME_ACTIVITIES_URI,projection,null);
    return cursorLoader;
}

@Override
public void onLoadFinished(android.content.Loader<Cursor> loader,Cursor cursor) {
    if (cursor != null && cursor.getCount() > 0) {
        cursor.moveToFirst();
        do {
            email.add(cursor.getString(cursor
                    .getColumnIndexOrThrow("email")));
            about.add(cursor.getString(cursor
                    .getColumnIndexOrThrow("about")));
            imagepath.add(cursor.getString(cursor
                    .getColumnIndexOrThrow("imagepath")));
            latitude.add(cursor.getString(cursor
                    .getColumnIndexOrThrow("serverLatitude")));
            longitude.add(cursor.getString(cursor
                    .getColumnIndexOrThrow("serverLongitude")));
        } while (cursor.moveToNext());
    }

    int listPosition = getIntent().getExtras().getInt("position");


    ViewPager vpPager = (ViewPager) findViewById(R.id.vpPager);
    adapterViewPager = new MyPagerAdapter(getSupportFragmentManager(),email,longitude,listPosition);
    vpPager.setAdapter(adapterViewPager);
    vpPager.setCurrentItem(listPosition);

}

@Override
public void onLoaderReset(android.content.Loader<Cursor> loader) {



   }
}

如何修改代码以使用该教程直接将viewPager与加载器一起使用,而不是将所有内容存储在列表中然后使用列表?

解决方法

我无法评论,所以我正在写一个答案..

您有一个实现LoaderCallbacks< Cursor>的活动.加载数据时,您的活动会收到onLoadFinished回调.在此方法中,您有一个应该在ViewPager中显示的Cursor.

显示Cursor中的数据,请在适配器上调用swapCursor方法.因此,每次加载数据时都不要创建适配器.创建一次,然后只需调用swapCursor即可.

此外,每次都找不到ViewPager – findViewById是一个繁重的操作,它应该在创建视图层次结构后执行.

所以,你的onLoadFinished将如下所示:

@Override
public void onLoadFinished(android.content.Loader<Cursor> loader,Cursor cursor) {
    if (adapterViewPager == null) {
        adapterViewPager = new MyPagerAdapter(getSupportFragmentManager(),cursor);
        vpPager.setAdapter(adapterViewPager);
    } else {
        adapterViewPager.swapCursor(cursor);
    }
}

猜你在找的Android相关文章