custom view declared in xml - android

When declaring custom view in xml, what is the difference between declaring a View of a custom class, or declaring a completely custom view:
<LinearLayout>
<view class="packageName.MyView" android:id="#+id/myView" />
</LinearLayout>
and
<LinearLayout>
<packageName.myView android:id="#+id/myView" />
</LinearLayout>
?
I've created a subclass of EditText, and when instatiating it as View class=".." my Activity crashes with ClassCastException when trying to access MyView:
(MyView) myView = (MyView) findViewById(R.id.myView);
When declared as second option, everything works as expected.

I'm not 100% sure on this, but let me give it a go. A couple of things could be happening. The parser might not understand the class attribute correctly (e.g. it thinks it is part of a stylesheet). I am not sure how the parser handles the class attribute, since I have never seen or used it (in fact, I've never seen the <View> tag used either). A better explanation, though, might be this: the parser is trying to down-cast your View into packageName.myView class and fails (down-casting is always risky; up-casting is always safe).
Regardless of what is happening, I would always use the second option you listed, <packageName.myView android:id...>, instead of using the <View> tag. Reason being, it's redundant to use the <View> tag. Everything in this xml file must be a view (LinearLayout, Button, TextView, etc. are all descendants of the View class).
Hope that helps. If you're really, really curious, you could always download the source code for the parser...

Related

Nesting custom views

I have a custom view that, on a high level, takes whatever drawable one might pass into it and draws a ring around it, the ring is animated, and comes with a whole set of parameters; things such as ringWidth, gradient colors, etc.
Currently, to show/specify this view in my XML, my markup looks a lot like this:
<RingedImageView
android:id="#+id/ringedImageView"
android:layout_height="#dimen/image_gigantic"
android:layout_width="#dimen/image_gigantic"
app:source="#drawable/ic_icon_1"
app:ringWidth="2dp" />
This is all well and good. However, instead of passing in a drawable as the image in the middle, what I would like is to be able to pass in a whole view, entirely seperate from #id/ringedImageView.
Ideally, I'd like this to look as follows in my XML:
<RingedImageView
android:id="#+id/ringedImageView"
android:layout_height="#dimen/image_gigantic"
android:layout_width="#dimen/image_gigantic" ...>
<ImageView
android:id="#+id/imageView" .../>
</RingedImageView>
My question then is, can I access that nested ImageView in my RingedImageView.java class? How can I specify how to handle this situation?
Some answers point to having to extend ViewGroup instead of View, but as this isn't a layout manager per se, and the component comes with its own rules for displaying content, a View seems more appropriate. Would appreciate a pointer.
Thanks all

Is it bad proactive to create backing subclasses for your layouts if they don't need customization?

