我正在尝试创建一个用户可以点按照片的照片,而照片会突出显示'状态。
我实现了突出显示的'通过在图像上方设置FrameLayout覆盖来进行状态。问题是,当我通过页面滑动时,状态不仅会丢失,而且会显示在未选择的图像上。
这是我的viewpager适配器:
public class ImageSliderAdapter extends FragmentPagerAdapter {
//Image ids from constants
private int[] Images = Constants.Images;
private int mCount = Images.length;
public ImageSliderAdapter$Adapter(FragmentManager fm) {
super(fm);
}
// The displayed fragment for each position
@Override
public FragmentImageSlider getItem(int position) {
return FragmentImageSlider.newInstance(Images[position];
}
@Override
public int getCount() {
return mCount;
}
}
这是viewpager返回的片段:
public class FragmentImageSlider extends Fragment {
//Image resource id to show
int imageResourceId;
//Image view of the pic displayed
ImageView image;
// View to indicate highlighted images
View highliteView;
public static FragmentImageSlider newInstance(int imageResourceId){
FragmentImageSlider f = new FragmentImageSlider();
Bundle b = new Bundle();
b.putInt("image", imageResourceId);
f.setArguments(b);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (getArguments() !=null) {
//get image resource id from extras
imageResourceId = getArguments().getInt("image");
}
View root = inflater.inflate(R.layout.displayLayout, null);
image = (ImageView) root.findViewById(R.id.imageView);
highliteView = root.findViewById(R.id.highliteView);
image.setImageResource(imageResourceId);
//When the image is clicked, toggle the highlighted state
image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//toggle state
//this view has a selector and changes when selected
highliteView.setSelected(!highliteView.isSelected());
}
});
return root;
}
}
所以我的问题是,我如何保持突出显示的状态?
答案 0 :(得分:0)
您可以更改visibility
的{{1}}而不是highlight view
。
默认情况下,将突出显示视图的selected state
设置为visibility
,并在选择图像时将其更改为GONE
。
visible
答案 1 :(得分:0)
根据[FragmentPagerAdapter文档](视图层次结构可能在不可见时被销毁),
用户访问的每个页面的片段将保留在内存中,但其视图层次结构可能会在不可见时被销毁
view
可能会在退出视图时从默认布局重新加载,这就是突出显示状态丢失的原因。
您应该在Fragment
:
public MyFragment extends Fragment{
//variable to keep the state
private boolean highlight;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//rest of your other code
image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
highliteView.setSelected(!highliteView.isSelected());
//set the highlight state when clicked
highlight = !highliteView.isSelected();
}
});
return root;
}
//set the view state to the image view
public void onViewCreated(View view, Bundle savedInstanceState){
highliteView.setSelected(highlight);
}
}