Android启动活动介绍-定义文本消息

Android启动活动介绍-定义文本消息,android,Android,我正在编写Android指南:其中引用了一个从未创建过的变量 mTextView = (TextView) findViewById(R.id.text_message); 我应该在哪里定义文本消息 谢谢你的帮助 更新:我相信这段代码只是一个示例,不能与我们在本教程前一部分中创建的应用程序合并 在这里声明 TextView mTextView; // Member variable for text view in the layout // Right here @Override pu

我正在编写Android指南:其中引用了一个从未创建过的变量

mTextView = (TextView) findViewById(R.id.text_message);
我应该在哪里定义文本消息

谢谢你的帮助

更新:我相信这段代码只是一个示例,不能与我们在本教程前一部分中创建的应用程序合并

在这里声明

TextView mTextView; // Member variable for text view in the layout  // Right here

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
在方法之外声明它(通常在类声明之后),使其成为成员变量,因此可以在类中的任何位置使用它,包括内部类和侦听器。您不能在同一位置初始化它,因为您还没有调用
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\u message
是在
main\u 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>


使用这种方法在res/layout/main.xml文件夹中定义xml布局,并在setconentView中设置

private TextView mTextView = null; 
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    stContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.text_message);
mTextView.setText("Hello");
}

您可能还希望显示
findviewbyd()
的位置,并将所有内容包装在示例活动类中以显示完整语法(包括编译此文件所需的所有右大括号。您好,如果我不清楚,很抱歉,我正在更新我的问题。R.id.text_消息从未在任何地方定义过。回顾教程,它们显示的代码似乎只是一个示例,而不是我已经拥有的代码。@code Guru这就是教程的目的。但是如果有更多,我可以编辑confusion@jsc123我用一个简短的例子进行了编辑。如果没有意义,请告诉我