In this part, you will be able to:
- Create the Custom View
- Create Custom Attributes
- Use your View in an Activity
- Capture Touch Events to move the knob
Note: The code demonstrated here can be directly fetched from the git repository WidgyWidgets. You need to clone the repository and checkout to tags/knobview-part1 (Instruction are at the end of this post)
To start with this, you want to decide on whether to extend the base View class or to extend one of the widgets available in android.
In our case, I want to create a view that somehow shows in its center a circle that can be dragged by the user to any of the edges. One way to go would be to extend one of the available ViewGroups, add the knob in its center, and implement this dragging functionality. Another way would be to start the view from scratch by extending View.
To make things more interesting, I will, in this post, extend View. By the way, I will call it KnobView.
As a general practice I usually create a class that extends View and directly create a function called init and override the 3 constructors of View calling init() in all of them:
public class KnobView extends View { public KnobView(Context context) { super(context); init(context, null); } public KnobView(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public KnobView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context, attrs); } private void init(Context context, AttributeSet attrs) { // TODO Auto-generated method stub } }If you do not know, the AttributeSet parameter in the constructor contains the attributes specified in the xml. To demonstrate, I will create an attribute called knob that will reference a drawable used for the knob in the center. To do so, we need to declare this attribute in the res folder. I will create a file called attr_knobview.xml in the res/values folder: this file will include the attributes of our KnobView. At this stage, we will only declare the attribute called knob of type integer since it is a reference to a drawable:
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="KnobView"> <attr name="knob" format="integer" /> </declare-styleable> </resources>
private void init(Context context, AttributeSet attrs) { // TODO Auto-generated method stub TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.KnobView); int drawable = a.getResourceId(R.styleable.KnobView_knob, 0); if(drawable != 0) { mKnobDrawable = a.getDrawable(R.styleable.KnobView_knob); } }
In this code, I try to get the integer which would be specified by the attribute knob (KnobView_knob). If this integer is not 0, I get the drawable and assign it to the field mKnobDrawable. You can add the field mKnobDrawable at the top of the class using this line: private Drawable mKnobDrawable;
What if there is no knob attribute specified in xml? I will simply create my own round black circle. This can be done in the else statement by creating a ShapeDrawable and assigning it to mKnobDrawable. Now my init function will assign a drawable to mKnobDrawable whether knob was specified or not.
private void init(Context context, AttributeSet attrs) { // TODO Auto-generated method stub TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.KnobView); int drawable = a.getResourceId(R.styleable.KnobView_knob, 0); if(drawable != 0) { mKnobDrawable = a.getDrawable(R.styleable.KnobView_knob); } else { mKnobDrawable = new ShapeDrawable(new OvalShape()); ShapeDrawable s = (ShapeDrawable) mKnobDrawable; s.getPaint().setColor(Color.BLACK); } }
Now we want to take care of the size of this knob. For now, I will center it in the view and let it take half the width and half the height. I will update the Bounds of this mKnobDrawable each time the size of our KnobView changes. This can be captured in onSizeChanged:
@Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mKnobDrawable.setBounds(w/2-w/4, h/2-h/4, w/2+w/4, h/2+h/4); }
Notice that I am always updating the bounds of the knob drawable when the size changed. These bounds determine the actual rectangle in which my drawable will be drawn. I set the bounds to be the rectangle that is exactly half the size of the view and exactly located in the center of our view. It is pretty straight-forward.
Finally, I want to draw this Knob. This is simply calling the Drawable's draw function on our canvas in the onDraw function of the KnobView:
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); mKnobDrawable.draw(canvas); }
For testing, I created an activity with the following xml layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res/mobi.sherif.widgywidgetstest" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" > <mobi.sherif.widgywidgets.KnobView android:id="@+id/knob1" android:background="#f00" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_weight="1" /> <mobi.sherif.widgywidgets.KnobView android:id="@+id/knob2" android:background="#0f0" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_weight="1" app:knob="@drawable/ic_launcher" /> </LinearLayout>
Notice:
- If you are doing your own project, you probably want to specify your package name instead of mobi.sherif.widgywidgetstest (second line)
- Due to layout_height="0dp" and layout_weight="1", each KnobView will take half the screen.
- The first KnobView does not specify the knob attribute while the second does.
- Each of the KnobView has a differnt background (red and blue).
Anyway, if you run this activity, you will get the output that is shown in the previous image.
With some modifications, int the drawables used for the background and the knob, I was able to get the following KnobView:
I modified the first KnobView in the layout (notice the background and the knob values)
I modified the first KnobView in the layout (notice the background and the knob values)
<mobi.sherif.widgywidgets.KnobView android:id="@+id/knob1" android:background="@drawable/bg_knobview" app:knob="@drawable/bg_knob" android:layout_width="100dip" android:layout_height="100dip" android:layout_marginTop="100dip" android:layout_marginBottom="100dip" />
I also created res/bg_knobview
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" > <solid android:color="#aaaaaa" /> </shape>andres/bg_knob
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" > <solid android:color="#333333" /> </shape>
Now it is time to move our knob. It is a very simple thing to: We will capture the touches on our view using the function onTouchEvent and when an ACTION_DOWN or ACTION_MOVE is detected, we move the knob to the location of the event. How do we do so? It's pretty easy: we use the setBounds function that we used in the onSizeChanged.
@Override public boolean onTouchEvent(MotionEvent event) { final int action = MotionEventCompat.getActionMasked(event); if(action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_MOVE) { int w = getWidth(); int h = getHeight(); int x = (int) event.getX(); int y = (int) event.getY(); mKnobDrawable.setBounds(x-w/4, y-h/4, x+w/4, y+h/4); invalidate(); } return true; }Notice that we only did two things if the action is ACTION_DOWN or ACTION_MOVE:
- Set the bounds of our knob drawable based on the location of the event: We kept its width = w/2 and its height h/2 but we translated it to (x,y), the location of the event
- Invalidated the view using invalidate() to force our view to redraw -i.e. to move the knob.
The last natural thing to do is move the knob back when the user stops his touches. That is almost the same thing but with x and y set to the midpoint of the view -i.e. (w/2, h/2). Therefore our final onTouchEvent will look something like:
@Override public boolean onTouchEvent(MotionEvent event) { final int action = MotionEventCompat.getActionMasked(event); if(action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_MOVE) { int w = getWidth(); int h = getHeight(); int x = (int) event.getX(); int y = (int) event.getY(); mKnobDrawable.setBounds(x-w/4, y-h/4, x+w/4, y+h/4); invalidate(); } else if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { int w = getWidth(); int h = getHeight(); int x = w/2; int y = h/2; mKnobDrawable.setBounds(x-w/4, y-h/4, x+w/4, y+h/4); invalidate(); } return true; }
Notice that the only difference is that x and y are not set to w/2 and h/2 respectively.
At the end of this part, your knob should be able to move when touched and return to its original place when released. Clone the WidgyWidget repository to try it yourself.
Have fun (:
Note: If you want to get the code of this part only, clone and checkout tags/knobview-part1 using the following commands (If you ommit folder_name, it will automatically be cloned into folder WidgyWidgets) :
git clone https://github.com/sherifelkhatib/WidgyWidgets.git folder_name
cd folder_name
git checkout tags/knobview-part1
... Try it and when you are done ...
git checkout master
At the end of this part, your knob should be able to move when touched and return to its original place when released. Clone the WidgyWidget repository to try it yourself.
Have fun (:
Note: If you want to get the code of this part only, clone and checkout tags/knobview-part1 using the following commands (If you ommit folder_name, it will automatically be cloned into folder WidgyWidgets) :
git clone https://github.com/sherifelkhatib/WidgyWidgets.git folder_name
cd folder_name
git checkout tags/knobview-part1
... Try it and when you are done ...
git checkout master
Thanks for sharing, nice post!
ReplyDelete- Với sự phát triển ngày càng tiến bộ của kỹ thuật công nghệ, nhiều sản phẩm thông minh ra đời với mục đích giúp cuộc sống chúng ta trở nên thoải mái và tiện lợi hơn. Và thiet bi dua vong tu dong ra đời là một trong những sản phẩm tinh túy của công nghệ, may ru vong tu dong là phương pháp ru con thời hiện đại của các ông bố bà mẹ bận rộn.
- Là sản phẩm tuyệt vời của sự phát triển công nghệ, dung cu dua vong tu dong được thiết kế an toàn, tiện dụng. Những lợi ích mà may dua vong em be mang lại là vô cùng thiết thực.
- Hiện nay trên thị trường có nhiều loại may dua vong cho em bé, sau nhiều năm kinh doanh và kinh nghiệm đút kết từ phản hồi của quý khách hàng sau khi mua máy, máy đưa võng tự động An Thái Sơn nhận thấy máy đưa võng tự động TS – sản phẩm may dua vong tu dong thiết kế dành riêng cho em bé, có chất lượng rất tốt, hoạt động êm, ổn định sức đưa đều, không giật cục, tuyệt đối an toàn cho trẻ, là lựa chọn hoàn hảo đảm bảo giấc ngủ ngon cho bé yêu của bạn.
Bạn xem thêm bí quyết và chia sẽ kinh nghiệm làm đẹp:
Những thực phẩm giúp đẹp da tại http://nhungthucphamgiupda.blogspot.com/
Thực phẩm giúp bạn trẻ đẹp tại http://thucphamgiuptre.blogspot.com/
Thực phẩm làm tăng tại http://thucphamlamtang.blogspot.com/
Những thực phẩm giúp làm giảm tại http://thucphamlamgiam.blogspot.com/
Những thực phẩm tốt cho tại http://thucphamtotcho.blogspot.com/
Chúc các bạn vui vẻ!
I love to see you have written this content very Well and want to write more so people will aware of this issue
ReplyDeleteI have some favorite game Blogs as well like
||Happy Wheels at happywheels.in||
||Happy wheels game at classic happy wheels game||
||Happy Wheels demo at happy wheels||
||Fireboy and watergirl at fireboywatergirl.co||
Thank you for posting such a great article! I found your website perfect for my needs
ReplyDeletevisit our website
Obat Aborsi ,
ReplyDeleteCara Menggugurkan Kandungan ,
Obat Penggugur Kandungan ,
Great Article...Thanks for sharing the best information.It was so good to read and useful to improve my knowledge as updated one.
ReplyDeleteAndroid Training
now present in your city
ReplyDeleteYou are doing a great job. Now we are sharing with you all the Tresurebox store products which you will be buy online in a single click. Garden shed nz online in a single click,
ReplyDeleteLooking for English to Spanish Translators? We provide professional Translation Services at highly competitive rates without compromising the quality.
ReplyDeletespanish to english translation services
we are best calgary roofing companies & Best roofing contractors calgary. Contact us for transparent quotes. roofing calgary & roofing services calgary Roofing Company in Calgary
ReplyDeleteThis piece appeared educaitonal and informative. Thanks a lot for contributing the tutorial, I will be learning from it!
ReplyDeleteMoon Rocks,
ReplyDeleteCBD Isolate,
LOL Edibles,
Gummy Bears,
THC Distillate,
Rick Simpson Oil,
FECO,
Mendocino Purps
Thanks for posting such a great blog
ReplyDeleteVermicompost Manufacturers | Vermicompost in chennai
ReplyDeleteHi, Very nice article. I hope you will publish again such type of post. Thank you!
Corporate gifts ideas | Corporate gifts
Corporate gifts singapore | Corporate gifts in singapore
Promotional gifts singapore | corporate gifts supplier
Chiefs Game Live
ReplyDeleteChiefs Game Today
Chiefs Football Live
Kansas City Chiefs Game Live
Texans Game Today
Texans Game Live
Thursday Night Football Live
Monday Night Football Live
Steelers Football Live
I felt very happy while reading this article. we provide Mobile Back Cover Printing in Kenya at affordable prices. for more info visit our website.
ReplyDelete
ReplyDeleteBaltimore Ravens Football Live Online
Ravens Game Live Online
Watch Texans Game Live
Cardinals Game Live Online
Rams Game Live
Giants Game Live Online
Raiders Game Live Online
Buccaneers NFL Game Live
Internet Business Ideas for 2020
ReplyDeleteTo be honest your article is informative and very helpful. Hp Laptop | Hp laptop online price
ReplyDeletehttps://syntheticworldwide.com/
ReplyDeletesales@syntheticworldwide.com
Buy cheap liquid herbal incense at your best online shop
Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post.
ReplyDeletewonderful article....
ReplyDeleteMachine Learning Training in Coimbatore | Top 10 java training institute in coimbatore | web design training in coimbatore | selenium training in coimbatore | python tutorial in coimbatore | web development training in coimbatore | Web Designing training in coimbatore | Data Science course in coimbatore
rappers 1st choice official website
ReplyDeletewhere can i get rappers weed in la
buy rappers weed online in Europe
rappers weed for sale in Europe
rappers favorite weed
rappers 1st choice official website in Europe
rappers favorite weed in Europe
Buy rappers gelato-41 in Europe
Buy gelato-41 from rappers 1st choice in Europe
rappers 1st choice official website
rappers 1st choice official website
where to buy rappers 1st choice weed in Europe
where to buy rappers 1st choice weed online in Europe
rappers 1st choice in Europe
rappers 1st choice
Plug n play official website
ReplyDeletewhere to buy plug play batteries
Buy plug play pods online
plugnplay LA
flavors of plugplay for sale
buy plug n play online
plug n play
plug play all day
plugnplay
buy plugplay slushie online
buy plugsplay online
Tokyo Olympics Live Stream
ReplyDeleteWatch Olympic Game Live
Cleveland Browns live
ReplyDeleteCleveland Browns game live
Cleveland Browns game today
Very informative post! There is a lot of information here that can help any business get started with a successful social networking campaign.
ReplyDelete
ReplyDeleteOur online store is one of the best in the supply of rare and high-grade (Mushrooms, Edibles. Psychedelics, and more)with absolute purity. All our products are tested to guarantee potency after production, during distribution and even storage. We ship globally in discreet and undetectable packaging using our network of trusted partners.
psilosybin mushroom 2022, trusted magic mushroom site 2022,
cheap liquid lsd, order cheap psychedelic mushroom,
cheap magic mushroom, super quality shrooms,
most potent psilocybin mushroom on the market,
best microdosing mushrooms 2022, Golden teacher mushroom for sale,
where to buy B+ magic mushroom, buy shrooms online ,
buy psilocybin mushroom overnight shipping, effective microdosing for ptsd,
buy mushroom truffles online cash on delivery, buy microdose capsules online 2021,
magic mushrooms for mental illness for sale,
buy mushies for anxiety/deppression and ptsd, cheap psilocybin mushroom, shrooms near me,
where to buy psilocybin mushroom near me, cheap psychedelic mushroom for sale,
buy caps/buttons cheap, best place to buy magic mushroom,
buy cheap fungi mushrooms, cheap strong fungus, best quality spores for sale,
buy mushroom grow kit online, buy fungi shrooms near me, cheapest magic mushrooms online,
where to buy penis envy online, where to buy mexicanna online, buy microdose capsules online,
best microdose capsule for sale,
fungi mushroom for sale, best liquid cultures online, buy spores near me, buy Nirvana mushroom near me,
buy pajaritos mushrooms near me, psychedelic mushroom near me, buy medicinal mushroom online,
buy 5-MeO-DMT, buy dmt vape pen online, buy lsd tabs online, buy dmt online, where to buy dmt,
lsd for sale, buy mushies near me, buy shrooms wholesale price, strong boomers for sale,
Buy trippy shrooms online, buy penis envy, buy albino A+, buy amazonian cubensis,
buy psilocybe cubensis, buy blue meanie, buy vietam cubensis, buy z strain shrooms,
buy boomers cubensis online, buy cubensis buy golden teacher, buy liquid lsd online
Our quality is the best you can find around and we sell in small/large quantities with guaranteed discreet delivery in good time Shipping
website...https://megapsilocybin.com/
call/text..+1(458) 201-6900
email..sale@megapsilocybin.com
Fast-track your data analytics and machine learning career with guaranteed placement opportunities. Most extensive, industry-approved experiential learning program ideal for future Data Scientists.
ReplyDeleteCopying wii original DVDs and enjoying them on your console is not a tuff thing to do all you need to know is the good software to make your copying games process successful and let you play all your games. how to install cracked apps on mac Game downloads are free of harmful viruses, adware, and spyware (scanned by Virustotal).
ReplyDelete
ReplyDeleteWe believe every puppy deserves a home and every dog lover deserves the best..
welcome to Maltese Puppies
where to buy Maltese Puppies
Maltese puppies
Maltese Puppies For Sale
You provided fantastic information which is going to help people. You can also get information about IT solutions company Mississauga, Managed IT Services Mississauga, cloud consulting services Mississauga
ReplyDeleteQuality Spice Incense
ReplyDeleteK2 spice spray omg
K2 spice spray pure fire
Black diamond kush
Cannabis crumble
Liquid incense spray
K2 E-Liquid red code
k2 clear paper spray
Risk management software is a type of computer program designed to help businesses and organizations identify, assess, and manage potential risks to their operations. These risks may include financial risks, operational risks, legal risks, and reputational risks, among others.
ReplyDeleteOnline learning can be a great option for seniors who want to continue their education, learn new skills, or simply explore new interests. It offers flexibility, convenience, and a wide range of subjects to choose from. Online Learning for Seniors
ReplyDeleteExcellent instruction! Your step-by-step instructions for developing the Android Custom View for the PlayStation Knob are quite helpful. It's simple to follow along as you explain decisions regarding extending View, custom attributes, and touch event processing. Your code samples and XML layouts give depth to your explanation, making it understandable to beginners. I'm looking forward to the following installments in the series! 🎮📱
ReplyDeleteData Analytics Courses in India
This article seemed to be instructive and informative. I appreciate you sharing the information; I will benefit from it.
ReplyDeleteData Analytics Courses in Agra
This article is a fantastic introduction to creating Android Custom Views, especially the PlayStation Knob. The step-by-step explanation and clear code snippets make it easy to follow along. Keep up the good work.
ReplyDeleteIs iim skills fake?
This blog post seems to be the beginning of an exciting journey into creating a custom view for Android inspired by a PlayStation knob. Custom views can add unique and engaging elements to Android apps, and this post likely offers a promising start for developers looking to delve into this creative process. A must-read for Android developers seeking to enhance their skills and add a touch of innovation to their app's user interface.
ReplyDeleteData Analytics Courses in Delhi
This blog article appears to be the start of an intriguing path towards developing an Android custom view that is motivated by a PlayStation knob. Custom views may bring interesting and distinctive features to Android apps, and this article can serve as a helpful starting point for developers interested in exploring this creative process. Thank you for sharing.
ReplyDeleteData Analytics Courses in Agra
This knob design feels like a nostalgic gaming joystick – a cool twist for my Android app! I'm thrilled to give it a spin in my next project. Thanks for sharing this gem.
ReplyDeleteData Analytics Courses In Gujarat
This blog helped me level up my Android skills! I'm all set to craft some cool custom knobs for my app now. Thanks for sharing this gem of a tutorial!
ReplyDeleteData Analytics Courses In Gujarat
Sherif elKhatib's blog, powered by cutting-edge AI technology, is a game-changer in the realm of Android-focused content creation.
ReplyDeleteDigital Marketing Courses in Hamburg
The PlayStation Knob, or joystick, is a fundamental input device for gaming consoles, offering precise control and enhancing the gaming experience. In the world of data analytics, London offers a variety of Data Analytics courses that equip individuals with the skills to extract insights from diverse data sources and make data-driven decisions. Please also Digital Marketing Courses in London.
ReplyDeleteThank you for providing this valuable resource, offering clear instructions and practical tips for creating engaging and dynamic user interfaces on the Android platform."
ReplyDeleteDigital marketing courses in woking
I found the blog on Android Custom View: PlayStation Knob' series very informative the step by step guidance is fantastic thanks for sharing the valuable insights.
ReplyDeleteDigital Marketing Courses in Italy
The Android Custom View: PlayStation Knob - Part 1 is very informative and comprehensive guide thanks for sharing valuable instruction.
ReplyDeletedata analyst courses in limerick
great blog post, thanks for sharing.
ReplyDeletefinancial modelling course in melbourne
Thank you for providing in depth knowledge and insightful tutorial on how to create Android Custom View.
ReplyDeleteAdwords marketing
A clear and engaging guide! Part 1 effectively sets up creating the Android Custom View. Thanks for sharing this insightful tutorial!
ReplyDeleteHow Digital marketing is changing business
This blog helped me level up my Android skills! I'm all set to craft some cool custom knobs for my app now. Thanks for sharing this gem of a tutorial!
ReplyDeleteInvestment Banking courses in bangalore
Exceptional tutorial on creating a PlayStation Knob Android Custom View! Thanks for the detailed guide and sharing your expertise.
ReplyDeleteInvestment Banking Industry
The blog post is excellent tutorial on Android Custom View.
ReplyDeleteInvestment banking training Programs
Your post made me think about things in a whole new light. Thank you Investment banking courses in Chennai
ReplyDelete
ReplyDelete"Exciting start to the PlayStation Knob journey! Your blog's 'Getting Started' section provides a great foundation for what promises to be an interesting project. I'm looking forward to following the development and learning more about the process. The inclusion of images and the option to share on various platforms adds a nice touch of interactivity. Can't wait for the next installment! Happy crafting!"
Investment banking course details
ReplyDeleteThis is a great start to building a PlayStation-inspired knob for Android! The detailed explanation of how to create a custom view from scratch by extending the View class is very clear and easy to follow.
Data science courses in Visakhapatnam
Nice content. Thankyou for sharing.
ReplyDeleteData science courses in Pune
"Fantastic post! If you’re serious about building a career in data science, you should definitely explore the Data Science courses in Kochi. They offer great programs to help you get started."
ReplyDeleteGreat tutorial! The PlayStation knob custom view is a fantastic example of how to create engaging and interactive UI components in Android.
ReplyDeleteData science Courses in Canada
Loved the detailed explanation and clear code snippets. This tutorial is going to be so helpful. Thanks for sharing.
ReplyDeleteData science Courses in Sydney
Fantastic blog post! It was easy to follow and filled with practical advice
ReplyDeleteData science Courses in London
The explanation of creating custom UI components for Android is spot on! This post provides clear and useful instructions. Great job!
ReplyDeleteData science courses in France
This comment has been removed by the author.
ReplyDeleteThank you for sharing your expertise with us.
ReplyDeletetechnical writing course
This series on creating a PlayStation-inspired analog knob in Android is a great way to dive into custom views. By extending the base View class, the post sets up an interesting challenge to implement interactive touch events. I’m excited to see how the knob will be manipulated within the app, offering a cool user interface element.
ReplyDeleteData science Courses in City of Westminster
Neel KBH
kbhneel@gmail.com
This tutorial outlines the first steps to create a custom Android View that simulates the functionality of a PlayStation analog knob. Informative Article!
ReplyDeleteData science Courses in Ireland
Your tutorial on creating a custom PlayStation-style knob view in Android is impressive and very well-explained. The detailed code snippets and visuals make it easy to follow and implement. Thank you for sharing this creative approach to custom UI design!
ReplyDeleteData science courses in UAE
https://iimskills.com/data-science-courses-in-uae/
Your tutorial on creating a custom PlayStation-style knob view in Android is impressive and very well-explained. The detailed code snippets and visuals make it easy to follow and implement. Thank you for sharing this creative approach to custom UI design!
ReplyDeleteData science courses in UAE
https://iimskills.com/data-science-courses-in-uae/