Android 如何在片段中刷新listview

Android 如何在片段中刷新listview,android,listview,android-fragments,refresh,Android,Listview,Android Fragments,Refresh,我目前正在尝试构建一个android应用程序,目标是显示3个选项卡(每个选项卡上有一个片段)。每个选项卡都显示一个包含正确信息的列表视图。 问题是,当我尝试在删除一个元素之后刷新listview时,我很难刷新好的listview。 事实上,我注意到,当我第一次加载我的应用程序时,我可以在我的第一个listview(在第一个选项卡中)上自由删除一个元素,它将正常刷新。但是,如果我滑动到下一个选项卡(右侧)并尝试删除某个项目,它不会删除此listview上的项目,而是删除第一个列表视图中的项目。 同

我目前正在尝试构建一个android应用程序,目标是显示3个选项卡(每个选项卡上有一个片段)。每个选项卡都显示一个包含正确信息的列表视图。 问题是,当我尝试在删除一个元素之后刷新listview时,我很难刷新好的listview。 事实上,我注意到,当我第一次加载我的应用程序时,我可以在我的第一个listview(在第一个选项卡中)上自由删除一个元素,它将正常刷新。但是,如果我滑动到下一个选项卡(右侧)并尝试删除某个项目,它不会删除此listview上的项目,而是删除第一个列表视图中的项目。 同样,如果我再次向右滑动,并尝试删除一个元素,它将删除中间片段(第二个片段)上的一个项目。从现在起,我是否删除第一个、第二个或第三个选项卡上的项目将不再重要,因为只有第二个选项卡将被更新

我认为有一种潜在的生命周期机制,我不明白如何解释这一切,但我不知道对我的代码做什么修改

就组织而言,我有一个包含3个列表片段的主要活动(TabImages、TabMusiques、TabVideos)。 我正在使用FragmentStatePagerAdapter根据用户当前查看的位置实例化我的片段

/**
 * Adapter used to instanciate the right Fragment depending on the current tab selected in the
 * MainActivity.
 */
public class ViewPagerAdapter extends FragmentStatePagerAdapter {

      // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
      CharSequence Titles[];
      // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
      int NumbOfTabs;


      //Build a Constructor and assign the passed Values to appropriate values in the class
      public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
        super(fm);

        this.Titles = mTitles;
        this.NumbOfTabs = mNumbOfTabsumb;
   }

   /**
    * This method returns the fragment for a given position in the tabs
    * @param position Integer describing the position in the tabs of the activity
    */
    @Override
    public Fragment getItem(int position) {

        if(position == 0) // if the position is 0 we are returning the First tab
        {
            TabImages tabImages = new TabImages();
            return tabImages;
        }
        else if(position == 1)   //if the position is 1 we are returning the Second type of tab
        {
            TabMusiques tabMusiques = new TabMusiques();
            return tabMusiques;
        }
        else //else we return the last type of tab
        {
            TabVideos tabVideos = new TabVideos();
            return tabVideos;
        }


   }

   /**
    * This method returns the titles for the Tabs in the Tab Strip
    * @param position position of the tab asked
    * return the title of the tab
    */
    @Override
    public CharSequence getPageTitle(int position) {
        return Titles[position];
    }

    /**
     * This method returns the Number of tabs for the tabs Strip
     */
    @Override
    public int getCount() {
        return NumbOfTabs;
    }
}
片段:

public class TabImages extends ListFragment {

//Views
private View rootView;

//Vars
private Dossier dossier;
private StableArrayAdapterImage adapterImages;

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

}

/**
 * Method called on the creation of the Fragment (initiated by the MainActivity)
 */
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    //Inflate the layout of the music tab
    rootView = inflater.inflate(R.layout.tab, container, false);

    dossier = new Dossier("Dossier1", "02/06/2015", EnumTypeElement.IMAGE);

    //Creating the object to add to the Dossier
    Element d1 = new Dossier("sous-dossier1", "03/12/2008", EnumTypeElement.IMAGE);
    Element d2 = new Dossier("sous-dossier2", "23/03/2002", EnumTypeElement.IMAGE);
    Element i1 = new Image("image1", "12/12/2012");
    Element i2 = new Image("image2", "13/03/2007");
    Element i3 = new Image("image3", "00/00/0000");
    Element i4 = new Image("image4", "15/15/1515");
    Element i5 = new Image("image5", "21/12/2345");
    Element i6 = new Image("image6", "22/11/1994");
    Element i7 = new Image("image7", "12/08/1995");
    Element i8 = new Image("image8", "01/12/1985");

    try {
        dossier.ajouterElement(d1);
        dossier.ajouterElement(d2);
        dossier.ajouterElement(i1);
        dossier.ajouterElement(i2);
        dossier.ajouterElement(i3);
        dossier.ajouterElement(i4);
        dossier.ajouterElement(i5);
        dossier.ajouterElement(i6);
        dossier.ajouterElement(i7);
        dossier.ajouterElement(i8);
    }
    catch (WrongTypeElementException e){
        e.getMessage();
    }

    adapterImages = new StableArrayAdapterImage(getActivity(), android.R.layout.simple_list_item_1, dossier.getListeElement());
    setListAdapter(adapterImages);

    return rootView;
}