I'm new to Android and have recently started adopting the pattern to create an auto-layout-loading custom view based on a layout file. In the layout you use the 'merge' tag as the root, then in the constructor of your view, you inflate that layout into yourself so you are essentially the root of the merged-in controls. Right after you inflate, still in the constructor, you can find the child controls from the layout and assign them to private fields in the custom class so they will always be available, even when using recycler views.
Contrast that with including a layout. In that case, the layout has to define a root element (which can be your custom control, but in that case, you would not inflate the layout into yourself and would have to move the control lookup to onFinishInflate) but otherwise it ends up with the same view hierarchy.
In short, instead of this...
<include layout="#layout/layout_myCustomControl" />
You can now do this...
<com.mydomain.MyCustomControl />
However I find the auto-loading custom control version to be much more flexible and maintainable. The advantages of the second one are not only that you can use custom attributes in the referencing XML layouts (which you can't with the 'include' version) but it also gives you a central place to manage the code as well as layout management/control lookup.
So now I can do this...
<com.mydomain.MyCustomControl
app:myCustomAttribute="Foo" />
And if the control has to have code backing up its behavior, it's nicely encapsulated in the custom view.
Here's an example layout for the auto-loading version...
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is static text in the header" />
<TextView android:id="#+id/dateTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</merge>
And here's the class that uses it...
public class MainHeader extends LinearLayout
{
TextView dateTextView;
public MainHeader(Context context, #Nullable AttributeSet attrs)
{
super(context, attrs);
setOrientation(VERTICAL);
LayoutInflater.from(context).inflate(R.layout.header_main, this);
dateTextView = (TextView)findViewById(R.id.dateTextView);
dateTextView.setText(<<Code for setting date goes here>>);
}
}
But what I'm wondering is if the layout is purely static in nature--say holding a static image and fixed text--is it still considered good practice to use a custom view to represent it? I'd say yes for consistency, plus should I want to extend it in the future, you're already prepared for it and have to do so in just one place regardless of how many places it's used. In contrast, if you included the layout directly in say 20 places, you may have to update all 20 (depending on what's actually changed/needed.)
Pros for the Custom View approach:
Central location for managing layout loading and control lookup
Can support backing code implicitly/internally for updating the view.
Can use attributes when being referenced in other layout files
Better encapsulation (you can hide the layout itself from the outside world exposing behaviors via direct methods)
Can simply be 'new'd' up in code and the layout will automatically load. No inflating or casting needed.
Cons for Custom View approach
When used in Layout files, you now have to also specify width and height making usage a little more verbose.
May add extra classes to your project (not always, but sometimes.)
Again, it seems to me like a no-brainer, but I'm wondering if there's a preferred 'Androidy' way, or is it just a preference up to each developer?
Such approach will add additional level in your view trees. So you only made the UI tree more complex for no good reason. From other side, you can follow next steps to get rid of that side-effect:
<merge /> can only be used as the root tag of an XML layout
when inflating a layout starting with a <merge />, you must specify a parent
ViewGroup and you must set attachToRoot to true (see the
documentation of the inflate() method)
That's it.
Well apparently what I came up with wasn't that unique after all! Here's an article explaining in detail this exact scenario, along with the pros and cons of each. Looks like they too came to the same conclusion.
TrickyAndroid: Protip. Inflating layout for your custom view

What is tag <view> in layout xml used for?

I notice that there is a tag <view>(not <View>) which can be used in Android layout xml. When I add such a tag in a layout xml, the app can be successfully compiled but crashes when running. So what is this <view> used for?
view is an alternative way for specifying a view to inflate. You need to combine it with class attribute to specify the class name.
This is "useful" if your view class is an inner class and you cannot use something with a $ in the tag name in XML. (Having inner classes as Views you inflate is not a very good idea though.)
For example:
<view class="your.app.full.package.Something$InnerClass" ... />
Reference: http://androidxref.com/5.0.0_r2/xref/frameworks/base/core/java/android/view/LayoutInflater.java#696
View is widget of android that is use to add any kind of view.Like in problems when we use scrollView in a activity and at bottom of activity there is buttons ,That time we add view to looks better.We can set any kind of color to View .
for exp
This will make a View of 20dp height.

Accessing a custom view from the xml layout

In an Android application, I have created a custom view extending the View class. I want to declare an object of my class in the xml layout file but, even after many tries, the application unexpectedly stops when the setContentView call is executed (that's what the popup windows which appears says).
In my view class, which is declared in my MainActivity file as public, I have two constructors : one with only the Context as parameter and one with a Context and an AttributeSet parameters. And I have overridden the onDraw function.
This class is in my source package, named org.me.myapp.
In the layout file, I declare the object I want to insert like this :
<org.me.myApp.MainActivity.myView"
android:id="#+id/View"
android:layout_below="#id/toto"
android:layout_width="300dip"
android:layout_height="100dip"/>
Can anyone tell me what is wrong?
Thanks in advance for the time you will spend trying to help me.
What Yar said, you should extend View or ViewGroup to create custom layout element, and use that class name in your layout xml. Not member variable what it looks you're trying to do. After inflating your layout you can access your custom view with;
org.me.myapp.MyView myView = (org.me.myapp.MyView) findViewById(R.id.MYVIEWID);
I think you need to declare your custom layout as a separate class, for example: org.me.myapp.MyView and relate to it in your xml file like this:
<org.me.myapp.MyView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
...
/>

Android XML Common Elements between pages? Frames?

I am skinning an app and I was wondering if there was a way to keep common elements the same between XML layouts without copying the same code around all the time.
For instance, I have a header and footer and background that will be the same between most pages. Can I make a "common" xml containing the header and footer and just load the individual page like a frame inside of it?
I'm not sure how I would reference that individual page within the XML. Maybe I could change an ID from the java side in an onCreate function, although it seems like more work now, if I changed something on the header and footer in the future I wouldn't have to change every Activity of the app.
Thanks for any insight!
I think it's the inclue tag you're looking for. Example:
<include layout="#layout/bar_header_top" />
Make a Java class that extends a View that holds all header elements and one that holds all footer elements and implement them in every view like this
<LinearLayout>
<com.[package].[classname of header] />
-- content here --
<com.[package].[clasname of footer] />
</LinearLayout>

Categories

Resources