将setOnFocusChangeListener设置为EditText时,Android App崩溃

时间:2012-09-01 00:11:31

标签: android

当我将OnFocusChangeListener设置为editText时,我的应用程序一直崩溃..应用程序崩溃,我的logcat发送给我java.lang.nullPointerException..why?

public class MainActivity extends FragmentActivity 
    implements HeadlinesFragment.OnHeadlineSelectedListener {
 private int myYear, myMonth, myDay;
 static final int ID_DATEPICKER = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.news_articles);
    EditText txt1 = (EditText) findViewById(R.id.editText2);
    txt1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
             final Calendar c = Calendar.getInstance();
             myYear = c.get(Calendar.YEAR);
             myMonth = c.get(Calendar.MONTH);
             myDay = c.get(Calendar.DAY_OF_MONTH);
             showDialog(ID_DATEPICKER);
        }
      });

1 个答案:

答案 0 :(得分:1)

确保您的布局news_articles.xml内有editText2

如果您在NullPointerException上获得txt1.setOnFocusChangeListener,则可能是原因