Understand and Implement Custom Views in Android - Part 1 by ideba

View this thread on steempeak.com
· @ideba ·
$21.91
Understand and Implement Custom Views in Android - Part 1
<center>https://i.imgur.com/puH4Dfh.png</center>

**Repository**

https://github.com/enyason/custom_view

### What Will I Learn?

- How custom views works
- How to extend a built in view

   

### Requirements

- System Requirements : Java JDK, Android Studio
- OS Support for Java : Windows, mac OS, Linux
- Required Knowledge : A fair knowledge of Java ,OOP and Android Studio

### Resources for Java and this tutorial

- Oracle Website - <https://www.oracle.com/index.html>
- Java Docs -  <http://www.oracle.com/technetwork/java/javase/documentation/api-jsp-136079.html>
- Android Docs - https://developer.android.com/docs



- **Difficulty**
  Beginner

### Tutorial Duration 20- 25 Minutes

### Tutorial Content

This is the first part of this tutorial series. By the end of this part 1, we are going to have understanding of custom views in android and how to implement it.



### Android Views

we can categorize android built in views into 3:

- Simple view
- Container
- Compound control 

The simple view could be a TextField, a TextView or a Button. it displays one simple piece of information.

<center>
![textfield.png](https://cdn.steemitimages.com/DQmSsDojW2GiPh1rNGsg42i8uawM5fUZmDchmbBBPaAgfBk/textfield.png) </center>

<center>![colored-button.gif](https://cdn.steemitimages.com/DQmZkaGDPip95JdgcaYmd2tTk5V3kkEVegDofA1Zg2w1f1i/colored-button.gif)</center>

The container contains other views. Example of the container view includes: Linear Layout, Grid View, Relative Layout etc.

**GridView**


<center>
![gridview.png](https://cdn.steemitimages.com/DQmVhJGDE8Gt6h2jpe9g57AGFNofne1SGQ72pB17syWpwcS/gridview.png)</center>





**LinearLayout Vs RelativeLayout**





<center>![linearlayout vs relative layout.jpeg](https://cdn.steemitimages.com/DQmekkzC4PhfAe5Xux4k5HNoTG1aDUEjG6jGQUV12rmnH33/linearlayout%20vs%20relative%20layout.jpeg)</center>



The compound control is similar to container in that it has multiple views inside of it. It also has specific views inside. Example is a time picker.



**TimePicker**



<center>![time picker.png](https://cdn.steemitimages.com/DQmam6E1PdpA6TB9fbJjJLXqzUmaRqiQDyT8j2hR9d36z4b/time%20picker.png)</center>



### Why Custom Views

Most times we would love to have looks and feels that goes far beyond what the android built in views offers. To achieve this we either extend any of the built in views (e.g textview, framelayout ) or we directly extend the view class if we want to have full control of the custom element. The following are advantages of using custom views

1. Modularize repeated code: Putting code you often use into a custom component
2. Access protected methods: Inheriting a view gives you access to overriding methods
3. Optimize rendering speed: You can reduce the number of views you are drawing on screen and hence optimize rendering speed.
4. Complete control with the draw, measure and layout



### Extending Built in Views

The simplest way to build a custom view is to extend a simple view (Android Built in component). To do this, you pick a view that is close to what you need and extend that so that you can reuse the parent class functionality while only writing codes for the parts you need. With this way, you don't have to handle all the drawing and layout complexity.

### Steps to Create a custom view

For this tutorial, we are going to extend the text view component

1. Choose a parent class view closest to what you need. We will use a Text View

2. we extend textview then we have 3 constructors, 1 for java, 1 for xml, and the other for xml with style

   ```
   public class UtopianTextView extends android.support.v7.widget.AppCompatTextView {
       public UtopianTextView(Context context) {
           super(context);
           init();
       }
   
       public UtopianTextView(Context context, @Nullable AttributeSet attrs) {
           super(context, attrs);
           init();
   
       }
   
       public UtopianTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
           super(context, attrs, defStyleAttr);
           init();
   
       }
   ```

   - After extending the built in text view, we have 3 constructors. Why is because this we can use this view in 3 ways
     - The first constructor allows you create this view in Java
     - The Second and the third are for using in XML. The difference between these two is that the 3rd constructor also allows you specify a style in XML
     - The `init()` method defines our extra functionalities  and is applied to all constructors. This is to ensure the view works as expected regardless of where it's being called, whether java or xml.

3. Add extra functionality

   ```
   void init() {
   
           setText("UtopianDroid");
           setTextSize(20);
           setTextColor(getResources().getColor(R.color.colorPrimary));
           setCompoundDrawablesWithIntrinsicBounds(null, 			getResources().getDrawable(R.drawable.ic_android), null, null);
           setOnClickListener(this);
   
       }
   ```

   In the `init()`method, add extra functionalities to our custom textview. 

   - We first set the text of our view to UtopianDroid
   - Then give it a size  of 20 points and the color to primary
   - We give it a top drawable to display an icon on the top.
   - We finally set an onclick listener for the view. Whenever the view is clicked, it will open up the utopian site

   ```
    @Override
       public void onClick(View v) {
         Toast.makeText(getContext(),"Hello Utopian",Toast.LENGTH_SHORT).show();
           Uri webPage = Uri.parse("https://utopian.io");
           Intent intent = new Intent(Intent.ACTION_VIEW, webPage);
   
           if (intent.resolveActivity(getContext().getPackageManager()) != null) {
   
               getContext().startActivity(intent);
           }
       }
   ```

   - This is our onClick method where we put the logic to navigate the user to the webpage.

   - the intent object is created with the action type and uri as parameters.

   - we then navigate to the web page if there is any supported application for the implicit intent defined 

     

Using the custom view we created above should reproduce what is in the image below


<center>![utopian_text_view.png](https://cdn.steemitimages.com/DQmYLCyR27AuLyNyTxMSq3UoU8BhMXxZqkdJ9EAiUVAZqKH/utopian_text_view.png)</center>


### Summary

To create a custom view

- we extend textview then we have 3 constructors, 1 for java, 1 for xml, and the other for xml with style

- Choose a parent class view closest to what you need

- Add extra functionality



Demo video of the app:

https://youtu.be/uLV5kRAzzDs



**Proof of Work** The complete source code can be found on [gitHub](https://github.com/enyason/custom_view) <https://github.com/enyason/custom_view>
πŸ‘  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 25 others
properties (23)
post_id71,646,832
authorideba
permlinkunderstand-and-implement-custom-views-in-android---part-1
categoryutopian-io
json_metadata{"tags":["utopian-io","tutorials","android","java","steemdevs"],"app":"steem-plus-app"}
created2019-03-18 09:48:00
last_update2019-03-18 09:48:00
depth0
children5
net_rshares33,505,753,475,714
last_payout2019-03-25 09:48:00
cashout_time1969-12-31 23:59:59
total_payout_value16.390 SBD
curator_payout_value5.522 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length6,781
author_reputation10,180,703,228,549
root_title"Understand and Implement Custom Views in Android - Part 1"
beneficiaries
0.
accountsteemplus-pay
weight100
1.
accountutopian.pay
weight500
max_accepted_payout100,000.000 SBD
percent_steem_dollars10,000
author_curate_reward""
vote details (89)
@steem-plus ·
SteemPlus upvote
Hi, @ideba!

You just got a **0.56%** upvote from SteemPlus!
To get higher upvotes, earn more SteemPlus Points (SPP). On your Steemit wallet, check your SPP balance and click on "How to earn SPP?" to find out all the ways to earn.
If you're not using SteemPlus yet, please check our last posts in [here](https://steemit.com/@steem-plus) to see the many ways in which SteemPlus can improve your Steem experience on Steemit and Busy.
properties (22)
post_id71,671,925
authorsteem-plus
permlinkunderstand-and-implement-custom-views-in-android---part-1---vote-steemplus
categoryutopian-io
json_metadata{}
created2019-03-18 20:49:48
last_update2019-03-18 20:49:48
depth1
children0
net_rshares0
last_payout2019-03-25 20:49:48
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length432
author_reputation247,995,867,762,997
root_title"Understand and Implement Custom Views in Android - Part 1"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@portugalcoin · (edited)
$9.80
Thank you for your contribution @ideba.
After reviewing your tutorial we suggest the following points listed below:

- Your tutorial is quite short for a good tutorial. We recommend you aim for capturing at least 2-3 concepts.

- We suggest you put comments in your code sections. The comments in the code are very important because it helps a lot less experienced readers to understand your code better.

- Images that aren't yours is necessary to put the source.

- It's interesting to have a short video with the presentation of the features that developed.

Thank you for your work in developing this tutorial.
Looking forward to your upcoming tutorials.

Your contribution has been evaluated according to [Utopian policies and guidelines](https://join.utopian.io/guidelines), as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, [click here](https://review.utopian.io/result/8/3-1-2-2-3-4-2-3-).

---- 
Need help? Chat with us on [Discord](https://discord.gg/uTyJkNm).

[[utopian-moderator]](https://join.utopian.io/)
πŸ‘  , , , , , , , , , , , , , , , , ,
properties (23)
post_id71,673,174
authorportugalcoin
permlinkre-ideba-understand-and-implement-custom-views-in-android---part-1-20190318t212323216z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"users":["ideba"],"links":["https:\/\/join.utopian.io\/guidelines","https:\/\/review.utopian.io\/result\/8\/3-1-2-2-3-4-2-3-","https:\/\/discord.gg\/uTyJkNm","https:\/\/join.utopian.io\/"],"app":"steemit\/0.1"}
created2019-03-18 21:23:24
last_update2019-03-18 21:23:54
depth1
children1
net_rshares14,454,993,679,944
last_payout2019-03-25 21:23:24
cashout_time1969-12-31 23:59:59
total_payout_value7.444 SBD
curator_payout_value2.356 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length1,110
author_reputation214,343,891,436,406
root_title"Understand and Implement Custom Views in Android - Part 1"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
author_curate_reward""
vote details (18)
@utopian-io ·
Thank you for your review, @portugalcoin! Keep up the good work!
properties (22)
post_id71,800,596
authorutopian-io
permlinkre-re-ideba-understand-and-implement-custom-views-in-android---part-1-20190318t212323216z-20190321t130757z
categoryutopian-io
json_metadata{"app":"beem\/0.20.17"}
created2019-03-21 13:08:00
last_update2019-03-21 13:08:00
depth2
children0
net_rshares0
last_payout2019-03-28 13:08:00
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length64
author_reputation152,913,012,544,965
root_title"Understand and Implement Custom Views in Android - Part 1"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@steem-ua ·
#### Hi @ideba!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
**Feel free to join our [@steem-ua Discord server](https://discord.gg/KpBNYGz)**
properties (22)
post_id71,676,222
authorsteem-ua
permlinkre-understand-and-implement-custom-views-in-android---part-1-20190318t222627z
categoryutopian-io
json_metadata{"app":"beem\/0.20.18"}
created2019-03-18 22:26:27
last_update2019-03-18 22:26:27
depth1
children0
net_rshares0
last_payout2019-03-25 22:26:27
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length284
author_reputation23,203,609,903,979
root_title"Understand and Implement Custom Views in Android - Part 1"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@utopian-io ·
Hey, @ideba!

**Thanks for contributing on Utopian**.
We’re already looking forward to your next contribution!

**Get higher incentives and support Utopian.io!**
 Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via [SteemPlus](https://chrome.google.com/webstore/detail/steemplus/mjbkjgcplmaneajhcbegoffkedeankaj?hl=en) or [Steeditor](https://steeditor.app)).

**Want to chat? Join us on Discord https://discord.gg/h52nFrV.**

<a href='https://steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1'>Vote for Utopian Witness!</a>
properties (22)
post_id71,699,340
authorutopian-io
permlinkre-understand-and-implement-custom-views-in-android---part-1-20190319t105822z
categoryutopian-io
json_metadata{"app":"beem\/0.20.17"}
created2019-03-19 10:58:24
last_update2019-03-19 10:58:24
depth1
children0
net_rshares0
last_payout2019-03-26 10:58:24
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length587
author_reputation152,913,012,544,965
root_title"Understand and Implement Custom Views in Android - Part 1"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000