如何在调用Fragment时刷新ListView(FragmentStatePagerAdapter)

时间:2014-04-21 04:17:32

标签: android android-listview fragmentstatepageradapter

嗨,这是我的MainActivity For Tab。它有3个片段。

Second Fragment将一些数据添加到数据库,第三个片段可以检查它是否发生了变化。但即使我用第二个片段向数据库添加一些数据,第三个片段也没有变化。

如何只需点击第三个标签即可刷新我的第三个片段 下面是mainActivity,

package com.example.location;

import java.util.Locale;

import com.example.meta.LocationNState;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends Activity implements ActionBar.TabListener {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a {@link FragmentPagerAdapter}
     * derivative, which will keep every loaded fragment in memory. If this
     * becomes too memory intensive, it may be best to switch to a
     * {@link android.support.v13.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.e("Activity : ", "MainActivity");
        // Set up the action bar.
        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        // When swiping between different sections, select the corresponding
        // tab. We can also use ActionBar.Tab#select() to do this if we have
        // a reference to the Tab.
        mViewPager
        .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }
        });

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            // Create a tab with text corresponding to the page title defined by
            // the adapter. Also specify this Activity object, which implements
            // the TabListener interface, as the callback (listener) for when
            // this tab is selected.
            actionBar.addTab(actionBar.newTab()
                    .setText(mSectionsPagerAdapter.getPageTitle(i))
                    .setTabListener(this));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.

        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentStatePagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {

            switch(position){

            case 0 :
                return new LocationFragment().newInstance(position);
            case 1 :
                LocationNState location = LocationNState.get();
                return new NewLocation().newInstance(location);
            case 2 :                
                return new ShowSavedLocation().newInstance(position);
            }

            return new LocationFragment().newInstance(0);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            case 2:
                return getString(R.string.title_section3).toUpperCase(l);
            }
            return null;
        }
    }
}

下面是第三个片段。

package com.example.location;

import java.util.ArrayList;
import java.util.List;

import android.app.Fragment;
import android.content.Context;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.example.db.MySQLiteHelper;
import com.example.meta.LocationNState;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class ShowSavedLocation extends Fragment implements OnItemClickListener{

    private GoogleMap map = null;
    private MySQLiteHelper db = null;
    private Context context = null;
    private ListView listView = null;
    private Button del_Button = null;
    private Geocoder geocoder = null;
    private List<LocationNState> locationNStates = null;
    private ArrayList<LocationNState> array_locationNStates  = null;
    private LocationNStateAdapter adapter = null;

    public  ShowSavedLocation newInstance(int sectionNumber) {
        ShowSavedLocation fragment = new ShowSavedLocation();
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        context = getActivity();
        View rootView = inflater.inflate(R.layout.fragment_showsavedlocation, container, false);
        map =  ((MapFragment) getFragmentManager().findFragmentById(R.id.map_showSavedLocation)).getMap();
        db = new MySQLiteHelper(context);
        geocoder = new Geocoder(context);  


        listView = (ListView) rootView.findViewById(R.id.list_view);


        locationNStates = db.getAllLocationNStates();
        array_locationNStates = new ArrayList<LocationNState>(locationNStates);
        adapter = new LocationNStateAdapter(context, R.layout.listview_locationnstate, array_locationNStates);
        listView.setAdapter(adapter);


        listView.setOnItemClickListener(this);

        setMapSetting(LocationNState.get());

        return rootView;
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        MapFragment f = (MapFragment) getFragmentManager().findFragmentById(R.id.map_showSavedLocation);
        if (f != null) 
            getFragmentManager().beginTransaction().remove(f).commit();
    }
    public void setMapSetting(LocationNState locationNState){
        if(locationNState.getAddress() == null ||
                locationNState.getLocation().getLatitude() == 0 ||
                locationNState.getLocation().getLongitude() == 0)
            return;
        map.clear();
        map.setMyLocationEnabled(true);
        map.setBuildingsEnabled(true);
        map.getUiSettings().setCompassEnabled(true);
        map.getUiSettings().setZoomControlsEnabled(true);
        map.addMarker(new MarkerOptions()
        .position(new LatLng(locationNState.getLocation().getLatitude() , locationNState.getLocation().getLongitude()))
        .title(locationNState.getAddress())
        //.snippet(address_Snippet)
        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(locationNState.getLocation().getLatitude(), locationNState.getLocation().getLongitude()), 17 ));
    }


    public class LocationNStateAdapter extends ArrayAdapter<LocationNState>  {

        private ArrayList<LocationNState> LocationNStateArrayList = null;

        public LocationNStateAdapter(Context context, int resource,
                ArrayList<LocationNState> objects) {
            super(context, resource, objects);
            // TODO Auto-generated constructor stub

            this.LocationNStateArrayList = objects;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {


            View rootView = convertView;
            if(rootView == null){
                LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                rootView = vi.inflate(R.layout.listview_locationnstate, null);
            }

            LocationNState locationNState = LocationNStateArrayList.get(position);
            if(locationNState != null){
                TextView addressTextView = (TextView) rootView.findViewById(R.id.listview_address);
                TextView stateTextView = (TextView) rootView.findViewById(R.id.listview_state);

                if(addressTextView != null )
                    addressTextView.setText(" 위치 : "  +locationNState.getAddress().toString());
                if(stateTextView != null){
                    int state = locationNState.getState();
                    String mState = "벨소리";
                    switch(state){
                    case 0:
                        mState = "벨소리";
                        break;
                    case 1:
                        mState = "진동";
                        break;
                    case 2:
                        mState = "무음";
                        break;
                    default :
                        break;
                    }
                    stateTextView.setText(" 상태 : " + mState);
                }
            }



            final int index = position;
            del_Button = (Button) rootView.findViewById(R.id.listview_del);
            del_Button.setOnClickListener(new Button.OnClickListener() {
                public void onClick(View v)
                {
                    LocationNState locationNState = (LocationNState)listView.getAdapter().getItem(index);
                    LocationNStateArrayList.remove(index);

                    db.deleteLocationNState(locationNState);

                    refreshListView();
                } 
            });
            return rootView;
        }

    }
    @Override
    public void onPause(){
        refreshListView();
        super.onPause();

    }
    public void refreshListView(){

        final ArrayAdapter adapter = ((ArrayAdapter)listView.getAdapter());
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        // TODO Auto-generated method stub
        /*      View rootView = view;
        if(rootView == null){
            LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            rootView = vi.inflate(R.layout.listview_locationnstate, null);
        }*/
        LocationNState locationNState = (LocationNState)listView.getAdapter().getItem(position);    //obj 자체가 locationNState네.
        setMapSetting(locationNState);
    }   
}

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

第三个片段在refreshListView()而不是onPause()中调用onResume()