Reputation: 866
First of all, I would like to apologise if my question is very basic - I don't know which keywords are useful to find the answer.
I know how to programme two "types" of application - ones which are run by .xml files (for instance, a converter from Celsius to Fahrenheit, some options menu and so on), and ones which are run with a class which extends View (for applications with graphical components). My question is, how to combine them? More precisely, how to add a View component into an XML file? Practical example: drawing a circle in an options menu, which moves once touched.
Thank you in advance.
Upvotes: 0
Views: 343
Reputation: 24722
To use custom view in XML you will need to
Code your view in such a way that it accepts AttributeSet. Example:
public ActivityTitleView(Context context, AttributeSet attrs)
Define styleable attributes. They go into res/values/attr.xml
<resources> <declare-styleable name="ActivityTitleView"> <attr name="text" format="string"/> <attr name="helpContext" format="string"/> </declare-styleable> </resources
< LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:yournamespace="http://schemas.android.com/apk/res/com.yourpackage" >
<com.yourpackage.ActivityTitleView yournamespace:text="Bla Bla" android:layout_width="fill_parent" android:layout_height="wrap_content"/>
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ActivityTitleView, 0, 0); String text = array.getString(R.styleable.ActivityTitleView_text); helpContext = array.getString(R.styleable.ActivityTitleView_helpContext);
Sorry StackOverflow does not seem to format my snippets well. Feel free to edit formatting.
Upvotes: 1
Reputation: 6073
I don't know about drawing a circle in options menu, but in general you can use your custom View classes in layout xmls like this;
<com.testing.MyCustomView
id="@+id/my_view"
... />
Making them very much alike compared to using TextViews, ImageViews etc.
Upvotes: 1