テーマとして定義されたボタンの独自のスタイルがありますが、独自のクラスを使用してボタンを処理します (独自のフォントのため)。次のようなきれいな名前でボタンを呼び出すことはできますか
<MyButton>
それ以外の
<com.wehavelongdomainname.android.ui.MyButton>
テーマとして定義されたボタンの独自のスタイルがありますが、独自のクラスを使用してボタンを処理します (独自のフォントのため)。次のようなきれいな名前でボタンを呼び出すことはできますか
<MyButton>
それ以外の
<com.wehavelongdomainname.android.ui.MyButton>
LayoutInflater.Factory の独自のサブクラスを定義するのは大変な作業のようです。アクティビティの onCreateView() を一般的なコードでオーバーライドするだけです。
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
View view;
// No need wasting microseconds getting the inflater every time.
// This method gets called a great many times.
// Better still define these instance variables in onCreate()
if (mInflator == null){
mInflator = LayoutInflater.from(context);
mPrefix = ((Activity) context).getComponentName().getClassName();
// Take off the package name including the last period
// and look for custom views in the same directory.
mPrefix = mPrefix.substring(0, mPrefix.lastIndexOf(".")+1);
}
// Don't bother if 'a path' is already specified.
if (name.indexOf('.') > -1) return null;
try{
view = mInflator.createView(name, mPrefix, attrs);
} catch (ClassNotFoundException e) {
view = null;
} catch (InflateException e) {
view = null;
}
// Returning null is no big deal. The super class will continue the inflation.
return view;
}
カスタム ビューは、このアクティビティと同じパッケージ (つまり、同じディレクトリ) に存在する必要がありますが、これは、任意のアクティビティで平手打ちできる (または、さらに良いことに、カスタムの親アクティビティ クラスから継承できる) 一般的なコードに過ぎないことに注意してください。kcoppock が提供するソリューションで指定されているように、特定のクラスを探すことについて心配する必要はありません。
if (MyCustomView.class.getSimpleName().equals(name)) {....
確かに、まったく新しいクラスを作成しているわけではありません。
本当の魔法は、コア ライブラリ クラスである LayoutInflator.java にあります。以下の mPrivateFactory.onCreateView() の呼び出しを参照してください。
if (view == null && mPrivateFactory != null) {
view = mPrivateFactory.onCreateView(parent, name, mContext, attrs);
}
if (view == null) {
if (-1 == name.indexOf('.')) {
view = onCreateView(parent, name, attrs);
} else {
view = createView(name, null, attrs);
}
}
いわゆる mPrivateFactory が null を返す場合 (ちなみに、mPrivateFactory はたまたまアクティビティ クラスです)、LayoutInflator は他の代替アプローチを続行し、インフレを続けます。
if (view == null) {
if (-1 == name.indexOf('.')) {
view = onCreateView(parent, name, attrs);
} else {
view = createView(name, null, attrs);
}
}
IDE デバッガーを使用してライブラリ クラスを「ウォークスルー」し、Android がどのように機能するかを実際に確認することをお勧めします。:)
コード はif (-1 == name.indexOf('.')) {
、カスタム ビューでフル パスを入力することをまだ主張しているユーザー向けのものであることに注意して<com.wehavelongdomainname.android.ui.MyButton>
ください。ヌル:view = createView(name, null, attrs);
私がこのアプローチを使用する理由は、開発の初期段階でパッケージ名が移動 (つまり、変更) されることがあることに気付いたからです。ただし、Java コード自体で実行されるパッケージ名の変更とは異なり、コンパイラはそのような変更を検出せず、XML ファイルに現在存在する不一致を検出します。このアプローチを使用すると、今では必要ありません。
乾杯。