【问题标题】:Android Relative Layout Change TextView ProgrammaticallyAndroid相对布局以编程方式更改TextView
【发布时间】:2012-03-21 01:56:17
【问题描述】:

我正在尝试在我的应用程序中使用相对布局。有两个 TextViews 和一个 Button。这是xml文件:

    <RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:padding="30dip"
android:orientation="vertical">


<TextView
    android:id="@+id/up"
    android:text="@string/start_game"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    />

 <TextView
    android:id="@+id/level"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
     android:layout_below="@id/up"/>
    />

   <Button android:id="@+id/start"
   android:text = "@string/go"
   android:layout_height="wrap_content" 
   android:layout_width="fill_parent"  
   android:layout_alignParentBottom="true"
  />

  </RelativeLayout>

现在,id=up 的 TextView 完美显示。对于第二个 TextView(id=level),我想通过我的 java 代码向它添加文本。这是我所做的:

       TextView text = (TextView) findViewById(R.id.level);
       text.setText("Hello Android");

但这会使程序崩溃。我的错误是什么?

【问题讨论】:

  • 您在哪里执行该代码?请记住,您必须在 setContentView 之后执行此操作。
  • 那个代码应该是正确的,在eclipse debug中查看错误信息日志看看是哪一行代码有问题
  • 唉!我在 setContentView 之前执行它。谢谢@克里斯蒂安

标签: android textview android-relativelayout


【解决方案1】:

就是这样……您必须在使用findViewById之前始终调用setContentView

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    相关资源
    最近更新 更多