我已经研究了类似的问题,但是没有一个适合这个问题。我正在尝试从名为nextQuestion()的方法名称访问可绘制数组,但是我不断收到错误消息,无法解析符号'ballArray',请提供任何帮助。我只是觉得这应该起作用,但不知道为什么。这是我的代码。
公共类MainActivity扩展了AppCompatActivity {
ImageView mBallDisplay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int quote;
mBallDisplay = (ImageView) findViewById(R.id.image_eightBall);
Button nextbutton = (Button) findViewById(R.id.nextbutton);
Button prevbutton = (Button) findViewById(R.id.prevbutton);
final int[] ballArray = {
R.drawable.ball1,
R.drawable.ball2,
R.drawable.ball3,
R.drawable.ball4,
R.drawable.ball5
};
//next button
nextbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
nextQuestion();
}
});
//previous button
prevbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
prevQuestion();
}
});
}
private void nextQuestion(){
mBallDisplay.setImageResource(ballArray[4]);
}
private void prevQuestion(){
}
}
答案 0 :(得分:1)
您无法从ballArray
访问nextQuestion()
的原因是因为它是在单独的方法中声明的。如果希望从nextQuestion()
内部访问它,则需要在该级别使其可见:
ImageView mBallDisplay;
final int[] ballArray = {
R.drawable.ball1,
R.drawable.ball2,
R.drawable.ball3,
R.drawable.ball4,
R.drawable.ball5
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int quote;
mBallDisplay = (ImageView) findViewById(R.id.image_eightBall);
Button nextbutton = (Button) findViewById(R.id.nextbutton);
Button prevbutton = (Button) findViewById(R.id.prevbutton);
//next button
nextbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
nextQuestion();
}
});
//previous button
prevbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
prevQuestion();
}
});
}
private void nextQuestion(){
mBallDisplay.setImageResource(ballArray[4]);
}
private void prevQuestion(){
}
}
答案 1 :(得分:0)
这样做:-
public class MainActivity extends AppCompatActivity {
ImageView mBallDisplay;
int[] ballArray = {
R.drawable.ball1,
R.drawable.ball2,
R.drawable.ball3,
R.drawable.ball4,
R.drawable.ball5
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int quote;
mBallDisplay = (ImageView) findViewById(R.id.image_eightBall);
Button nextbutton = (Button) findViewById(R.id.nextbutton);
Button prevbutton = (Button) findViewById(R.id.prevbutton);
//next button
nextbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
nextQuestion();
}
});
//previous button
prevbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
prevQuestion();
}
});
}
private void nextQuestion(){
mBallDisplay.setImageResource(ballArray[4]);
}
private void prevQuestion(){
}
}