findViewById()不工作在不MainActivity类 [英] findViewById() not working in a not MainActivity class

查看:126
本文介绍了findViewById()不工作在不MainActivity类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Lyout文本视图,我想设置一些文本这个TextView的。 这应在一类,它不是一个MainActivity类制成。

I have a text view in my Lyout and I would like to set some text to this textview. This should be made in a class which is not a MainActivity class.

现在的问题是,我得到一个空指针异常。

The problem is that I got a null pointer exception.

下面是我的code:

public class UserInformations extends Activity{

TextView emailTextView;
LocalDatabase localdatabase= new LocalDatabase(this);


    public void getUserInformation()
    {
    emailTextView = (TextView) findViewById(R.id.EmailTextView);
    String email = localdatabase.getUserEmail();
    emailTextView.setText(email);
    }
}

当我这样做的主要活动类,它的工作原理,但它不能在另一个类不工作。

When I am doing this in the Main Activity class, it works, but it doesn't work not in another class.

推荐答案

调用 findViewById()活动如果当前活动布局由的setContentView 设置对象才有效。如果通过其他途径补充的布局,那么你需要的布局和呼叫 findViewById()查看对象就可以了。

Calling findViewById() on the Activity object will only work if the current Activity layout is set by setContentView. If you add a layout through some other means, then you need the View object of the layout and call findViewById() on it.

View v = inflater.inflate(id_number_of_layout);
View innerView = v.findViewById(id_number_of_view_inside_v);

如果布局应该是活动的主要布局,然后执行:

If the layout is supposed to be the main layout of the activity, then do this:

public class MyActivity extends Activity{
  TextView emailTextView; 

  @Override
  public void onCreate(Bundle savedInstanceState){
     super.onCreate(savedInstanceState);
     setContentView(id_number_of_layout);
     emailTextView = (TextView) findViewById(R.id.EmailTextView);
     // ... whatever other set up you need to do ...
  }

  public void getUserInformation() {
     // .... regular code ... 
  }
}

这篇关于findViewById()不工作在不MainActivity类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