这是我的应用程序的范围:
我正在尝试使用 ViewPager 和 Fragment 编写应用程序。应用程序的布局有 2 个选项卡(主页/配置)。这些选项卡之一的片段可以更改为另一个。例如:* FragmentHome(在 TabHome 中)被 FragmentGraphics 替换。如果用户按下按钮返回,FragmentHome 将再次显示。
问题(1):应用程序在打开之前崩溃并关闭。我不知道会发生什么。问题(2):如何用另一个视图寻呼机替换片段?(FragmentHome 中的 button1ClickListener)?
希望得到帮助!
代码:
ActivityMain.java
import java.util.List;
import java.util.Vector;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
public class ActivityMain extends FragmentActivity {
private TabHost mTabHost;
private PagerAdapter mPagerAdapter;
private ViewPager mViewPager;
List<Fragment> fragments = new Vector<Fragment>();
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setLayout(savedInstanceState);
}
@Override
public void onBackPressed() {
if(!mPagerAdapter.back(getSupportFragmentManager())) {
super.onBackPressed();
}
}
public void setLayout(Bundle args){
this.mViewPager = (ViewPager)findViewById(R.id.viewpager);
this.mTabHost = (TabHost)findViewById(android.R.id.tabhost);
//HomeTab
TabSpec tabSpecHome = mTabHost.newTabSpec(getResources().getString(R.string.tab_home_name));
tabSpecHome.setIndicator(getResources().getString(R.string.tab_home_label));
//ConfigTab
TabSpec tabSpecConfig = mTabHost.newTabSpec(getResources().getString(R.string.tab_config_name));
tabSpecConfig.setIndicator(getResources().getString(R.string.tab_config_label));
this.mPagerAdapter = new PagerAdapter(this, this.mTabHost,this.mViewPager);
//HomeTab
this.mPagerAdapter.addTab(tabSpecHome, FragmentHome.class, args);
this.mPagerAdapter.addFragment(getSupportFragmentManager(), getResources().getString(R.string.tab_home_name), FragmentHome.class, null);
//ConfigTab
this.mPagerAdapter.addTab(tabSpecConfig, FragmentConfig.class, args);
this.mPagerAdapter.addFragment(getSupportFragmentManager(), getResources().getString(R.string.tab_config_name), FragmentConfig.class, null);
}
}
PagerAdapter.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Stack;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TabWidget;
public class PagerAdapter extends FragmentPagerAdapter {
private final Context mContext;
private final TabHost mTabHost;
private final ViewPager mViewPager;
private ArrayList<String> mTabTags = new ArrayList<String>();
private HashMap<String, Stack<TabInfo>> mTabStackMap = new HashMap<String, Stack<TabInfo>>();
public interface SaveStateBundle{
public Bundle onRemoveFragment(Bundle outState);
}
public PagerAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager){
super(activity.getSupportFragmentManager());
this.mContext = activity;
this.mTabHost = tabHost;
this.mTabHost.setOnTabChangedListener(tabChangeListener);
this.mViewPager = pager;
this.mViewPager.setAdapter(this);
this.mViewPager.setOnPageChangeListener(viewPagerChangeListener);
}
@Override
public Fragment getItem(int position) {
Stack<TabInfo> tabStack = mTabStackMap.get(mTabTags.get(position));
TabInfo info = tabStack.peek();
return Fragment.instantiate(mContext, info.getClass().getName(), info.getArgs());
}
@Override
public int getItemPosition(Object object) {
ArrayList<Class<?>> positionNoneHack = new ArrayList<Class<?>>();
for(Stack<TabInfo> tabStack: mTabStackMap.values()){
positionNoneHack.add(tabStack.peek().getClass());
}
if(positionNoneHack.contains(object.getClass())){
return POSITION_UNCHANGED;
}
return POSITION_NONE;
}
public void addTab(TabSpec tabSpec, Class<?> clss, Bundle args){
try{
this.mTabHost.setup();
Stack<TabInfo> tabStack = new Stack<TabInfo>();
tabSpec.setContent(new TabContent(this.mContext));
this.mTabHost.addTab(tabSpec);
String tag = tabSpec.getTag();
TabInfo info = new TabInfo(tag, clss, args);
this.mTabTags.add(tag);
tabStack.add(info);
this.mTabStackMap.put(tag, tabStack);
notifyDataSetChanged();
}catch(Exception ex){
ex.printStackTrace();
}
}
public void addFragment(FragmentManager fm, String _tag, Class<?> _class, Bundle _args){
try{
TabInfo info = new TabInfo(_tag, _class, _args);
Stack<TabInfo> tabStack = mTabStackMap.get(_tag);
Fragment frag = fm.findFragmentByTag("android:switcher:" + mViewPager.getId() + ":" + mTabTags.indexOf(_tag));
if(frag instanceof SaveStateBundle){
Bundle b = new Bundle();
((SaveStateBundle) frag).onRemoveFragment(b);
tabStack.peek().setArgs(b);
}
tabStack.add(info);
FragmentTransaction ft = fm.beginTransaction();
ft.remove(frag);
ft.addToBackStack(null);
ft.commit();
notifyDataSetChanged();
}catch(Exception ex){
ex.printStackTrace();
}
}
public boolean popFragment(FragmentManager fm, String _tag){
Stack<TabInfo> tabStack = mTabStackMap.get(_tag);
if(tabStack.size()>1){
tabStack.pop();
Fragment frag = fm.findFragmentByTag("android:switcher:" + mViewPager.getId() + ":" + mTabTags.indexOf(_tag));
FragmentTransaction ft = fm.beginTransaction();
ft.remove(frag);
ft.addToBackStack(null);
ft.commit();
notifyDataSetChanged();
return true;
}
return false;
}
public boolean back(FragmentManager fm) {
int position = mViewPager.getCurrentItem();
return popFragment(fm, mTabTags.get(position));
}
@Override
public int getCount() {
return mTabStackMap.size();
}
@Override
public void notifyDataSetChanged(){
super.notifyDataSetChanged();
}
private final ViewPager.OnPageChangeListener viewPagerChangeListener = new ViewPager.OnPageChangeListener(){
@Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
TabWidget widget = mTabHost.getTabWidget();
int oldFocusability = widget.getDescendantFocusability();
widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
mTabHost.setCurrentTab(position);
widget.setDescendantFocusability(oldFocusability);
}
};
private final TabHost.OnTabChangeListener tabChangeListener = new TabHost.OnTabChangeListener(){
@Override
public void onTabChanged(String tabId) {
int pos = mTabHost.getCurrentTab();
mViewPager.setCurrentItem(pos);
}
};
}
TabContent.java
import android.content.Context;
import android.view.View;
import android.widget.TabHost.TabContentFactory;
public class TabContent implements TabContentFactory{
private final Context mContext;
public TabContent(Context context){
mContext = context;
}
@Override
public View createTabContent(String tag) {
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
TabInfo.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
public class TabInfo {
private String tag;
private Class<?> clss;
private Bundle args;
private Fragment fragment;
public TabInfo(String tag, Class<?> clazz, Bundle args) {
this.tag = tag;
this.clss = clazz;
this.args = args;
}
public void setTag(String tag){
this.tag = tag;
}
public String getTag(){
return this.tag;
}
public void setClazz(Class<?> clzz){
this.clss = clzz;
}
public Class<?> getClazz(){
return this.clss;
}
public void setArgs(Bundle args){
this.args = args;
}
public Bundle getArgs(){
return this.args;
}
public Fragment getFragment(){
return this.fragment;
}
}
片段主页.java
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class FragmentHome extends Fragment{
Button button1;
View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(container == null){
return null;
}
this.view = inflater.inflate(R.layout.home, container, false);
this.setItens();
return this.view;
}
private void setItens(){
button1 = (Button)this.view.findViewById(R.id.button1);
button1.setOnClickListener(button1OnClickListener);
}
private final View.OnClickListener button1OnClickListener = new View.OnClickListener(){
public void onClick(View v) {
showFragmentGraphics();
}
};
public void showFragmentGraphics(){
//the code for replace fragment home
}
}
显现
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="br.com.my.app"
android:versionCode="1"
android:versionName="1.0.0"
android:installLocation="internalOnly">
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".ActivityMain"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation">
<intent-filter android:label="@string/app_name">
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
现在,错误日志
04-30 18:56:19.591: E/AndroidRuntime(1275): FATAL EXCEPTION: main
04-30 18:56:19.591: E/AndroidRuntime(1275): java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.my.app/br.com.my.app.ActivityMain}: java.lang.NullPointerException
04-30 18:56:19.591: E/AndroidRuntime(1275): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
04-30 18:56:19.591: E/AndroidRuntime(1275): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
04-30 18:56:19.591: E/AndroidRuntime(1275): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
04-30 18:56:19.591: E/AndroidRuntime(1275): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
04-30 18:56:19.591: E/AndroidRuntime(1275): at android.os.Handler.dispatchMessage(Handler.java:99)
04-30 18:56:19.591: E/AndroidRuntime(1275): at android.os.Looper.loop(Looper.java:123)
04-30 18:56:19.591: E/AndroidRuntime(1275): at android.app.ActivityThread.main(ActivityThread.java:3683)
04-30 18:56:19.591: E/AndroidRuntime(1275): at java.lang.reflect.Method.invokeNative(Native Method)
04-30 18:56:19.591: E/AndroidRuntime(1275): at java.lang.reflect.Method.invoke(Method.java:507)
04-30 18:56:19.591: E/AndroidRuntime(1275): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-30 18:56:19.591: E/AndroidRuntime(1275): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-30 18:56:19.591: E/AndroidRuntime(1275): at dalvik.system.NativeStart.main(Native Method)
04-30 18:56:19.591: E/AndroidRuntime(1275): Caused by: java.lang.NullPointerException
04-30 18:56:19.591: E/AndroidRuntime(1275): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:651)
04-30 18:56:19.591: E/AndroidRuntime(1275): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
04-30 18:56:19.591: E/AndroidRuntime(1275): at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:551)
04-30 18:56:19.591: E/AndroidRuntime(1275): at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1129)
04-30 18:56:19.591: E/AndroidRuntime(1275): at android.app.Activity.performStart(Activity.java:3791)
04-30 18:56:19.591: E/AndroidRuntime(1275): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1620)
04-30 18:56:19.591: E/AndroidRuntime(1275): ... 11 more