Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to color some percent of a layout?

Tags:

android

I want to color e.g. 20 percent of layout background and after some time color 40 percent of it and so on. How can I achieve this in android ?

like image 255
Obtice Avatar asked Aug 23 '16 16:08

Obtice


2 Answers

You can start off with a ClipDrawable. This will clip another drawable — for instance, a ShapeDrawable — based on the drawable level.

Then in your timer callback:

    int level; // from 0 to 10000 = 100%

    view.getBackground.setLevel(level);

Drawable#setLevel


EDIT: Here's an example:

  1. Define the shape drawable in /res/drawable. Call it bkgd_shape.xml.

    <?xml version="1.0" encoding="utf-8"?>
    <shape
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <solid android:color="@color/background"/>
    </shape>
    
  2. Define the background drawable in /res/drawable. Let's call it bkgd_level.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <clip
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:drawable="@drawable/bkgd_shape"
        android:clipOrientation="horizontal"
        android:gravity="left|clip_horizontal|fill_vertical"/>
    

    You might be able to put a color in directly for the drawable source, but I haven't tried it.

  3. Set it as the background of your layout:

        android:background="@drawable/bkgd_level"
    
  4. Call setLevel on the drawable:

        int level; // from 0 to 10000 = 100%
    
        view.getBackground.setLevel(level);
    
like image 74
kris larson Avatar answered Sep 20 '22 10:09

kris larson


You can put any type of view in the background and update it's with and set the color you'd like it to have dynamically.

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);

int width = dm.widthPixels;
int height = dm.heightPixels;

Expanding across the width then, just go by percentage.

int percentChange = .2; //Update this accordingly, put in its own function possibly
int backgroundWidth = width * percentChange;

For example, using an imageView in the background:

ImageView background = (ImageView) findViewById(R.id.expandingBackground);
background.requestLayout();
background.getLayoutParams().width = backgroundWidth;

Hope that helps, good luck.

like image 39
Steeno Avatar answered Sep 20 '22 10:09

Steeno