zoukankan      html  css  js  c++  java
  • [android]R.class里有ID,onCreate方法里调用findViewById返回空

    在做android练习,一个新手错误,记录一下:

    在练习android权威编程指南时,第5章 第二个Activity部分练习,出现标题问题,代码还原如下:

    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mQuestionTitle = (TextView)findViewById(R.id.question_title);
            mQuestionAnswer = (TextView)findViewById(R.id.answer_text_view);
            mShowAnswer = (Button)findViewById(R.id.show_answer_button);
            setContentView(R.layout.activity_cheat);
            String mAnswerIsTrue = getIntent().getStringExtra(EXTRA_ANSWER);
            if(mAnswerIsTrue != null && mAnswerIsTrue.equals("")==false){
                mCheatQuestion = GSON.fromJson(mAnswerIsTrue,Question.class);
                mQuestionAnswer.setText(mCheatQuestion.getTextResId());
            }else{
                mQuestionTitle.setText(R.string.cheat_activity_error);
                mQuestionAnswer.setText(R.string.cheat_activity_error);
            }

    错误原因是没有设置ContentView就获取对象了,要把findViewById置于setContentView函数下面:

    setContentView(R.layout.activity_cheat);
    
    mQuestionTitle = (TextView)findViewById(R.id.question_title);
            mQuestionAnswer = (TextView)findViewById(R.id.answer_text_view);
            mShowAnswer = (Button)findViewById(R.id.show_answer_button);
            

     

  • 相关阅读:
    CMake 用法导览
    Irrlicht 1.8.4 + Win7 + VC2015 + x64 +OpenGL编译
    VirtualBox 5.1.14 获取VirtualBox COM对象错误
    CGAL Manual/tutorial_hello_world.html
    CGAL 介绍
    Open CASCADE 基础类(Foundation Classes)
    OpenCASCADE 基础
    Nginx 反向代理详解
    修改docker容器中的hosts文件
    Jmeter 设置连接oracle数据库
  • 原文地址:https://www.cnblogs.com/aocshallo1/p/12256343.html
Copyright © 2011-2022 走看看