更新到Android 4.4,写了个小程序。发现运行不起来了。抛空指针异常。debug模式下,发现在onCreate方法中获取Button是null。
Android 4.4把layout进行了重组,全部放到了Fragment下,在onCreate方法执行时,Fragment还没有被调用,所以在这个方法中获取Fragment中的Button是空值。新类中多了一个Fragment的内部类,当xml的Fragment被装载时,会调用内部类的onCreateView方法,所以要将所有之前在layout中而现在移到fragment中的操作全部移到此方法中进行。
package com.bignerdranch.android.geoquiz; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.ActionBarActivity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; public class TestActivity extends ActionBarActivity { private static Button mFirstButton; private static Button mSecondButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()).commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.test, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View rootView = inflater.inflate(R.layout.fragment_test, container, false); mFirstButton = (Button) rootView.findViewById(R.id.first_button); mFirstButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(rootView.getContext(), R.string.first_toast, Toast.LENGTH_SHORT).show(); } }); mSecondButton = (Button) rootView.findViewById(R.id.second_button); mSecondButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(rootView.getContext(), R.string.second_toast, Toast.LENGTH_SHORT).show(); } }); return rootView; } } }