Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

android - Get focused View from ViewPager

i use the ViewPager for switching views with left/right swipe.

The ViewPager needs an Adapter, so I've built this one:

public class ListViewPagerAdapter extends PagerAdapter {

protected static final String TAG = "ListViewPagerAdapter";
protected static final int NUM_VIEWS = 3;

protected final Activity mActivity;

public ListViewPagerAdapter(Activity activity) {
    mActivity = activity;
}

@Override
public int getCount() {
    return NUM_VIEWS;
}

@Override
public void startUpdate(View container) {}

@Override
public Object instantiateItem(View container, int position) {
    // ViewPager
    ViewPager viewPager = (ViewPager) container;

    // Wird verwendet, um die Views aufzurufen
    LayoutInflater layoutInflater = mActivity.getLayoutInflater();

    // Standardm??ig ist news eingeblendet
    View view = layoutInflater.inflate(R.layout.news_fragment, null);
    // Falls sich die Position ver?ndert, so ver?ndert sich auch die View
    if (position == 0) {
        view = layoutInflater.inflate(R.layout.favorite_fragment, null);
    } else if (position == 2) {
        view = layoutInflater.inflate(R.layout.videos_fragment, null);
    }

    // View einblenden
    viewPager.addView(view, 0);

    return view;
}

@Override
public void destroyItem(View container, int position, Object object) {
    // ViewPager
    ViewPager viewPager = (ViewPager) container;
    // View
    View view = (View) object;

    // View l?schen
    viewPager.removeView(view);
}

@Override
public void finishUpdate(View container) {}

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

@Override
public Parcelable saveState() {
    return null;
}

@Override
public void restoreState(Parcelable state, ClassLoader loader) {}
 }

Now, i want to get the current focused view by the viewpager. I tried getChildAt(x), but it does not work.

Are there some example, or do you have any idea how to get the current view?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is possible to save the currently active object (View, Fragment, ...) by overriding PagerAdapter.setPrimaryItem method. For example:

private View mCurrentView;

@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
    mCurrentView = (View)object;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...