我创建了一个或多或少看起来像这样的customTextView java类:
public class CustomTextView extends TextView {
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
}
在xml中我会像这样使用它:
<com.mypackage.mystyles.CustomTextView
android:id="@+id/myid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="hello world this is a tv" />
但我还想制作一个具有非常相似的覆盖行为的自定义EditTextView,并能够像这样进行调用:
<com.mypackage.mystyles.CustomEditText
android:id="@+id/et_id"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="hello world this is a et" />
我如何使用相同的java类(在我的情况下为CustomTextView.java),因为我不想重复代码,因为真正的EditText是TextView的子类。
答案 0 :(得分:0)
我找到了一种有趣的方法来实现这一点,重用代码。在oncreate中,我会调用一个名为applyMyOwnFonts()
的方法然后我会覆盖inflater以在每个视图上设置我自己的自定义:
public void applyMyOwnFonts() {
getLayoutInflater().setFactory(new Factory() {
@Override
public View onCreateView(String name, Context context,
AttributeSet attrs) {
if (name.equalsIgnoreCase("TextView")
|| name.equalsIgnoreCase("Button")
|| name.equalsIgnoreCase("EditText")
|| name.equalsIgnoreCase("RadioButton"){
LayoutInflater f = LayoutInflater.from(context);
final View view = f.createView(name, null, attrs);
new Handler().post(new Runnable() {
public void run() {
MyCustomTextView.doWhatIneedToDo(view); //static call
}
});
return view;
}
return null;
}
});
}
所以任何textview,buttons,edittexts和radiobuttons都可能具有所有相同的字体或相同的文本大小等,而不是像框架默认值那样。