Created
August 19, 2013 11:17
-
-
Save liminal/6268046 to your computer and use it in GitHub Desktop.
From http://stackoverflow.com/questions/17477981/using-custom-views-in-xml-without-using-fully-qualified-class-name How to use a custom layoutinflater in order to use layout xml files with custom classes without using fully qualified classname
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" | |
android:orientation="vertical" | |
android:layout_width="match_parent" | |
android:layout_height="match_parent"> | |
<MyCustomView | |
android:id="@+id/my_view" | |
android:layout_width="match_parent" | |
android:layout_height="60dp" | |
android:layout_gravity="center_vertical" /> | |
</FrameLayout> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CustomViewActivity extends Activity { | |
public void onCreate (Bundle savedInstanceState) { | |
//Get the LayoutInflater for this Activity context | |
//and set the Factory to be our custom view factory | |
LayoutInflater.from(this).setFactory(CustomViewFactory.getInstance()); | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.layout_with_custom_view); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CustomViewFactory implements LayoutInflater.Factory { | |
private static CustomViewFactory mInstance; | |
public static CustomViewFactory getInstance () { | |
if (mInstance == null) { | |
mInstance = new CustomViewFactory(); | |
} | |
return mInstance; | |
} | |
private CustomViewFactory () {} | |
@Override | |
public View onCreateView (String name, Context context, AttributeSet attrs) { | |
//Check if it's one of our custom classes, if so, return one using | |
//the Context/AttributeSet constructor | |
if (MyCustomView.class.getSimpleName().equals(name)) { | |
return new MyCustomView(context, attrs); | |
} | |
//Not one of ours; let the system handle it | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment