【问题标题】:NullPointerException: when set TextView valueNullPointerException:设置 TextView 值时
【发布时间】:2012-02-13 15:11:08
【问题描述】:

我有一个布局文件(layout/my_test.xml):

<TextView
      android:id="@+id/my_title"
      android:gravity="left|center_vertical"
      android:layout_width="wrap_content"
      android:layout_height="fill_parent"
      />

我的活动:

import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.TextView;

public class MyActivity extends FragmentActivity{

    private View myTestView;    
    private TextView actionBarTitle;

    @Override
    protected void onCreate(Bundle arg0) {
       super.onCreate(arg0);

       myTestView = getLayoutInflater().inflate(R.layout.my_test, null);
       myTitle = (TextView) findViewById(R.id.my_title);

       //NullPointerException here !!
       myTitle.setText(getString(R.string.hello));
    }
}

(我确定问题不在于 res/strings.xml ,因为“hello”字符串资源已在其他地方使用,这很好。)

为什么我在设置TextView 内容时得到NullPointerException??

完整的错误跟踪:

 Caused by: java.lang.NullPointerException
E/AndroidRuntime(17283):    at com.test.MyActivity.onCreate(MyActivity.java:21)
E/AndroidRuntime(17283):    at com.eficode.card.CardActivity.onCreate(CarActivity.java:29)
E/AndroidRuntime(17283):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
E/AndroidRuntime(17283):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2669)
E/AndroidRuntime(17283):    ... 11 more

【问题讨论】:

  • 你没有设置任何东西显示在屏幕上?

标签: android android-layout android-intent android-emulator


【解决方案1】:

如下创建Textview id myTitle = (TextView) myTestView .findViewById(R.id.my_title);

【讨论】:

  • 嗨!谢谢,现在好了。但是你能解释一下为什么我不能在Activity中直接使用findViewById吗?
【解决方案2】:

您应该正确编写 onCreate,因为您没有设置任何要在屏幕上显示的内容:

@Override
    protected void onCreate(Bundle arg0) {
       super.onCreate(arg0);
       setContentView(R.layout.my_test);

       myTitle = (TextView) findViewById(R.id.my_title);

       myTitle.setText(getString(R.string.hello));
    }

【讨论】:

  • 不,我不能同意你的观点,因为活动不必总是设置内容。使用@Venkata Krishna 的答案后,我的代码运行良好。
  • 是的,您可以将您的活动保持空白,但如果您不希望它显示在任何地方,那么您的活动中的 TextView 的意义何在?这就是 android-developer 所说的:An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View).
【解决方案3】:

您只能在 setcontentView(R.layout.your_layout_id); 中声明的布局中直接获取视图的 ID。但是当你膨胀一些布局时,你必须在膨胀的视图中获取视图的 ID,如下所示 view_id.find....();

【讨论】:

    猜你喜欢
    • 2019-04-08
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 2013-07-07
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多