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