android类可以在xml中使用,android – 在XML中使用自定义视图而不使用完全限定的类名...

我有自己的样式用于定义为主题的按钮,但我也使用自己的类来处理按钮(因为自己的字体).可以用一个漂亮的名字来调用我的按钮,例如

代替

解决方法:

令人惊讶的是,答案是肯定的.我最近了解到这一点,实际上你可以采取一些措施来提高你的自定义视图通胀效率. IntelliJ仍警告你它无效(虽然它会编译并成功运行) – 我不确定Eclipse是否会警告你.

无论如何,你需要做的是定义自己的LayoutInflater.Factory子类:

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;

}

}

然后,在您向包含这些自定义视图的布局进行充气的任何活动或上下文中,您需要将工厂分配给该上下文的LayoutInflater:

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);

}

}

然后,您可以在XML中使用简单的类名:

android:orientation="vertical"

android:layout_width="match_parent"

android:layout_height="match_parent">

android:id="@+id/my_view"

android:layout_width="match_parent"

android:layout_height="60dp"

android:layout_gravity="center_vertical" />

标签:android,android-layout

来源: https://codeday.me/bug/20190926/1822000.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值