public void updateFragmentImages(){
    if(adapterImages != null){
        adapterImages.notifyDataSetChanged();
    }
}

/**
 * Method called once the Fragment is created
 * Allows us to register the Context menu and make it available for the event listeners
 * @param savedInstanceState If the fragment is being re-created from a previous state, this is the state
 */
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    registerForContextMenu(getListView());
}

/**
 * Method called on click of a ListView item
 * @param l the ListView on which the call occured
 * @param v the View containing the ListView
 * @param position the position of the item clicked
 * @param id the id of the item clicked
 */
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    Element element = dossier.getListeElement().get(position);

    if(element instanceof Dossier) //Si l'element est un dossier
    {
        Toast.makeText(getActivity(), "Impossible de lire un fichier actuellement", Toast.LENGTH_SHORT).show();
    }
    else
    {
        //Clicking on a element result in the launching of the lecture activity
        Intent myIntent = new Intent(v.getContext(), ImageLectureActivity.class);
        myIntent.putExtra("dossier", dossier);
        myIntent.putExtra("position", position);
        startActivityForResult(myIntent, 0);
    }

}

/**
 * Listener of the LongClick on an item of the list
 * Results in the layout inflation of the menu
 * @param menu The context menu being created
 * @param v The view for which the context menu is being built
 * @param menuInfo additional information on the menu (depends mainly on the view v)
 */
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    MenuInflater inflater = this.getActivity().getMenuInflater();
    inflater.inflate(R.menu.context_menu_images, menu);
    menu.setHeaderTitle(R.string.menuImageTitle);
}

/**
 * Listener of the click on an item of the contextual menu
 * Handles the items one by one
 * @param item selected item of the menu.
 * @return true to override the behaviour of the click on the item, false otherwise
 */
@Override
public boolean onContextItemSelected(MenuItem item) {
    final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    switch (item.getItemId()) {
        case R.id.menu1:
            return true;
        case R.id.menu2:
            return true;
        case R.id.menu3:
            //Handles the click on the "Supprimer" button of the context menu
            new AlertDialog.Builder(getActivity())
                    .setTitle("Supprimer")
                    .setMessage("Confirmer la suppression")
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            try{
                                dossier.supprimerElement(info.position);
                                updateFragmentImages();
                            }
                            catch(ElementNotFoundException e) {
                                e.getMessage();
                            }
                        }
                    })
                    .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // do nothing
                        }
                    })
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .show();
            return true;
        default:
            return super.onContextItemSelected(item);
    }
}
}
用于填充listview的适配器(每个选项卡上都有一个适配器,因为3个listview不会使用相同的对象:

package com.antoine.polytelecommande.views.Adapters;

public class StableArrayAdapterImage extends ArrayAdapter<Element> {

private HashMap<String, Integer> mIdMap = new HashMap<>();

/**
 * Constructor of the adapter.
 * Iterates on the element of the list to populate the HashMap mIdMap.
 * @param context Application context passed to the adapter.
 * @param textViewResourceId layout used for the listview.
 * @param objects List of Images used to populate the listview.
 */
public StableArrayAdapterImage(Context context, int textViewResourceId, List<Element> objects) {
    super(context, textViewResourceId, objects);
    for (int i = 0; i < objects.size(); ++i) {
        mIdMap.put(objects.get(i).toString(), i);
    }
}

/**
 * Getter of an item in the listview given its position.
 * @param position position in the listview.
 * @return the id of the item.
 */
@Override
public long getItemId(int position) {
    String item = getItem(position).toString();
    return mIdMap.get(item);
}


@Override
public boolean hasStableIds() {
    return true;
}

}
package com.antoine.polytelecommande.views.Adapters;
公共类StableArrayAdapterImage扩展ArrayAdapter{
私有HashMap mIdMap=新HashMap();
/**
*适配器的构造函数。
*在列表的元素上迭代以填充HashMap mIdMap。
*@param context应用程序上下文已传递给适配器。
*@param textViewResourceId用于listview的布局。
*@param objects用于填充listview的图像列表。
*/
公共StableArrayAdapterImage(上下文上下文、int-textViewResourceId、列表对象){
超级(上下文、textViewResourceId、对象);
对于(int i=0;i
您将备份数据对象保存在哪里?您如何填充它/它们?您如何删除项目?我认为问题更多的是ListView或/和适配器代码(如果您使用)。请发布它们。我添加了您想要的代码。我将对象存储在“目录”中对象,该对象使用ArrayList存储对象。然后我使用此ArrayList使用StableAryAdapterXXX填充listview。