私はAndroidアプリケーション開発とJavaにはかなり新しく、別のクラスのメソッドを呼び出すときに次のエラーが発生しました:Android LoginActivityタイプから非静的メソッドshowToast(String)への静的参照を作成できません
Cannot make a static reference to the non-static method showToast(String) from the type LoginActivity
私は他のクラスでこれを呼び出し、クラス自体でそれをインスタンス化しないようにしたい理由は、適応性とアップグレードの問題です。これは私の素晴らしいコンセプトか、過大評価されているのでしょうか?
CreateAccountActivity
public class NewAccountActivity extends Activity{
private Button mCreateAccountButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newaccount);
mCreateAccountButton = (Button) findViewById(R.id.createaccount_button);
registerButtonListeners();
}
private void registerButtonListeners() {
mCreateAccountButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LoginActivity.showToast(getString(R.string.createaccount_message));
}
});
}
}
LoginActivity
public void showToast(String toastString) {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));
ImageView image = (ImageView) layout.findViewById(R.id.toastImage);
image.setImageResource(R.drawable.android);
TextView text = (TextView) layout.findViewById(R.id.toastText);
text.setText(toastString);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
}
それはエラーメッセージが離れて行かせる上で新しいLoginActivityオブジェクトを作成し、その後showToastを呼び出すことが、私与える:
関連するコードです代わりにNullPointerExceptionが発生します。
getLayoutInflaterが同じ「静的参照を作成できません...」というエラーが発生したため、showToast staticは機能しません。 Nullpointer例外は、getLayoutInflaterを使用しています。 –
LayoutInflater inflater = LayoutInflater.from(getApplicationContext())を試してください。代わりにgetLayoutInflater(); ? – Blackbelt
これを実行し、findViewById(R.id.toast_layout_root)をoncreateメソッドでインスタンス化され、showToastに渡された変数で置き換えました。 –