簡體   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