我在应用程序中创建了一个Android全局变量,当我尝试使用getApplication在活动中访问它时,出现错误消息:
无法解析方法getApplication()
我在扩展Application的类中的代码:
package com.example.user.app;
import android.app.Application;
public class answer extends Application {
private String answer1;
public String getSomeVariable() {
return answer1;
}
public void setanswer1(String one) {
this.answer1 = one;
}
}
我在活动中的代码:
package com.example.user.pilz_app;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageButton;
public class QuestionOne extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question_one);
ImageButton half = findViewById(R.id.half);
half.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(QuestionOne.this, QuestionTwo.class);
startActivity(intent);
((answer) this.getApplication()).setanswer1("half");
}
});
最佳答案
您正在使用匿名类引用
half.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(QuestionOne.this, QuestionTwo.class);
startActivity(intent);
((answer) this.getApplication()).setanswer1("half");
}
此时,请参见
this
,它指向OnClickListener引用而不是Activity的引用。因此,您可以做的是使用如下所示的完全合格的参考。QuestionOne.this.getApplication().setanswer1("half");