標籤:android broadcastreceiver fragment
首先描述下所要實現的功能點:
MainActivity使用Fragment實現底部菜單,底部共有四個功能表按鈕,分別對應:AFragment,BFragment,CFragment,DFragment。其中AFragment是預設顯示。
點擊CFragment中的一個button後跳轉到第二個Activity介面:SecondActivity。
SecondActivity返回鍵有兩個:button01、button02.其中button01返回的是CFragment;button02返回的是AFragment。
問題出現了:
button01可以返回到MainActivity中的CFragment,但是button02卻沒實現返回到MainActivity中的AFragment,無論是在SecondActivity中使用finish(),還是使用Intent跳轉,都不能實現返回到MainActivity中的AFragment。
最後想到了廣播機制來實現(我總感覺應該有更簡單更好的方法,卻始終沒找到,迫不得已使用廣播機制)。
去出現了另外一個問題:
Fragment java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState。
最後fragmentTransaction.commitAllowingStateLoss()替換掉fragmentTransaction.commit()解決問題。
最後再瀏覽下代碼:
import java.util.ArrayList;import android.annotation.SuppressLint;import android.app.Activity;import android.app.AlertDialog;import android.app.Dialog;import android.content.BroadcastReceiver;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.content.IntentFilter;import android.graphics.Color;import android.graphics.drawable.Drawable;import android.os.Bundle;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentTransaction;import android.view.MotionEvent;import android.view.View;import android.view.View.OnClickListener;import android.widget.ImageButton;import android.widget.TextView;import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;import com.nostra13.universalimageloader.core.ImageLoader;import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;import com.nostra13.universalimageloader.core.assist.QueueProcessingType;public class MainActivity extends BaseActivity {private static final String LOG_TAG = MainActivity.class.getSimpleName();private FragmentManager fragmentManager;private TextView txt_home;private TextView txt_find;private TextView txt_collection;private TextView txt_setting;private FragmentTransaction transaction;private HomeFragment homeFragment;private FindFragment findFragment;private CollectionFragment collectionFragment;private SettingFragment settingFragment;private ImageButton imgbtn_voice;private final static int SCANNIN_GREQUEST_CODE = 65537;private BackBroadcast backBroadcast;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);ResourceHelper.activityContext = this;setContentView(R.layout.activity_main);initImageLoaderConfi();initView();}/** * 底部菜單切換 */private void initView() {fragmentManager = getSupportFragmentManager();txt_home = (TextView) findViewById(R.id.home_text);txt_find = (TextView) findViewById(R.id.find_text);txt_collection = (TextView) findViewById(R.id.collection_text);txt_setting = (TextView) findViewById(R.id.setting_text);txt_home.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {setTabSelection(0);}});txt_find.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {setTabSelection(1);}});txt_collection.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {setTabSelection(2);}});txt_setting.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {setTabSelection(3);}});setTabSelection(0);}@SuppressLint("NewApi")public void setTabSelection(int index) {clearSelection();transaction = fragmentManager.beginTransaction();hideFragments(transaction);switch (index) {case 0:// 當點擊了tab時,改變控制項的圖片和文字顏色Drawable drawable01 = this.getResources().getDrawable(R.drawable.home_home_pressed);txt_home.setCompoundDrawablesRelativeWithIntrinsicBounds(null, drawable01, null, null);txt_home.setTextColor(Color.parseColor("#2786c8"));if (homeFragment == null) {homeFragment = new HomeFragment();transaction.add(R.id.content, homeFragment);} else {transaction.show(homeFragment);}break;case 1:Drawable drawable02 = this.getResources().getDrawable(R.drawable.home_find_pressed);txt_find.setCompoundDrawablesRelativeWithIntrinsicBounds(null, drawable02, null, null);txt_find.setTextColor(Color.parseColor("#2786c8"));if (findFragment == null) {findFragment = new FindFragment();transaction.add(R.id.content, findFragment);} else {transaction.show(findFragment);}break;case 2:Drawable drawable03 = this.getResources().getDrawable(R.drawable.home_collection_pressed);txt_collection.setCompoundDrawablesRelativeWithIntrinsicBounds(null, drawable03, null, null);txt_collection.setTextColor(Color.parseColor("#2786c8"));if (collectionFragment == null) {collectionFragment = new CollectionFragment();transaction.add(R.id.content, collectionFragment);} else {transaction.show(collectionFragment);}break;case 3:Drawable drawable04 = this.getResources().getDrawable(R.drawable.home_setting_pressed);txt_setting.setCompoundDrawablesRelativeWithIntrinsicBounds(null, drawable04, null, null);txt_setting.setTextColor(Color.parseColor("#2786c8"));if (settingFragment == null) {settingFragment = new SettingFragment();transaction.add(R.id.content, settingFragment);} else {transaction.show(settingFragment);}break;}transaction.commitAllowingStateLoss(); //該處是重點,如果使用transaction.commit()會一直崩潰報錯。}// 每次選中之前先清楚掉上次的選中狀態@SuppressLint("NewApi")private void clearSelection() {txt_home.setTextColor(Color.parseColor("#82858b"));Drawable drawableHome = this.getResources().getDrawable(R.drawable.home_home_normal);txt_home.setCompoundDrawablesRelativeWithIntrinsicBounds(null, drawableHome, null, null);txt_find.setTextColor(Color.parseColor("#82858b"));Drawable drawableFind = this.getResources().getDrawable(R.drawable.home_find_normal);txt_find.setCompoundDrawablesRelativeWithIntrinsicBounds(null, drawableFind, null, null);txt_collection.setTextColor(Color.parseColor("#82858b"));Drawable drawableMy = this.getResources().getDrawable(R.drawable.home_collection_normal);txt_collection.setCompoundDrawablesRelativeWithIntrinsicBounds(null, drawableMy, null, null);txt_setting.setTextColor(Color.parseColor("#82858b"));Drawable drawableMore = this.getResources().getDrawable(R.drawable.home_setting_normal);txt_setting.setCompoundDrawablesRelativeWithIntrinsicBounds(null, drawableMore, null, null);}// 先隱藏掉所有的Fragment,以防止有多個Fragment顯示在介面上的情況private void hideFragments(FragmentTransaction transaction) {if (homeFragment != null) {transaction.hide(homeFragment);}if (findFragment != null) {transaction.hide(findFragment);}if (collectionFragment != null) {transaction.hide(collectionFragment);}if (settingFragment != null) {transaction.hide(settingFragment);}}@Overrideprotected void onResume() {super.onResume();//setTabSelection(0);backBroadcast = new BackBroadcast();registerReceiver(backBroadcast, new IntentFilter(Constant.HOME_BACK_ACTION));}@Overrideprotected void onDestroy() {super.onDestroy();unregisterReceiver(backBroadcast);}private class BackBroadcast extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent) {String temp = intent.getAction();if (temp.equals(Constant.HOME_BACK_ACTION)) {setTabSelection(0);}}}@Overrideprotected void onSaveInstanceState(Bundle outState) {super.onSaveInstanceState(outState);}}
順便把布局也貼出來吧:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" > <FrameLayout android:id="@+id/content" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" > </FrameLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/home_bottom" android:baselineAligned="true" > <TextView android:id="@+id/home_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="10dip" android:layout_weight="1" android:drawableTop="@drawable/home_home" android:gravity="center" android:text="首頁" android:textColor="#82858b" /> <TextView android:id="@+id/find_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="10dip" android:layout_weight="1" android:drawableTop="@drawable/home_find" android:gravity="center" android:text="發現" android:textColor="#82858b" /> <TextView android:id="@+id/collection_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="10dip" android:layout_weight="1" android:drawableTop="@drawable/home_collection" android:gravity="center" android:text="收藏" android:textColor="#82858b" /> <TextView android:id="@+id/setting_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="10dip" android:layout_weight="1" android:drawableTop="@drawable/home_setting" android:gravity="center" android:text="設定" android:textColor="#82858b" /> </LinearLayout></LinearLayout>
Fragment java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState