【问题标题】:TextView unreachable codeTextView 无法访问的代码
【发布时间】:2014-02-23 12:42:06
【问题描述】:

代码如下:

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 编译)

我是新手,所以请尽量给出一个不太复杂的答案。抱歉英语不好。谢谢

【问题讨论】:

    标签: java android unreachable-code


    【解决方案1】:

    将返回放在底部。

    @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;
    }
    

    【讨论】:

      【解决方案2】:

      因为您在该语句之前写了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
      }
      

      【讨论】:

      • 谢谢你的简单回答;)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      相关资源
      最近更新 更多