11

我知道这里已经有一些关于此的主题,但我找不到可以为我的案例工作的解决方案。

我有一个使用自定义的滑动画廊FragmentActivityFragmentPagerAdapter其中包含一个片段列表。

里面FragmentActivity是一个ImageView“删除”。如果单击,deleteMedia()则调用该函数,然后应删除当前函数Fragment并显示以下内容Fragment。在我的示例中,我将如何做到这一点?

片段活动:

public class GalleryPagerActivity extends FragmentActivity implements OnClickListener {

    private Intent intent;
    private SharedPreferences settings;
    private PagerAdapter mPagerAdapter;
    private ViewPager mPager;
    private List<Fragment> fragments;
    private List<WhiteboardMedia> wiList;

    private int selectedPosition;
    private LinearLayout llTop;
    private TextView tvTop;
    private ImageView delete;
    private ImageView share;
    private TextView tvCounter;
    private TextView tvFilename;
    private TextView tvFilesize;
    private TextView tvDate;

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

        try {
            super.setContentView(R.layout.gallery_pager);

            intent = getIntent();

            Type collectionType = new TypeToken<List<WhiteboardMedia>>(){}.getType();

            wiList = gson.fromJson(intent.getStringExtra("wiList"), collectionType);
            selectedPosition = intent.getIntExtra("position", 1);

            llTop = (LinearLayout) findViewById(R.id.llTop);
            llTop.setOnClickListener(this);
            tvTop = (TextView) findViewById(R.id.tvTop);
            tvTop.setOnClickListener(this);
            delete = (ImageView) findViewById(R.id.imgDelete);
            delete.setOnClickListener(this);
            share = (ImageView) findViewById(R.id.imgShare);
            share.setOnClickListener(this);

            tvCounter = (TextView) findViewById(R.id.tvCounter);
            tvFilename = (TextView) findViewById(R.id.tvFilename);
            tvFilesize = (TextView) findViewById(R.id.tvFilesize);
            tvDate = (TextView) findViewById(R.id.tvDate);

            createContextMenu();
            initDropbox();
        } catch (Exception e) {
            Log.e("GalleryPagerActivity", e.getLocalizedMessage());
        }
    }

    /**
     * Initialise the pager
     */
    private void initialisePager() {
        mPager = (ViewPager) super.findViewById(R.id.viewpager);
        mPager.setAdapter(this.mPagerAdapter);
        mPager.setOnPageChangeListener(new GalleryPageListener(tvCounter, tvFilename, tvFilesize, tvDate, wiList));

        mPager.setCurrentItem(selectedPosition, true);
        updatePage(selectedPosition);
    }

    public void updatePage(int position)
    {
        int focusedPage = position + 1;
        Log.i("onPageSelected", "page selected " + position);

        WhiteboardMedia wiImage = wiList.get(position);

        String imageDate = "N/A";
        try {
            Date dateTaken= new Date(); //wiImage.getDate();
            SimpleDateFormat sdf = new SimpleDateFormat("yy/MM/dd");
            imageDate = sdf.format(dateTaken);
        } catch (Exception e) {
        }

        try {
            tvCounter.setText(focusedPage + "/" + wiList.size());
            tvFilename.setText(wiImage.getFilename());
            tvFilesize.setText(wiImage.getSize() + "a");
            tvDate.setText(imageDate);
        } catch (Exception e) {
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

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

    private WhiteboardMedia getActiveWhiteboardImage() {
        return wiList.get(mPager.getCurrentItem());
    }

    private final int DELETE = 1;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(1, DELETE, 2, R.string.delete).setIcon(R.drawable.menu_btn_trash);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case DELETE:
            deleteMedia();
            return true;
        }
        return super.onContextItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        if (v == delete) {
            deleteMedia();
        }
    }

    private void deleteMedia() {
        // TODO delete the active Fragment and display the next Fragment in the list
    }

    /******************************************************************************
     * Context Menu
     *****************************************************************************/
    private void createContextMenu() {
        // context menu stuff
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        // stuff
    }

}

片段页面适配器:

