Reputation: 2105
Here I made my own custom widgets in android and they all work fine. However, i have like 20 xml files and I don't want to change the EditText
in xml to com.example.customwidget.MyEditText
in all the xml layouts that I have. Any fast way to do that?
For example:
The below xml won't work. It will crash the application because there is no MyEditText
in the android sdk widgets, that's my own widget.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<MyEditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:ems="10"
android:inputType="number" >
<requestFocus />
</MyEditText>
</RelativeLayout>
However, This one will work:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.customwidget.MyEditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:ems="10"
android:inputType="number" >
<requestFocus />
</com.example.customwidget.MyEditText>
</RelativeLayout>
What I would like to do is to simply keep the EditText
tag in the xml. However, I want to by my own custom EditText
.
Ok I know I will have to change the class name first to be EditText
instead of MyEditText
but how can I let all the XML Layout files know that I want my custom EditText
and not the native one?
Upvotes: 1
Views: 73
Reputation: 9609
Implement custom LayoutInflater.Factory
and set it to your activity's LayoutInflater
Here is an example of such factory:
public class MyLayoutInflaterFactory implements LayoutInflater.Factory
{
public View onCreateView(String name, Context context, AttributeSet attrs)
{
if ("EditText".equals(name))
return new MyEditText(context, attrs);
return null;
}
}
Then you need to use it in your activity:
public class MyActivity extends Activity
{
⋮
LayoutInflater layoutInflater;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
layoutInflater = LayoutInflater
.from(this)
.cloneInContext(this)
.setFactory(new MyLayoutInflaterFactory());
setContentView(layoutInflater.inflate(R.layout.my_activity, null));
}
@Override
public LayoutInflater getLayoutInflater()
{
return layoutInflater;
}
⋮
}
Upvotes: 2