我在 LogCat 中收到此错误消息:
06-25 15:17:34.495:E/AndroidRuntime(5891):java.lang.RuntimeException:无法启动活动 ComponentInfo{com.example/com.example.MainActivity}: java.lang.NullPointerException 06-25 16:07 :43.589: E/AndroidRuntime(6587): 由: java.lang.NullPointerException 06-25 16:07:43.589: E/AndroidRuntime(6587): at com.example.MyTabsListener.onTabSelected(MyTabListener.java:28)
这是我的主要活动:
package com.example;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
public class MainActivity extends SherlockActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ActionBar actionbar = getSupportActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tab1 = actionbar.newTab().setText("Fragment A");
SherlockFragment fragment1 = new AFragment();
tab1.setTabListener(new MyTabsListener(fragment1, this
.getApplicationContext()));
actionbar.addTab(tab1);
}
}
还有我简单的 TabListener:
package com.example;
import android.content.Context;
import android.support.v4.app.FragmentTransaction;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragment;
class MyTabsListener implements ActionBar.TabListener {
public SherlockFragment fragment;
private final Context appContext;
public MyTabsListener(SherlockFragment fragment, Context ctx) {
this.fragment = fragment;
this.appContext = ctx;
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(this.appContext, "Reselected!", Toast.LENGTH_LONG)
.show();
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.fragment_container, fragment);
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(fragment);
}
}
最后是我的班级片段 A:
package com.example;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.app.SherlockFragment;
public class AFragment extends SherlockFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.weekdays, container, false);
}
}
所以这个函数导致 TabListener 中的错误:
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.fragment_container, fragment);
}