Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating an inner class (Preference) in xml file

When you want to access a custom view in some layout.xml file, you have two options:

  1. The view is in it's own class. Then you do <package.name.MyView android:layout_width= ... />
  2. The view is an inner class: <view class="package.name.OuterClass$MyView" android:layout_width= ... />

Now I want to do the same thing inside a <PreferenceScreen>. The first way works well, but I would like to put all the custom Preference classes together in my PreferenceActivity. I tried <Preference class="package.name.OuterClass$MyPreference" ... /> (also with '.' instead of '$') as well as <package.name.OuterClass.MyPreference ... />, but both failed.

Does anyone have an idea?

like image 781
m1ntf4n Avatar asked Aug 30 '11 19:08

m1ntf4n


People also ask

How do you instantiate an inner class?

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass outerObject = new OuterClass(); OuterClass. InnerClass innerObject = outerObject.

How do you access a static inner class from another class?

They are accessed using the enclosing class name. For example, to create an object for the static nested class, use this syntax: OuterClass. StaticNestedClass nestedObject = new OuterClass.

What is the difference between inner class and nested class?

A class that is defined within another class is called a nested class. An inner class, on the other hand, is a non-static type, a particular specimen of a nested class.

What is the main difference between an inner class and a static nested class in Java?

1) First and most important difference between Inner class and nested static class is that Inner class require instance of outer class for initialization and they are always associated with instance of enclosing class. On the other hand nested static class is not associated with any instance of enclosing class.


1 Answers

When dealing with Views inflating, LayoutInflater looks for a "view" -> "class" case:

View createViewFromTag(View parent, String name, AttributeSet attrs) {
    if (name.equals("view")) {
        name = attrs.getAttributeValue(null, "class");
    } ...

Preference's PreferenceInflater doesn't, so that is for the "class" case.

It uses reflection in its createItem() method and that's probably why the first case works for you.

like image 172
avimak Avatar answered Nov 15 '22 19:11

avimak