在这里声明
TextView mTextView; // Member variable for text view in the layout // Right here
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
在方法之外声明它,通常在类声明之后,使其成为成员变量,因此它可以在类中的任何地方使用,包括内部类和侦听器。你只是不能在同一个地方初始化它,因为你还inflated
没有Layout
通过调用setContentView()
简短的例子
public class MyActivity extends Activity
{
TextView mTextView; // Member variable for text view in the layout
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the user interface layout for this Activity
// The layout file is defined in the project res/layout/main_activity.xml file
setContentView(R.layout.main_activity);
// Initialize member TextView so we can manipulate it later
mTextView = (TextView) findViewById(R.id.text_message); // findViewById) looks for the id you set in the xml file, here text_message
}
R.id.text_message
被定义在main_activity.xml
其中可能看起来像这样
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text_message" <!-- this is where the R.id.text_message comes from -->
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"/>
</LinearLayout>
该文档绝对值得阅读,但您可能想从这里开始,并从创建项目开始阅读一个简短的示例