Android setVisibility无法在PagerAdapter中运行

时间:2017-04-28 20:42:14

标签: java android android-viewpager android-imageview

我正试图隐藏并在我的PagerAdapter项目中显示我的部分视图,但它没有做任何事情,没有GONE,VISIBLE或INVISIBLE。

public class FeedPagerAdapter extends PagerAdapter {
    private final String KEY_GLOBAL_PREFS = "global";

    @BindView(R.id.item) ImageView image;
    @BindView(R.id.progress_bar) ProgressBar progressBar;

    private final SlideActivity host;
    private List<Thing> items;

    private SharedPreferences sharedPreferences;

    private int postition;

    public FeedPagerAdapter(SlideActivity host, List<Thing> items){
        this.host = host;
        this.items = items;

        sharedPreferences = host.getSharedPreferences(KEY_GLOBAL_PREFS, Context.MODE_PRIVATE);
    }

    @Override
    public Object instantiateItem(final ViewGroup parent, int position) {
        final View view = LayoutInflater.from(host).inflate(R.layout.item_slide_reddit_post, parent, false);
        ButterKnife.bind(this, view);

        progressBar.setVisibility(View.GONE);

        return view;
    }

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

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

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }
}

这是项目xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/item"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src:"..."/>
    <ProgressBar
        android:id="@+id/progress_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

以下是从主机活动设置适配器的方法:

adapter = new FeedPagerAdapter(SlideActivity.this, List<> of items);
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(position);
adapter.notifyDataSetChanged();

任何帮助都很棒

4 个答案:

答案 0 :(得分:0)

再次查看item.xml,它查找我的图像是匹配父项,而您的进度条是包装内容。将图像更改为wrap_contet并确保显示进度条!

答案 1 :(得分:0)

在设置progressBar可见性之前,notifyDataSetChanged()可能在行progressBar.setVisibility(View.GONE);之后添加adapter.notifyDataSetChanged();

答案 2 :(得分:0)

我记得改变ProgressBar状态,你应该总是使用runOnUiThread()

getActivity().runOnUiThread(new Runnable() {
    public void run() {
        // implement View changes.
    }
}); 

答案 3 :(得分:0)

似乎使用addEdge(Source, Target, Edge)或标准Butterknife设置findViewById项无法更新视图,不确定原因,也许有人可以解释。每当需要在ProgressBar中更改其可见性时,我会通过查找实际项目来解决问题:

PagerAdapter