【问题标题】:Why setText() function doesn't work?为什么 setText() 函数不起作用?
【发布时间】:2013-12-13 19:31:42
【问题描述】:

你能告诉我为什么这段代码不起作用吗?一旦我单击图像(Imageview1),应用程序就会停止。调试器指向 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);
        }
    });

}           

【问题讨论】:

  • 尝试不在调试器中运行您的应用程序。
  • 为什么调试器会停在tv.setText(x)?那里有断点吗?调试器是否告诉您它停止的原因?是否显示任何消息?

标签: java settext


【解决方案1】:

扩展布局后,您需要获取 UI 元素,否则 findViewById 会返回 null,因此当您尝试在 textView 上设置文本时会抛出 NPE。

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);

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 2014-08-06
    • 2015-02-20
    • 2021-08-20
    • 2021-07-25
    • 2013-08-26
    • 2011-11-13
    • 2023-03-15
    相关资源
    最近更新 更多