Applying style to views dynamically in java code

In my answer to Applying style to views dynamically in java code on Jun 25 at 18:51, I thought setting a style to a view dynamically would be as simple as passing the style to the constructor of your view. A couple of minutes ago, I had a notification and a comment (Thank you for it) saying that this does not work. I had a freaking -1 ):

My first solution was to override the constructors and pass the style as a third parameter to the View(android.content.Context, android.util.AttributeSet, int) constructor in this manner:
public StyledButton(Context context) {
    super(context, null, R.style.Button_PrayerTimeButton);
//... whatever
}

public StyledButton(Context context, AttributeSet attrs) {
    super(context, attrs, R.style.Button_PrayerTimeButton);
//... whatever
}

public StyledButton(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, R.style.Button_PrayerTimeButton);
//... whatever
}

So, obviously this did not work although according to the documentation of the third parameter of the constructor:
The default style to apply to this view. If 0, no style will be applied (beyond what is included in the theme). This may either be an attribute resource, whose value will be retrieved from the current theme, or an explicit style resource.
Anyway, now that an explicit style resource is another dead end, I had to find a work around!
And here it is: Instead of supplying a style to the constructor (which again doesn't work for some unknown native reason), you have to supply an attribute and define that attribute in your theme as follows:

styles.xml:


<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <item name="@attr/gangnamStyle">@style/myDefaultStyle</item>
    </style>

    <attr name="gangnamStyle" format="reference" />

    <style name="myDefaultStyle" parent="@android:style/Widget.Button">
        <item name="android:background">#f00</item>
    </style>

</resources>

StyledButton.java:


public class StyledButton extends Button {

 public StyledButton(Context context) {
  super(context, null, R.attr.gangnamStyle);
 }

 public StyledButton(Context context, AttributeSet attrs) {
  super(context, attrs, R.attr.gangnamStyle);
 }

 public StyledButton(Context context, AttributeSet attrs, int defStyle) {
  super(context, null, R.attr.gangnamStyle);
 }
}

Finally, you just have to set the theme of the Activity or Application to your Theme (in this case AppBaseTheme) :
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppBaseTheme" >

And that's it! Enjoy


Click here for Sample Project + Source Code (download)

23 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. hello sherif, I wanted to know from you if there could be any solution where I get color code from web and according I can change color of all my buttons runtime without going to all particular buttons and applying BackGround color, could there be any solution using theme or style? Please share any suggestion you have.

    please also check this question :- http://stackoverflow.com/questions/22529646/android-app-apply-color-theme-dynamically-at-runtime

    ReplyDelete
    Replies

    1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.

      Delete
  3. Really Nice Information,Thank You Very Much For Sharing.
    Web Development Company

    ReplyDelete
  4. Can we use other method for this problem ?
    Example : I have more than one button style. How to use them style (from css) programmatically ?
    Thank you

    ReplyDelete
  5. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training India . Nowadays Java has tons of job opportunities on various vertical industry.

    ReplyDelete
  6. Developed using the structured yet friendly Java language, Android mobile applications span a range of functions from utility to enterprise apps, catering to almost all requirements of the next generation mobile users including music, videos, shopping, bill payments, banking, web-based apps, social networking and instant messaging.gerald winata gozali

    ReplyDelete

  7. Very good information. Its very useful for me. We need learn from real time examples and for this we choose good training institute, we need to learn from experts . So we make use of demo classes . Recently we tried java demo class of Apponix Technologies.
    https://www.apponix.com/Java-Institute/Java-Training-Institute-in-Bangalore.html

    ReplyDelete
  8. Read the information you share, it is very helpful for me. Hope I will learn more interesting information on your blog.
    Đến với Proship khách hàng sẽ được sử dụng những dịch vụ tốt nhất, chất lượng nhất, thời gian nhanh nhất và đặc biệt giá cả cạnh tranh nhất.
    Dịch vụ vận chuyển ô tô
    Dịch vụ cho thuê xe tải
    Vận chuyển xe máy bằng tàu hỏa
    Dịch vụ chuyển hàng bằng container,...

    ReplyDelete
  9. the number of global social media consumers is predicted to reach about 3.1 billion people. With customersusing social media each and every single day, this poses a wonderful chance for businesses who wish to reach their audience. Marketing through social mediaNot only are your customers on social media, but there is a Good probability of them are currently assessing these sites daily. Connecting with your target audience can be easy if You're Active on the stations that they use https://buy-followers.org/product/buy-10000-instagram-followers/

    ReplyDelete
  10. Even once an influencer creates a complete ITC new, you Can still collaborate. You can sell their product on your stores as a
    formal partner, how Nordstrom did with Ankari Floruss.

    Ankari Floruss partner with Nordstrom

    (Supply )

    Product off the floor, there's a good chance they'll be happy to continue promoting your products.

    Just be wary of influencers whose goods are in direct Competition with yours.

    4. Listen (and Talk) to Your Influencer

    Collaboration is a key part of a winning influencer marketing strategy. You're the expert on your brand, and they're the expert on
    the audience you're trying to achieve.

    The way to best reflect your goods to their followers.

    Give them brand guidelines to follow so their content remains True to the image and voice you have created for your business. By
    way of example, are they allowed to declare when they create branded content? If not, the influencer needs to know.

    At the same time, ask about what functions with their viewers.

    Find out what Sort of content works best with their Followers, and if they believe one line of the goods may work better compared
    to another. The influencer knows their audience best, which means that your partnership will be successful if you give them a few
    creative liberty.
    https://buymorefollower.com

    ReplyDelete
  11. Taking Games is just a free game but it contains adult content and discretionary in-app purchases to get Real Money. You might want to keep description it away from your kiddies. Give us 5 stars evaluation for encouraging us to improve the game continuously. Go to war online and prove that your sniper shooting skills within the king of multiplayer 3D sniper games.

    ReplyDelete
  12. The Takeaway
    Brand? Make certain that you take advantage of your own influencer marketing plan by
    following the suggestions above to make an effective, high-converting TikTok
    marketing effort.



    Start reaching out to those influencers on TikTok, place those
    Targets and aims, and keep experimenting to understand your brand image burst.

    content!

    It is important not to rely solely on the influencers following to deem the TikTok Influencer activity successful. One would have to consider the key points that they would like for the influencer to relay. We will assist you with structuring and executing content marketing activities, to ensure that we catch the user’s attention.

    Our TikTok influencers will create trendy and viral videos that will generate awareness to your product or service. We will track every heart (similar to Instagram likes) and number of comments, and an extensive report will be created for you at the end of each camp
    Bring You A Solid ROI
    A number of marketing professionals find it challenging to calculate an accurate ROI for an influencer marketing campaign. Due to our tools and expertise, this is not a challenge for The Influencer Marketing Factory.Buy Tiktok Likes UK

    ReplyDelete
  13. They're limited enough that her post is probably going to be found through pursuits. Suppose she had utilized #food or #goodeats. Those hashtags aren't close to as extraordinary and her post would most likely get lost. Label your area and applicable clients when conceivable Whenever it's conceivable, attempt to label your area. It builds the odds that others in your general vicinity would have the option to discover you. Individuals like to follow similarly invested individuals. Additionally, ensure you label applicable clients at whatever point conceivable too. On the off chance that you snap a photo while you're eating out at an eatery, check and check whether that café has an Instagram. On the off chance that they do, make certain to label them in your photograph on the grounds that there's a decent possibility they could repost it or offer it to their story. By labeling them, it expands the odds that they will look at your post, similar to it, remark on it, and perhaps share it with their devotees. Any possibility you need to label a pertinent client, put it all on the line since it can just expand your compass on Instagram. See additionally: How to transfer photographs to Instagram on your PC Instagram is a network – be drawing in Remember that Instagram gives you the ideal occasion to associate with individuals. buy instagram followers singapore

    ReplyDelete
  14. If you run a local business or wish to attract local followers, then it is a good idea to add geotags to your media content. Instagram gives users the ability to search for local content. If you want to target these local users, you need to use geotags to do so. Geotags are basically a form of local search engine optimization.

    There are online tools that let you generate local geotag metadata for your images and videos. You can find apps that let you do this too. If you’re successful, then you’ll have more local viewers following your channel.
    Instagram gives users many ways to add a “call to action” to their posts. A call to action would be something like “shop now,” “click here,” or “share this content.” The purpose is to motivate users to take any action that helps your business or channel in some way.

    If you encourage people to follow your channel or share your content, then you should see an increase in your channel’s follower count rather quickly.
    https://rizzwanhussain1.medium.com/

    ReplyDelete
  15. Combine this with the teledensity and GPS (global positioning system) coverage. It is estimated that Pakistan has 169 million unique subscribers of which 87m are smartphone users. With the recent introduction of smartphones built especially for the masses, smartphones with long-life batteries, all popular applications built-in, and the phone provided free of cost if the customer agrees to a 12-month post-paid contract, it is expected that smartphones will be 80pc of the market within 3 years.

    Ownership of a smartphone enables a user to access apps. YouTube leads the market with 44m monthly active users (MAU), followed closely by Facebook with 36m MAU and then TikTok at 24m MAU. The number then drops for Instagram at 6m and Twitter at 4 million. LinkedIn has 6m users in Pakistan. Local apps are also showing scale and some have the potential to become super apps. As these apps scale up, they will also become potential mediums for social media marketing.


    https://medium.com/@rizzwanhussain1/buy-instagram-followers-3a66e21f9aee

    ReplyDelete
  16. That's right -- they suppose these 10 shares are even better buys. See the 10 stocks *Stock Advisor returns as of October 20, 2020 CONSTELLATION BRANDS, INC. Jason Hall: Here's some other one, any other tech stock this is having a terrible day. Facebook, ticker FB, it's down like 6% proper now. Daniel, you need to inform us what's happening there? Daniel Sparks: Yeah. Facebook. Again, same issue we are seeing in advertising and marketing: an acceleration in Q3 from 11% sales growth to 22% boom. Management did suggest they assume a similarly acceleration in Q4, which I assume turned into absolutely exciting given the uncertain environment proper now. It just really goes to reveal this digital transformation it's happening. But what can be weighing on the inventory nowadays is a few unease throughout the earnings call. I suppose a number of the remarks from the CFO and the press release approximately 2021 -- approximately the future. What management is essentially saying goes into subsequent year, there may be primary concerns that could be headwinds on revenue boom. One of them sounds like perhaps a hard comparison, and that could be because, as we are seeing here, this changed into a very robust sector, Q4 is probably even stronger. https://buymorefollower.com/buy-instagram-followers-singapore

    ReplyDelete
  17. Get The 2020 Ultimate Instagram Influencer & Marketing Bundle for $10.50 with promo code BFSAVE70. 8. The 2020 Complete Digital Copywriting Master Class Bundle You may understand all of the technical aspects of digital advertising, however if you can not write compelling replica, you are dead inside the water. This complete bundle will educate you the way to write for social media, emails, blogs, and extra channels. This is how you will turn site visitors into buyers. Get The 2020 Complete Digital Copywriting Master Class Bundle for $11.70 with promo code BFSAVE70. nine. The Complete Content Creator Bundle for YouTube Believe it or not, you really can make cash on YouTube. If you're inquisitive about video advertising, YouTube is the platform to be on. In this path, you'll learn how to start and develop your channel via established methods. Get The Complete Content Creator Bundle for YouTube for $12 with promo code BFSAVE70.
    https://buymorefollower.com/buy-instagram-followers-greece

    ReplyDelete
  18. Click the notification you want to see and it will automatically take you to the picture where they have responded. Certainly, we all love this technological age, and when we have platforms like Instagram, description
    that are always updated and offer us new features, we don't ever wish to leave them. In the event that you enjoyed what you read, how to find out what photographs someone likes on Instagram, then keep learning on our blog the best way to observe stories on Instagram without looking, you can not lose it. If you wish to know how to view Instagram stories without being viewed, then this article is made for you.

    ReplyDelete