如何刷新片段中的列表视图

时间:2015-06-09 01:23:41

标签: android listview android-fragments refresh

我目前正在尝试构建一个Android应用程序,其目标是显示3个选项卡(每个选项卡有一个片段)。每个选项卡都会显示列表视图及其正确的信息。 问题是,当我尝试刷新列表视图后,例如,在删除元素后,我无法刷新好的列表视图。 事实上,我注意到当我第一次加载我的应用程序时,我可以自由地删除我的第一个列表视图中的元素(在第一个选项卡中)并且它将正常刷新。但是,如果我滑动到下一个选项卡(右侧)并尝试删除项目,它将不会删除此列表视图中的项目,而是删除第一个项目。 同样的事情,如果我再次向右滑动,并尝试删除一个元素,它将删除中间片段(第二个)上的项目。从这时起,我删除第1,第2或第3个选项卡上的项目无关紧要,因为它只是第2个将被更新的内容。

我认为生命机制存在潜在的循环,我不明白解释所有这些,但我不知道该如何更改我的代码。

在组织方面,我有一个带有3个ListFragments的MainActivity(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);
    }
}
}

用于填充列表视图的适配器(每个选项卡都有一个适配器,因为3个列表视图不会使用相同的对象:

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

}

0 个答案:

没有答案