我一直在网上搜索一小时,我为viewPager创建了自定义视图。我看到的每个解决方案都是碎片。我的问题是如何使用if语句检查我的页面是否可见。我想这样做有一个原因。我有一些位于相机屏幕顶部的视图,并希望根据视图保存每张图片。例如:如果正在使用“TOPS”衣服对象和“tops_view”,我想将其保存到android中的“tops”文件夹中。我已经知道如何保存到不同的文件夹,所以我想在我的cameraAPI文件中创建if语句。 if语句是我想要实现的伪代码:
if (ClothesPagerView == TOPS)
final File file = new File(Environment.getExternalStorageDirectory() + "/OutfitMatcher/tops/img" + System.currentTimeMillis () +".jpg");
else if (ClothesPagerView == BOTTOMS)
final File file = new File(Environment.getExternalStorageDirectory() + "/OutfitMatcher/bottoms/img" + System.currentTimeMillis () +".jpg");
CustomPagerAdapater.java
public class CustomPagerAdapter1 extends PagerAdapter{
private Context mContext;
public CustomPagerAdapter1(Context context) {
mContext = context;
}
@Override
public Object instantiateItem(ViewGroup collection, int position) {
ClothesObject clothesObject = ClothesObject.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(clothesObject.getLayoutResId(), collection, false);
collection.addView(layout);
return layout;
}
@Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
@Override
public int getCount() {
return ClothesObject.values().length;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public CharSequence getPageTitle(int position) {
ClothesObject customPagerEnum = ClothesObject.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}
}
ClothesObject.jaca(我使用适配器)
public enum ClothesObject {
TOPS(R.string.tops_camera, R.layout.tops_view),
BOTTOMS(R.string.bottoms_camera, R.layout.bottoms_view),
ACCESSORIES(R.string.accessories_camera, R.layout.accessories_view),
SHOES(R.string.shoes_camera, R.layout.shoes_view),
OUTERWEAR(R.string.outerwear_camera, R.layout.outerwear_view),
DRESSES(R.string.dresses_camera, R.layout.dresses_view);
private int mTitleResId;
private int mLayoutResId;
ClothesObject(int titleResId, int layoutResId) {
mTitleResId = titleResId;
mLayoutResId = layoutResId;
}
public int getTitleResId() {
return mTitleResId;
}
public int getLayoutResId() {
return mLayoutResId;
}
}
答案 0 :(得分:1)
为此,您必须在Viewpager中使用片段。然后,您可以在片段中使用getUserVisibleHint()
来检查页面是否处于活动状态
即
if(getUserVisibleHint()){
//Your fragment is visible
}else{
// Not visible
}