安卓 java。添加TextChangedListener时的lang.NullPointerException
将addTextChangedListener添加到onCreate时出现以下错误 操作系统Android 4.4 API19:
错误:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nes.安卓.emplacements/com.nes.安卓.emplacements.MainActivity}: java.lang.NullPointerException
Caused by: java.lang.NullPointerException
at com.nes.安卓.emplacements.MainActivity.onCreate(MainActivity.java:32)
at 安卓.app.Activity.performCreate(Activity.java:5231)
at 安卓.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at 安卓.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
at 安卓.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at 安卓.app.ActivityThread.access$800(ActivityThread.java:135)
这是我的密码:
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
EditText valEmplacement = (EditText)findViewById(R.id.editText2);
valEmplacement.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) { }
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
}
editText2位于fragment_main中,而不在Activy_main中
活动区。xml:
<FrameLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
xmlns:tools="http://schemas.安卓.com/tools"
安卓:id="@+id/container"
安卓:layout_width="match_parent"
安卓:layout_height="match_parent"
tools:context="com.nes.安卓.emplacements.MainActivity"
tools:ignore="MergeRootFrame" />
梅因。xml:
<RelativeLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
xmlns:tools="http://schemas.安卓.com/tools"
安卓:layout_width="match_parent"
安卓:layout_height="match_parent"
安卓:paddingLeft="@dimen/activity_horizontal_margin"
安卓:paddingRight="@dimen/activity_horizontal_margin"
安卓:paddingTop="@dimen/activity_vertical_margin"
安卓:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.nes.安卓.emplacements.MainActivity$PlaceholderFragment"
安卓:focusable="true">
<EditText
安卓:layout_width="fill_parent"
安卓:layout_height="80px"
安卓:id="@+id/editText2"
安卓:inputType="text"
安卓:layout_below="@+id/textView"
安卓:background="#cccccc"
安卓:autoText="false"
安卓:textSize="20px"
安卓:textIsSelectable="true" />
<TextView
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:textAppearance="?安卓:attr/textAppearanceLarge"
安卓:text="@string/text_emplacement"
安卓:id="@+id/textView"
安卓:layout_below="@+id/textView3"
安卓:layout_alignParentLeft="true"
安卓:layout_alignParentStart="true"
安卓:layout_marginTop="46dp"
安卓:layout_alignParentRight="true"
安卓:layout_alignParentEnd="true" />
</RelativeLayout>
# 1 楼答案
试试清洁&清洁;在eclipse中构建项目以重新生成R文件
并确保Activy_主布局包含id为editText2的元素
更新:我看到id为editText2的视图实际上在片段布局中。因此,我建议您将处理此编辑文本视图的代码移动到Fragment类中。例如,在片段类的这个方法中: