문제

can u tell me why this code is not working? The app stops as soon as I click on Image(Imageview1). Debugger points to tv.setText(x);

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final TextView tv = (TextView)findViewById(R.id.textView1);
setContentView(R.layout.activity_main);
ImageView img = (ImageView) findViewById(R.id.imageView1);
img.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        String x="You clicked on the image.";
            tv.setText(x);
        }
    });

}           
도움이 되었습니까?

해결책

You need to get your UI elements after inflating your layout, otherwise findViewById returns null and hence the NPE is thrown when you try to set the text on your textView.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);                       /// I swap these two lines
    final TextView tv = (TextView)findViewById(R.id.textView1);   ///
    ImageView img = (ImageView) findViewById(R.id.imageView1);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top