0

Android UIコンポーネントの動的インスタンスを作成しようとすると、「java.lang.InstantiationException」が発生します。

サンプルコード:

Class components[] = {TextView.class, Button.class,...}
Component mControl = null;
...
...
mControl = (Component) components[nIndexOfControl].newInstance();

誰かが私を導くことができますか、ウィジェットごとにif..elseを保存したいので、上記を達成するための最良の方法は何ですか?

4

3 に答える 3

2

クラスにはデフォルトのTextViewコンストラクターがありません。3 つの利用可能なコンストラクターは次のとおりです。

TextView(Context context)
TextView(Context context, AttributeSet attrs)
TextView(Context context, AttributeSet attrs, int defStyle)

Buttonクラスでも同じこと:

public Button (Context context)
public Button (Context context, AttributeSet attrs)
public Button (Context context, AttributeSet attrs, int defStyle) 

Contextすべての UI (の子孫View) コントロールをインスタンス化するには、少なくとも変数を渡す必要があります。


次の方法でコードを変更します。

Context ctx = ...;
Class<?> components[] = {TextView.class, Button.class };
Constructor<?> ctor = components[nIndexOfControl].getConstructor(Context.class);
Object obj = ctor.newInstance(ctx);
于 2011-06-28T18:36:40.837 に答える
0

View オブジェクトのデフォルトのコンストラクターはありません。Class.newInstance()の javadoc を見てください。InstantiationException一致するコンストラクターが見つからない場合にスローします。

于 2011-06-28T18:37:23.193 に答える
0

Google で「java class.newInstance」を検索しました。

a) この例外がスローされる正確な状況を説明している java.lang.Class クラスのドキュメントを見つけました。

InstantiationException - if this Class represents an abstract class, an
interface, an array class, a primitive type, or void; or if the class has
no nullary constructor; or if the instantiation fails for some other reason.

b) 提案された検索用語は「java class.newinstance with parameters」で、StackOverflow からの結果を含む、「class has no nullary constructor」のケースに対処するためのいくつかのアプローチを見つけます。

クラスのリストに配列クラス、プリミティブ型、または「void」がなく、「その他の理由」はほとんどありません(とにかく例外メッセージで説明されます)。クラスが抽象またはインターフェースである場合、それをインスタンス化することはできません。

于 2011-06-28T18:40:21.780 に答える