I am trying to use a selector to implement a simple dot indicator for a ViewPager.
The dots are supposed to change color and size when the page is changed, but they only change color, while the size stays the same.
The selector:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true">
<shape android:shape="oval">
<size
android:height="12dp"
android:width="12dp"/>
<solid android:color="@color/highlight"/>
</shape>
</item>
<item>
<shape android:shape="oval">
<size
android:height="6dp"
android:width="6dp"/>
<solid android:color="@color/light_grey"/>
</shape>
</item>
</selector>
which is used in a layout
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="@dimen/margin_2x"
android:src="@drawable/dot_selector">
</ImageView>
which is used in onCreate() to show the initial state:
for (int i = 0; i < mPagerAdapter.getCount(); i++) {
getLayoutInflater().inflate(R.layout.dot_indicator, viewPagerCountDots);
}
viewPagerCountDots.getChildAt(0).setSelected(true);
This looks as expected:
But when I change the selector state when the page is changed like this...
@Override
public void onPageSelected(int position) {
for (int i = 0; i < mPagerAdapter.getCount(); i++) {
viewPagerCountDots.getChildAt(i).setSelected(i == position);
}
}
..it looks like this:
Invalidating the child or the ViewGroup does not do anything. Any clue what is going wrong here?
Update
Calling requestLayout on the child fixes it, as suggested by Bartek Lipinski
@Override
public void onPageSelected(int position) {
for (int i = 0; i < mPagerAdapter.getCount(); i++) {
View dotView = viewPagerCountDots.getChildAt(i);
dotView.setSelected(i == position);
dotView.invalidate();
dotView.requestLayout();
}
}
add requestLayout()
calls in your onPageSelected
callback:
@Override
public void onPageSelected(int position) {
for (int i = 0; i < mPagerAdapter.getCount(); i++) {
viewPagerCountDots.getChildAt(i).setSelected(i == position);
viewPagerCountDots.getChildAt(i).requestLayout();
}
}
alternatively you can change your drawable to have always the same size, so the setSelected
is enough:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true">
<shape android:shape="oval">
<size
android:width="12dp"
android:height="12dp"/>
<solid android:color="@color/highlight"/>
</shape>
</item>
<item>
<layer-list>
<item android:bottom="3dp"
android:left="3dp"
android:right="3dp"
android:top="3dp">
<shape android:shape="oval">
<size
android:width="6dp"
android:height="6dp"/>
<solid android:color="@color/light_grey"/>
</shape>
</item>
</layer-list>
</item>
</selector>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With