我在构建我的第一个应用程序时遇到问题。我正在使用导航抽屉在片段之间进行切换。但是,当我从导航抽屉中选择OrderFragment时,应用程序崩溃。
单击时,OrderFragment只有一个按钮显示吐司,但是应用程序在OrderFragment加载之前崩溃。
代码是:
MainActivity.java
package com.example.testcocogeek;
import android.app.Activity;
import android.app.Fragment;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
private String[] mListOptions;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private ActionBarDrawerToggle mDrawerToggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mListOptions = getResources().getStringArray(R.array.list_options);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set adapter for the list view
mDrawerList.setAdapter (new ArrayAdapter<String> (this,
R.layout.drawer_list_item, mListOptions));
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// Set the list click listener
mDrawerList.setOnItemClickListener (new DrawerItemClickListener());
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, "Cocogeek");
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listener for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
// This method selects correct fragment.
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
Bundle args = new Bundle();
switch (position) {
case 0:
fragment = new CocogeekFragment();
break;
case 1:
fragment = new OrderFragment();
break;
case 2:
fragment = new LocatorFragment();
break;
case 3:
fragment = new ContactFragment();
break;
default:
break;
}
fragment.setArguments(args);
android.app.FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment)
.commit();
mDrawerList.setItemChecked(position, true);
setTitle(mListOptions[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
OrderFragment.java
package com.example.testcocogeek;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class OrderFragment extends Fragment implements OnClickListener {
public OrderFragment() {
// Empty constructor required for fragment subclasses
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mView = (View) inflater.inflate(R.layout.order_fragment, container, false);
// Initialize UI views.
final Button send = (Button) getActivity().findViewById(R.id.send);
//Initialize OnClick listener.
send.setOnClickListener(this);
return mView;
}
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Clicked" ,Toast.LENGTH_LONG).show();
}
}
activity_main.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFF5EE"
>
<!-- The main content view -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</FrameLayout>
<!-- The navigation drawer -->
<ListView android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="#858585"/>
</android.support.v4.widget.DrawerLayout>
order_fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/send"
/>
</LinearLayout>
logCat:
07-08 12:28:09.332: D/dalvikvm(30471): GC_FOR_ALLOC freed 165K, 2% free 16940K/17136K, paused 15ms, total 15ms
07-08 12:28:09.362: I/dalvikvm-heap(30471): Grow heap (frag case) to 35.315MB for 19655120-byte allocation
07-08 12:28:09.372: D/dalvikvm(30471): GC_FOR_ALLOC freed 2K, 1% free 36132K/36332K, paused 11ms, total 11ms
07-08 12:28:09.522: I/Adreno-EGL(30471): <qeglDrvAPI_eglInitialize:320>: EGL 1.4 QUALCOMM Build: I0404c4692afb8623f95c43aeb6d5e13ed4b30ddbDate: 11/06/13
07-08 12:28:09.542:D / OpenGLRenderer(30471):启用调试模式0
07-08 12:28:11.852:D / AndroidRuntime(30471):关闭VM
07-08 12:28:11.852:W / dalvikvm(30471):threadid = 1:线程以未捕获的异常退出(group = 0x41625ba8)
07-08 12:28:11.862:E / AndroidRuntime(30471):致命异常:主
07-08 12:28:11.862:E / AndroidRuntime(30471):进程:com.example.testcocogeek,PID:30471
07-08 12:28:11.862:E / AndroidRuntime(30471):java.lang.NullPointerException
07-08 12:28:11.862:E / AndroidRuntime(30471):位于com.example.testcocogeek.OrderFragment.onCreateView(OrderFragment.java:29)
07-08 12:28:11.862:E / AndroidRuntime(30471):位于android.app.Fragment.performCreateView(Fragment.java:1700)
07-08 12:28:11.862:E / AndroidRuntime(30471):位于android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
07-08 12:28:11.862:E / AndroidRuntime(30471):位于android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
07-08 12:28:11.862:E / AndroidRuntime(30471):位于android.app.BackStackRecord.run(BackStackRecord.java:684)
07-08 12:28:11.862:E / AndroidRuntime(30471):位于android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
07-08 12:28:11.862:E / AndroidRuntime(30471):位于android.app.FragmentManagerImpl $ 1.run(FragmentManager.java:443)
07-08 12:28:11.862:E / AndroidRuntime(30471):位于android.os.Handler.handleCallback(Handler.java:733)
07-08 12:28:11.862:E / AndroidRuntime(30471):位于android.os.Handler.dispatchMessage(Handler.java:95)
07-08 12:28:11.862:E / AndroidRuntime(30471):位于android.os.Looper.loop(Looper.java:136)
07-08 12:28:11.862:E / AndroidRuntime(30471):位于android.app.ActivityThread.main(ActivityThread.java:5001)
07-08 12:28:11.862:E / AndroidRuntime(30471):at java.lang.reflect.Method.invokeNative(本机方法)
07-08 12:28:11.862:E / AndroidRuntime(30471):at java.lang.reflect.Method.invoke(Method.java:515)
07-08 12:28:11.862:E / AndroidRuntime(30471):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:785)
07-08 12:28:11.862:E / AndroidRuntime(30471):位于com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
07-08 12:28:11.862:E / AndroidRuntime(30471):在dalvik.system.NativeStart.main(本机方法)
07-08 12:28:13.332:I / Process(30471):发送信号PID:30471 SIG:9
最佳答案
乍一看,您应该更换:
final Button send = (Button) getActivity().findViewById(R.id.send);
与:
final Button send = (Button) mView.findViewById(R.id.send);
R.id.send
id包含在“片段”视图mView
中。