Create Rounded Shapes to apply Button background dynamically

Create Rounded Shapes with colours, and apply Button stateslist as background dynamically

While working on applying dynamic themes to app screens, I happen to work on applying Rounded Shapes with the colours dynamically, to display button states (i.e. default, pressed or focused etc) and also Text colors based on the colour codes in API response.

Rounded Shapesrounded_gray

below is the sample XML API response which shows color codes and XML data.

XML Color codes

 <!-- sample xml data -->
<DefBtnColour>#24014c</DefBtnColour>
<SelBtnColour>#5656ff</SelBtnColour>
<DefBtnFontColour>#afdbb6</DefBtnFontColour>
<SelBtnFontColour>#aa0197</SelBtnFontColour>

Applying shapes and button colour states is easy by creating a selector xml file in drawable folder. but applying dynamically need some more insight to implement in code.

Here is the code snippet… for it

First implemented two rounded shapes with <DefBtnColour> and <SelBtnColour> colours data, using ShapeDrawable class.

Rounded Shapes drawables using ShapeDrawable class

float[] radii = new float[8];
radii[0] = getResources().getDimension(R.dimen.spacing_10); //spacing_10 is 10dp
radii[1] = getResources().getDimension(R.dimen.spacing_10);
radii[2] = getResources().getDimension(R.dimen.spacing_10);
radii[3] = getResources().getDimension(R.dimen.spacing_10);

radii[4] = getResources().getDimension(R.dimen.spacing_10);
radii[5] = getResources().getDimension(R.dimen.spacing_10);
radii[6] = getResources().getDimension(R.dimen.spacing_10);
radii[7] = getResources().getDimension(R.dimen.spacing_10);

ShapeDrawable selShape = new ShapeDrawable();
selShape.setShape(new RoundRectShape(radii, null, null));
selShape.getPaint().setColor(selectedColour);

ShapeDrawable defShape = new ShapeDrawable();
defShape.setShape(new RoundRectShape(radii, null, null));
defShape.getPaint().setColor(defaultcolour);

now add these shapes to the StateListDrawable for default and pressed states..

StateListDrawable stateListDrawable = new StateListDrawable();
stateListDrawable.addState(new int[] {android.R.attr.state_pressed}, selShape);
stateListDrawable.addState(new int[] {}, defShape);

now you can return this stateListDrawable object to apply button background drawable.

whole code snippets is below

 //step 1
protected StateListDrawable applyButtonSelector(int defaultcolour,int selectedColour){
    float[] radii = new float[8];
    radii[0] = getResources().getDimension(R.dimen.spacing_10);
    radii[1] = getResources().getDimension(R.dimen.spacing_10);
    radii[2] = getResources().getDimension(R.dimen.spacing_10);
    radii[3] = getResources().getDimension(R.dimen.spacing_10);

    radii[4] = getResources().getDimension(R.dimen.spacing_10);
    radii[5] = getResources().getDimension(R.dimen.spacing_10);
    radii[6] = getResources().getDimension(R.dimen.spacing_10);
    radii[7] = getResources().getDimension(R.dimen.spacing_10);

    ShapeDrawable selShape = new ShapeDrawable();
    selShape.setShape(new RoundRectShape(radii, null, null));
    selShape.getPaint().setColor(selectedColour);

    ShapeDrawable defShape = new ShapeDrawable();
    defShape.setShape(new RoundRectShape(radii, null, null));
    defShape.getPaint().setColor(defaultcolour);

    StateListDrawable stateListDrawable = new StateListDrawable();
    stateListDrawable.addState(new int[] {android.R.attr.state_pressed}, selShape);
    stateListDrawable.addState(new int[] {}, defShape);
    return stateListDrawable;
}

apply to button background as below

//step 2
themeBtn.setBackgroundDrawable(applyButtonSelector(convertToColorInt(DefaultButtonColour), convertToColorInt(SelectedButtonColour)));

below is the code to convert response colour code text to integer colour code

public static int convertToColorInt(String argb) throws IllegalArgumentException {
   if (!argb.startsWith(HASH)) {
      argb = HASH + argb;
   }
   return Color.parseColor(argb);
}

with this code (step 1,2) you can see,  shape and states drawable applied to button dynamically.

To apply ColorStates for button text you can see this post or SO ref link.

Hope this helps somebody…

ref links: http://stackoverflow.com/a/16502692/341443
http://stackoverflow.com/a/5963179/341443

🙂

You may be also interested in

 

Android Studio ADB wipes out logcat quickly when app crashes

Android Studio ADB wipes out logcat quickly

At time we may face this kind of annoying issue. In Android Studio, in Android tab ADB wipes out log cat data quickly when app crashes. And makes us not able to find out the code issue.

