0

i want to set different value for an int depending on the screen orientation ..what i have tried ..but it didn't work ( a lot of unresolved codes starting from if bloc ..) ,

PS: 1/ the mIndicatorHeight is the height of the space the indicator takes up at the bottom of the view. (for pagging the recyclerview) ..
2/The indicator for pagging the recycler is totally written in code (so i can't do different xml files)

LinePageIndicatorDecoration.java

  public class LinePagerIndicatorDecoration extends RecyclerView.ItemDecoration {
        RecyclerViewPositionHelper mRecyclerViewHelper;
        int firstVisibleItem;
        private int colorActive = 0xFFFFFFFF;
private int mIndicatorHeight;
        private int colorInactive = 0x66FFFFFF;
        private Context context;

        private static final float DP = Resources.getSystem().getDisplayMetrics().density;

        /**
         * Height of the space the indicator takes up at the bottom of the view.
         */
        int orientation = this.context.getResources().getConfiguration().orientation;

        if (orientation == Configuration.ORIENTATION_PORTRAIT)
        {
             mIndicatorHeight = (int) (DP * 200);
        }
        else if( orientation == Configuration.ORIENTATION_LANDSCAPE) {

             mIndicatorHeight = (int) (DP * 100);
        }

        /**
         * Indicator stroke width.
         */

        private final float mIndicatorStrokeWidth = DP * 2;

        /**
         * Indicator width.
         */
        private final float mIndicatorItemLength = DP * 16;
        /**
         * Padding between indicators.
         */
        private final float mIndicatorItemPadding = DP * 4;

        /**
         * Some more natural animation interpolation
         */
        private final Interpolator mInterpolator = new AccelerateDecelerateInterpolator();

        private final Paint mPaint = new Paint();

        public LinePagerIndicatorDecoration() {
            mPaint.setStrokeCap(Paint.Cap.ROUND);
            mPaint.setStrokeWidth(mIndicatorStrokeWidth);
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setAntiAlias(true);
        }

        @Override
        public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
            super.onDrawOver(c, parent, state);

            int itemCount = parent.getAdapter().getItemCount();

            // center horizontally, calculate width and subtract half from center
            float totalLength = mIndicatorItemLength * itemCount;
            float paddingBetweenItems = Math.max(0, itemCount - 1) * mIndicatorItemPadding;
            float indicatorTotalWidth = totalLength + paddingBetweenItems;
            float indicatorStartX = (parent.getWidth() - indicatorTotalWidth) / 2F;

            // center vertically in the allotted space
            float indicatorPosY = parent.getHeight() - mIndicatorHeight / 2F;

            drawInactiveIndicators(c, indicatorStartX, indicatorPosY, itemCount);

            mRecyclerViewHelper = RecyclerViewPositionHelper.createHelper(parent);
            //firstVisibleItem = mRecyclerViewHelper.findFirstVisibleItemPosition();

            // find active page (which should be highlighted)
            RecyclerView.LayoutManager layoutManager = (RecyclerView.LayoutManager) parent.getLayoutManager();
            int activePosition = mRecyclerViewHelper.findFirstCompletelyVisibleItemPosition();
            if (activePosition == RecyclerView.NO_POSITION) {
                return;
            }

            // find offset of active page (if the user is scrolling)
            final View activeChild = layoutManager.findViewByPosition(activePosition);
            int left = activeChild.getLeft();
            int width = activeChild.getWidth();

            // on swipe the active item will be positioned from [-width, 0]
            // interpolate offset for smooth animation
            float progress = mInterpolator.getInterpolation(left * -1 / (float) width);

            drawHighlights(c, indicatorStartX, indicatorPosY, activePosition, progress, itemCount);
        }

        private void drawInactiveIndicators(Canvas c, float indicatorStartX, float indicatorPosY, int itemCount) {
            mPaint.setColor(colorInactive);

            // width of item indicator including padding
            final float itemWidth = mIndicatorItemLength + mIndicatorItemPadding;

            float start = indicatorStartX;
            for (int i = 0; i < itemCount; i++) {
                // draw the line for every item
                c.drawLine(start, indicatorPosY, start + mIndicatorItemLength, indicatorPosY, mPaint);
                start += itemWidth;
            }
        }

        private void drawHighlights(Canvas c, float indicatorStartX, float indicatorPosY,
                                    int highlightPosition, float progress, int itemCount) {
            mPaint.setColor(colorActive);

            // width of item indicator including padding
            final float itemWidth = mIndicatorItemLength + mIndicatorItemPadding;

            if (progress == 0F) {
                // no swipe, draw a normal indicator
                float highlightStart = indicatorStartX + itemWidth * highlightPosition;
                c.drawLine(highlightStart, indicatorPosY,
                        highlightStart + mIndicatorItemLength, indicatorPosY, mPaint);
            } else {
                float highlightStart = indicatorStartX + itemWidth * highlightPosition;
                // calculate partial highlight
                float partialLength = mIndicatorItemLength * progress;

                // draw the cut off highlight
                c.drawLine(highlightStart + partialLength, indicatorPosY,
                        highlightStart + mIndicatorItemLength, indicatorPosY, mPaint);

                // draw the highlight overlapping to the next item as well
                if (highlightPosition < itemCount - 1) {
                    highlightStart += itemWidth;
                    c.drawLine(highlightStart, indicatorPosY,
                            highlightStart + partialLength, indicatorPosY, mPaint);
                }
            }
        }

how to do that properly ..thanks

EDIT: error exception (after BenP. solution)

java.lang.RuntimeException: Unable to start activity ComponentInfo{ma.ac.iav.menunaviagtion/ma.ac.iav.menunavigation.testanat.JustCoverFlowActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6541)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
    at com.github.bleeding182.recyclerviewdecorations.viewpager.LinePagerIndicatorDecoration.<init>(LinePagerIndicatorDecoration.java:55)
    at ma.ac.iav.menunavigation.testanat.JustCoverFlowActivity.onCreate(JustCoverFlowActivity.java:57)
    at android.app.Activity.performCreate(Activity.java:6975)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
Zouhair
  • 145
  • 1
  • 2
  • 13
  • `a lot of unresolved codes starting from if bloc ` be specific and post complete code, class etc – Pavneet_Singh Aug 31 '18 at 20:34
  • Why do you want to do this programmatically? My general recommendation would be to use the resources framework to solve this issue. – Ben P. Aug 31 '18 at 20:37
  • @Pavneet_Singh, the rest of the code is unrelated to the matter ..but i should state that this code belong to nonactivity class ..(PS the class is for paging a recyclerview) – Zouhair Aug 31 '18 at 20:44
  • @BenP. How to do that ..i'm 2months into android dvlpt now ..so i'm kind new , thanks for the help – Zouhair Aug 31 '18 at 20:45
  • @Pavneet_Singh for unresolved codes ..i meant from the if bloc to the end of the code i've posted ..not the entire class ..thansk for the help – Zouhair Aug 31 '18 at 20:49
  • can you post the error details although that why I asked you to post the code , can't help without full info – Pavneet_Singh Aug 31 '18 at 20:50
  • `context` is not initialised and use https://stackoverflow.com/questions/2795833/check-orientation-on-android-phone – Pavneet_Singh Aug 31 '18 at 20:55
  • @Pavneet_Singh how that is duplicate for the other question ..i've applied a solution there and it didn't work ..that doesn't mean it's duplicate!! Plus the context is intialized .. – Zouhair Aug 31 '18 at 21:40
  • Pavneet_Singh : remove the duplicate ..so people can answer! – Zouhair Aug 31 '18 at 21:54
  • the solution you selected is there in the duplicate , probably 3rd or 4th answer. that's why I marked it as a dupe otherwise I won't if there's a slightly different requirement – Pavneet_Singh Sep 01 '18 at 01:31
  • if you know the solution, then you should point at it ..i don't put questions randomly ..i search hours before giving up ..with all respect, be gental to new people to android ..thanks! – Zouhair Sep 01 '18 at 12:59

1 Answers1

1

Assuming that there's not some reason that you must accomplish this programmatically, the best solution would be to leverage the Android Resources Framework to do this for you.

Step one is to create two different dimens.xml files, one for portrait orientation and one for landscape orientation. Your directory structure should look like this:

src/
    main/
        res/
            values/
                dimens.xml
            values-land/
                dimens.xml

Your dimens.xml will define the dimension resource. For portrait:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="indicator_height">200dp</dimen>
</resources>

For landscape:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="indicator_height">100dp</dimen>
</resources>

Now, in your java code, you can just access this dimension value directly:

int height = context.getResources().getDimensionPixelSize(R.dimen.indicator_height);

Because you have both a values/ and a values-land/ version of this dimension, you will find that the value for height changes based on the device orientation.

Note that height will be in pixels, so it is unlikely to just be 200 or 100. Many screens will have something like 2.5 pixels per dp, so you'd see 500 or 250 (though your device could be anything, really).

Ben P.
  • 52,661
  • 6
  • 95
  • 123