布局充气器上的NullPointer-安卓系统



我在MainActivity中调用的另一个java文件中有一个类。我需要在外部类中展开一些布局。我遇到的问题是指定上下文,因为当我尝试扩展布局时,会出现空指针异常。该类没有自己的onCreate()方法,所以我需要从MainActivity传递上下文?不知道该怎么做。这导致了NullPointerException:

Context context = getApplicationContext();
LayoutInflater inflater = (LayoutInflater)context.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);;

Context上下文上的NullPointerException

public class CameraListener extends Activity implements OnCameraChangeListener {
    private static final int SCALE_HEIGHT = 50;
    GoogleMap mMap;
    GoogleC3iActivity mParent;

    Context context = getApplicationContext();

多个问题

第一个

Context context = getApplicationContext();
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

你不应该需要getApplicationContext(),因为你已经有了它。

OR(署名:@Delyan)

LayoutInflater.from(context) 

第二次

Context context = getApplicationContext();setContentView之前不工作。因此,在onCreate 中调用setContentView后,需要初始化上下文

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.home);
    context = getApplicationContext() ;

LayoutInflater也是如此,您需要在onCreate 中初始化它

ActivityContext扩展而来,这意味着您只需要在onCreate()方法中使用LayoutInflater inflater = LayoutInflater.from(this);

最新更新