wipes out

To solve this issue, in Android tab on right side you can see dropdown to select the log filter

logcat2

Select Edit Filter Configuration, and you will see this window

logcat3

In this window, set your application Package Name as shown in  above image. You can set any Filter Name text. and Click OK.

Now, if app crashes, it will show the log data.

Hope it helps somebody…

 

You may also interested in

Unable to resolve superclass of Activity

Unable to resolve superclass

When you added Android Support library to your project in Eclipse ADT, to implement classes like FragmentActivity, ViewPager etc At times you may see this error which results in app crash due to Unable to resolve superclass,

Unable to resolve superclass of Lin/AppPath/MainActivity; (9)
05-16 14:10:11.705: W/dalvikvm(6534): Link of class 'Lin/AppPath/MainActivity;' failed
05-16 14:10:11.705: D/AndroidRuntime(6534): Shutting down VM
05-16 14:10:11.705: W/dalvikvm(6534): threadid=1: thread exiting with uncaught exception (group=0x41ba5c08)
05-16 14:10:11.705: E/AndroidRuntime(6534): FATAL EXCEPTION: main
05-16 14:10:11.705: E/AndroidRuntime(6534): Process: , PID: 6534
05-16 14:10:11.705: E/AndroidRuntime(6534): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{/.MainActivity}: java.lang.ClassNotFoundException: Didn't find class ".MainActivity" on path: DexPathList[[zip file
......
....

There may be a chance that Android Private Library, not exported while generating API file. Due to Android Private Libraries is unchecked in Order and Export tab in Java build path dialog as shown below. resolve superclass So, just check the Android Private Libraries and Click Ok. Clean and Build the app. Fixes the issue.

private_Library1

Hope it helps somebody. 🙂

You may be also interested in

ScrollView auto scroll to show content in app screen

While displaying long text data or displaying data in lot of views, we use ScrollView to view whole screen by scrolling. At times we may require app to auto Scroll down in a screen to show a bottom content.

If you try using below code in Activity’s OnCreate method to scroll down in ScrollView

ScrollView mScrollView = (ScrollView) findViewById(R.id.myScrollView);
mScrollView.fullScroll(ScrollView.FOCUS_DOWN);

It won’t scroll. Since the layout is not yet done adding all views and you call fullScroll immediately after instantiating the ScrollView.

Solution for ScrollView to auto scroll down

auto scroll

To solve this issue, A short delay gives, the system enough time to settle. You have to use following code to set the delay

mScrollView.postDelayed(new Runnable() {
    @Override
    public void run() {
       //replace this line to scroll up or down
       mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
    }
}, 100L);

voila, you can see app Scroll down to bottom of screen.

Similarly, If you want to set Scroll to top of screen, in above run() method replace line with

mScrollView.scrollTo(0, 0);

If you are using HorizotalScrollView, and if you want to move to right end of screen, use following code..

mHorizontalScrollView.postDelayed(new Runnable() {
    @Override
    public void run() {
      mHorizontalScrollView.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
    }
}, 100L);

here mHorizontalScrollView is object of HorizantalScrollView.

Hope it helps somebody.

🙂

You may be also interested in

Display AlertDialog with Multiple Options

AlertDialog with Multiple Options

Hi Guys, At times you may require to show multiple options in a dialog on Acitivty. So user can select any one option. here is the simple code to display with AlertDialog with Multiple Options

CharSequence options[] = new CharSequence[] {"Call", "SMS", "Email"};

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Select your option:");
builder.setItems(options, new DialogInterface.OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {
      // the user clicked on options[which]
   }
});
builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {
      //the user clicked on Cancel
   }
});
builder.show();

You can see as shown below

AlertDialog

Cheers …:)

You may be also interested in

Logcat Clearing too Fast- Eclipse

While running app on latest android devices, from ADT Eclipse, you may find difficulty in viewing LogCat data. As lots of other background services of different apps are running, logcat clearing out in a glimpse.

At this kind of situation, To view LogCat data you have to change a Eclipse setting as shown below..

Goto Window ->Preferences -> In left panel expand Android -> select LogCat -> here in right panel you can see Maximum number of LogCat messages to buffer set as 5000,

Change this value to some large number like 500000. Click Apply and then Ok. (You may get a Error notifying a preference change listener. just ignore it.)

logcat clearing

Now you can able to see LogCat data.

Hope it helps somebody.

Cheers 🙂

 

You may be also interested in

Could not resolve com.android.support:support-v4:22.0.0, Android Studio

While implementing Push Notifications, I get this error Could not resolve all dependencies for configuration

