不幸的是,我试图启动NewEventActivity
时按下浮动操作按钮会导致应用崩溃。这是我的代码:
MainActivity :
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void newEventIntent(View v){
Intent intent = new Intent(this, NewEventActivity.class);
startActivity(intent);
}
}
activity_main.xml :
<android.support.design.widget.FloatingActionButton
android:onClick="newEventIntent"
android:id="@+id/add_event_fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginRight="20dp"
android:layout_marginBottom="20dp"
android:src="@drawable/baseline_add_24"/>
LogCat :
java.lang.RuntimeException: Unable to start activity componentInfo{com.example.deadline/com.example.deadline.NewEventActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
我确保这两个活动都在清单中。
答案 0 :(得分:4)
原因是您试图将侦听器设置为布局中没有引用的FloatingActionButton
。
您应该按ID查找它:
添加private FloatingActionButton mFloatingActionButton;
和
floatingActionButton=findViewById(R.id.add_event_fab);
public class MainActivity extends AppCompatActivity {
private FloatingActionButton mFloatingActionButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
floatingActionButton=findViewById(R.id.add_event_fab);
}
public void newEventIntent(View v){
Intent intent = new Intent(this, NewEventActivity.class);
startActivity(intent);
}
}