在app中制作硬币翻转选项。这是杀死我的部分:
public ImageView tails;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.....
}
菜单中的是问题发生的地方:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.coin_flip:
final Context cointext = this;
final Dialog flip = new Dialog(cointext);
flip.setContentView(R.layout.coin);
flip.setTitle("Coin Flip");
flip.setCancelable(true);
n = 99;
n = (generator.nextInt(n)) + 1;
tails.findViewById(R.id.tails).setVisibility(1);
if (n % 2 == 0) {
tails.findViewById(R.id.tails).setVisibility(0);
}else {
tails.findViewById(R.id.tails).setVisibility(1);
}
Button flipBtn = (Button)findViewById(R.id.flipBtn);
flipBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (n % 2 == 0) {
tails.findViewById(R.id.tails).setVisibility(0);
}else {
tails.findViewById(R.id.tails).setVisibility(1);
}
}
});
flip.show();
}
}
我不断收到NullPointerException:
tails.findViewById(R.id.tails).setVisibility(1);
任何想法如何解决这个问题?提前致谢
答案 0 :(得分:3)
Tails没有被初始化。
你应该说
tails = (ImageView)findViewById(R.id.tails);
tails.setVisibility(View.VISIBLE);