Pranav
Pranav

Reputation: 4250

How to make Percent dynamic in PercentRelativeLayout?

I am using PercentRelativeLayout from Design Support Library and i want to set different Percentage for 7 inch and 10 inch tablet.

For example if i have ImageView like below.

<ImageView
     android:id="@+id/contactDoc"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     app:layout_widthPercent="70%"
     app:layout_heightPercent="70%"
     android:layout_centerHorizontal="true"
     android:clickable="true"
     android:src="@drawable/dashboard_contactdoctor" />

now if i want to set 70% for 7 inch tablet and 60% for 10inch tablet without making different layout folder like sw720dp . Can i do it? Help is appreciated.

Upvotes: 1

Views: 757

Answers (4)

Yury Fedorov
Yury Fedorov

Reputation: 14938

First of all, you are going to need to detect 7" or 10" tablet. I assume that you already know how to do it based on your question. If not, check out this great answer.

After you know what device are you dealing with, use the following code to put inside an if condition (or somewhere else) to define the percentage of your view in code:

    View view = findViewById(R.id.yourView);
    PercentLayoutHelper.PercentLayoutParams params =
            (PercentRelativeLayout.LayoutParams) view.getLayoutParams();
    PercentLayoutHelper.PercentLayoutInfo info = params.getPercentLayoutInfo();
    info.heightPercent = 0.60f;
    view.requestLayout();

Based on another great answer.

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1007296

Those percentages are fraction resources. You should be able to set up res/values/fractions.xml and res/values-sw720dp/fractions.xml, where you define the values for the fractions. Then, use @fraction/whatever_you_called_it in the layout.

Upvotes: 1

Mithun Sarker
Mithun Sarker

Reputation: 4023

Try using constraint layout, it is available on android studio 2.2 and after .

By using this, you can add both vertical and horizontal guideline according to screen percentage and then you set the height and width of your imageview relative to those guideline

Upvotes: 0

Katharina
Katharina

Reputation: 1642

You can use different layouts for different screen sizes. You can read more about it in the documentation: https://developer.android.com/training/multiscreen/screensizes.html

A possibility wihtout providing multiple layouts would be to place the ImageView inside a LinearLayout with a android:weightSum of 10 and then set the weight of the ImageView programmatically:

LinearLayout.LayoutParams layoutParams = yourView.getLayoutParams();
layoutParams.weight = WHATEVER;
yourView.setLayoutParams(layoutParams);

Upvotes: 0

Related Questions