2014-02-23 29 views
0

下面的代碼:的TextView可達代碼

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編譯)

I'm一個newbe所以請儘量給一個不太複雜的答案。對不起,英文不好。謝謝

回答

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

和Intialize在底部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 
} 
+0

Thx爲簡單的答案;) – pos1

4

放回到意見。

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