public class GalleryPagerAdapter extends FragmentPagerAdapter {

private final List<Fragment> fragments;

public GalleryPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
    super(fm);
    this.fragments = fragments;
}

@Override
public Fragment getItem(int position) {
    return this.fragments.get(position);
}

@Override
public int getCount() {
    return this.fragments.size();
}
}

感谢帮助!

4

5 回答 5

18

这就是我正在使用的解决方案:

mViewPager :是您用来设置 Fragment 的视图

mViewPager = (YourViewPager) findViewById(R.id.myPager);

TABLE :只是我所有片段位置的整数列表

    public void destroyAllItem() {
        int mPosition = mViewPager.getCurrentItem();
        int mPositionMax = mViewPager.getCurrentItem()+1;
        if (TABLE.size() > 0 && mPosition < TABLE.size()) {
            if (mPosition > 0) {
                mPosition--;
            }

            for (int i = mPosition; i < mPositionMax; i++) {
                try {
                    Object objectobject = this.instantiateItem(mViewPager, TABLE.get(i).intValue());
                    if (objectobject != null)
                        destroyItem(mViewPager, TABLE.get(i).intValue(), objectobject);
                } catch (Exception e) {
                    Log.i(TAG, "no more Fragment in FragmentPagerAdapter");
                }
            }
        }
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container, position, object);

        if (position <= getCount()) {
            FragmentManager manager = ((Fragment) object).getFragmentManager();
            FragmentTransaction trans = manager.beginTransaction();
            trans.remove((Fragment) object);
            trans.commit();
        }
    }
于 2012-07-11T22:43:20.470 回答
16

首先,我建议你考虑改变你的FragmentPagerAdapter, 看起来更像样本。您通常不保存片段列表,就像ArrayAdapter通常保存Views行列表一样。通常,您根据需要创建片段,而其他人则持有该列表。

然后,要删除某些内容,请将其从模型数据中删除(FragmentPagerAdapter通常包装的内容)。确保这getCount()将返回正确数量的项目。然后,调用notifyDataSetChanged()FragmentPagerAdapter这应该会触发 的重绘ViewPager

于 2012-03-18T14:15:35.767 回答
1

我找到了一个解决方案,覆盖了活动的方法“onPostResume()”并在其中调用了 notifyDataSetChanged。

@Override
protected void onPostResume() {
    super.onPostResume();
    if(this.mCustomPagerAdapter!=null){
        this.mCustomPagerAdapter.notifyDataSetChanged();
    }
}
于 2016-02-11T17:23:04.323 回答
1

如果您使用 FragmentPagerAdapter 在随机位置(不总是在末尾)动态添加和删除片段,则需要更多注意的方法是 getItemId。默认情况下,FragmentPagerAdapter 使用位置组合 viewId 作为片段的标签名称,但是如果添加或删除片段,位置会发生变化。结果,您可能会得到一个空页面,因为您正在添加的位置已被现有片段占用。要解决此问题,请覆盖 getItemId。

@Override
public long getItemId(int position) {
    long itemId = ...;  //Provide your unique ID here according to you logic
    return itemId;
}
于 2018-03-20T21:28:47.547 回答
0

就我而言,当我尝试从适配器中删除一项时,我将执行以下操作:

// get the position of item to remove
int position = getBinding().vp.getCurrentItem();
// remove the item from adapter
adapter.removeItem(position);
adapter.notifyDataSetChanged();
// minus one from the count
totalInvoice--;
updateTitle(getBinding().vp.getCurrentItem());
if (totalInvoice == 0) {
    finish();
}
// set the adapter to view pager again            
getBinding().vp.setAdapter(adapter);
// smooth scroll to given position
getBinding().vp.setCurrentItem(position);

我上面这样做的原因是我发现即使您从数据列表中删除了一个,但片段视图仍然存在。所以你必须让视图寻呼机实例化给定位置的视图。上面试图删除所有片段的答案对我不起作用。因此,我发现了将适配器设置为再次查看寻呼机的糟糕方法。

于 2018-07-27T08:09:54.000 回答