繁体   English   中英

TextView无法访问的代码

[英]TextView unreachable code

这里的代码:

package com.example.appbsp;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;

    TextView textView1 = (TextView)
             findViewById(R.id.textView1);
}

}

首先,我在activity_main.xml中添加了一个新的TextView并为其指定了ID:@ + id / textView1,然后在MainActivity.java中输入以下代码以获取更多输出:

TextView textView1 = (TextView)
             findViewById(R.id.textView1);

然后,我导入了android.widget.TextView,但是随后的上部代码变成了红色下划线,并且表示无法访问的代码,只是“删除”了快速修复方法。 它工作之前的一个月,现在我不再工作了。 有人知道答案吗?

(目标SDK:API 18;使用API​​ 19编译)

我是newbe,所以请尝试给出一个不太复杂的答案。 对不起,英语不好。 谢谢

放回底部。

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);


    TextView textView1 = (TextView)
             findViewById(R.id.textView1);

     return true;
}

因为您在该语句之前写了return true ,所以为什么这一行TextView textView1 = (TextView) findViewById(R.id.textView1); 是无法访问的,因为编译器不会到达此语句。

像这样

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

并在onCreate初始化视图

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView textView1 = (TextView) findViewById(R.id.textView1);            
    // you can set the text here any
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM