I have a ViewPager, and I\'d like to get the current selected and visible view, not a position.
getChildAt(getCurrentItem)
returns wrong Vi
I've figured it out. What I did was to call setTag()
with a name to all View
s/ListView
s, and just call findViewWithTag(mytag)
, mytag
being the tag.
Unfortunately, there's no other way to solve this.
Use an Adapter extending PagerAdapter, and override setPrimaryItem method inside your PagerAdapter.
https://developer.android.com/reference/android/support/v4/view/PagerAdapter.html
class yourPagerAdapter extends PagerAdapter
{
// .......
@Override
public void setPrimaryItem (ViewGroup container, int position, Object object)
{
int currentItemOnScreenPosition = position;
View onScreenView = getChildAt(position);
}
// .......
}
You can find fragment by system tag. It's work for me. I used it in OnMeasure
function.
id
- viewPager ID
position
- fragment which you want to get
Important! You get this fragment if your fragment was created in adapter. So you must to check supportedFragmentManager.findFragmentByTag("android:switcher:" + id + ":" + position)
nullify
You can get view like this:
supportedFragmentManager.findFragmentByTag("android:switcher:" + id + ":" + position).view
You shouldn't give custom tag in adapter
You can get the current element by accessing your list of itens from your adapter calling myAdapter.yourListItens.get(myViewPager.getCurrentItem());
As you can see, ViewPager can retrieve the current index of element of you adapter (current page).
If you is using FragmentPagerAdapter you can do this cast:
FragmentPagerAdapter adapter = (FragmentPagerAdapter)myViewPager.getAdapter();
and call
adapter.getItem(myViewPager.getCurrentItem());
This works very well for me ;)
If you do not have many pages and you can safely apply setOffscreenPageLimit(N-1)
where N is the total number of pages without wasting too much memory then you could do the following:
public Object instantiateItem(final ViewGroup container, final int position) {
CustomHomeView RL = new CustomHomeView(context);
if (position==0){
container.setId(R.id.home_container);} ...rest of code
then here is code to access your page
((ViewGroup)pager.findViewById(R.id.home_container)).getChildAt(pager.getCurrentItem()).setBackgroundColor(Color.BLUE);
If you want you can set up a method for accessing a page
RelativeLayout getPageAt(int index){
RelativeLayout rl = ((RelativeLayout)((ViewGroup)pager.findViewById(R.id.home_container)).getChildAt(index));
return rl;
}
is that your first activity on the screen or have you layered some above each other already?
try this:
findViewById(android.R.id.content).getRootView()
or just:
findViewById(android.R.id.content)
also depending on what you want try:
((ViewGroup)findViewById(android.R.id.content)).getChildAt(0)