I’ve installed Google Play Services and Google Repository using SDK manager

not resolve

and added the following dependencies in gradle file

dependencies {
   compile 'com.google.android.gms:play-services-gcm:7.0.0'
   ....
}

When I run the app, I see following error,

Could not resolve all dependencies for configuration ':library:_debugCompile'.
> Could not resolve com.android.support:support-v4:22.0.0.
Required by:
:library:unspecified > com.google.android.gms:play-services:7.0.0 > com.google.android.gms:play-services-base:7.0.0
> No cached version of com.android.support:support-v4:22.0.0 available for offline mode.

After searching solution for a while, I found the issue is due to this  “You need to make sure you have Android Support Repository up to date – that is where Android Support Library dependencies are resolved.”

So, I installed Android Support Repository,

fix_issue
and Rebuild app… Fixed the issue.

Hope it helps somebody..

ref link: http://stackoverflow.com/a/29569756/341443

Authentication is required. You need to sign in to your Google Account. -Google Play In-App Purchase(IAP)

Issue: Google Play In-App Purchase(IAP)

While working with Google Play In-App Purchase feature, follows

After uploading Trivial Drive app in Alpha Testing, and configuring Store listings and In App products and charges, published app in Google Play Developer Console.

While testing the Trivial Driver app,

TrivialDriverApp

on a device with test account… Im able to Buy Gas

IBP_buygas1

but when i tried to click on button for Upgrade My Car, or Get Infinite Gas, I see following error

In-App Purchase

At first I just confused about it. Later I find that there is a difference between Product Id that I created in In-App Products Developer console, and SKU_Productid constants written in code. as shown below In code

 // SKUs for our products: the premium upgrade (non-consumable) and gas (consumable)
    static final String SKU_PREMIUM = "premium";
    static final String SKU_GAS = "gas";

    // SKU for our subscription (infinite gas)
    static final String SKU_INFINITE_GAS = "infinite_gas";

In In-App Products

in-app_procucts

SO, I just changed code for SKU_ProductId constants to match with In-App products created in Developer console. And Changed application version code and name in manifest file, Generated new APK file and uploaded to Developer console Alpha Testing. After 2-3 hours waiting, its got published.. and I see everything is working fine. to summarize whole thing, you just need to use same SKU_ProductId in code, which is created in In-App Products developer console.

Hope it helps somebody…

Few other reference for In-App Billing app testing

http://developer.android.com/training/in-app-billing/test-iab-app.html

** https://help.gamesalad.com/hc/en-us/articles/203536123-7-6-In-App-Purchases-IAP-for-Google-Play

* https://blahti.wordpress.com/2014/07/30/how-to-add-in-app-billing-in-android-part-1/ http://android.stackexchange.com/a/40827/101168

 

onActivityResult always getting Result_Canceled from TabActivity

Recently while working with tabs, I see this situation onActivityResult , always getting 0(RESULT_CANCELLED).

I have four activities A-Activity,B-TabActivity,C-Activity, D-Activity. where A starts TabActivity B, and in this TabActivity, Im displaying 2 tabs C and D as child activities.

I need result from C or D whether success or not when Activity closed. So I started TabActivity B which displays C and D as tabs.. as shown below,

Intent intent = new Intent(this, TabActivityB.class);
startActivityForResult(intent,REQUEST_CODE_PAYMENT);

now after getting required information in Activity C, I closed Activity C by setting result as below

Intent data = new Intent();
setResult(Activity.RESULT_OK,data);
finish();

and when i check the resultCode in Activity A, in

onActivityResult(int requestCode, int resultCode, Intent data)

method, Im always getting

0(RESULT_CANCELLED)

Solution to handle this onActivityResult issue,

In child Activity C and D, before finish we should check the getParent() method null or not… and then setResult accordingly… as shown below,

Intent data = new Intent();
if (getParent() == null) {
setResult(Activity.RESULT_OK, data);
} else {
getParent().setResult(Activity.RESULT_OK, data);
}
finish();

After applying this change, Im able to get the exact resultCode in Activity A.

Hope it helps somebody..

Cheers 🙂

Ref link & credits:http://stackoverflow.com/a/2621390/341443

You may also interested in

 

Keytool error :java.io.IoException:Incorrect AVA format

When trying to generate new APK file in ADT Eclipse editor, using Android Tools-> Export Signed Application package. I see this following Keytool error as belowkeytool error

Solution for Keytool error

After searching for a while, I found the issue is due to entering invalid characters like comma(,), Plus (+) etc signs in Key creation dialog. So after removing it, Im able to generate APK file successfully.
Hope it helps somebody.

Cheers 🙂

You may be also interested in