第一種:Fragment對Activity傳遞數據
首先上張Gif圖,看起來直觀一點,直入主題。自己手機錄屏然後轉的Gif圖。
可以看出,通過點擊InfoFragment界面的按鈕來實現activity底部導航欄(這裏我用的BottomNavigationBar)數字的更新。
InfoFragment.java主要代碼
int num = 0;
public InfoCallback infoCallback;
public interface InfoCallback {
void updateBadgeCount(int num);
}
public void initView() {
bt = (Button) view.findViewById(R.id.fragment_info_bt);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
num++;
infoCallback.updateBadgeCount(num);
}
});
}
//這是最重要的代碼,目的就是爲接口賦值,使其不爲空
@Override
public void onAttach(Context context) {
super.onAttach(context);
Log.v(TAG, "--------onAttach");
//Fragment attach到Activity時,將Activity強轉爲Callbacks保存
if (context instanceof InfoCallback) {//如果宿主Activity實現了該接口
infoCallback = (InfoCallback) context; //infoCallback 指向該Activity
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
MainActivity.java主要代碼
public class MainActivity extends AppCompatActivity implements InfoFragment.InfoCallback {
@Override
public void updateBadgeCount(int num) {
//自己要做的操作
}
}
第一種:Activity通知Fragment更新
應用場景:還是動圖中的界面,點擊下面Mine切換到我的界面時,要更新UI,但我不想每次都重走fragment的生命週期,只讓它走一次,之後會通過控制顯示與隱藏來切換,並且實現數據的更新。
MainActivity.java主要代碼
private void showFragment(int position) { FragmentManager fm = getSupportFragmentManager(); FragmentTransation ft = fm.beginTransaction(); Fragment fragment = mFragmentList.get(position); //判斷當前展示的fragment是否爲空,不爲空,則隱藏 if (mCurrentShowFrag != null) { ft.hide(mCurrentShowFrag); } //首先判斷點擊的fragment是否被添加,如果沒有則添加 if (!fragment.isAdded()) { ft.add(R.id.main_framlayout, fragment); } else { if (fragment instanceof MineFragment) { //調用接口,然後在fragment中實現 againRequestCountListener.againRequestCount(); //不用接口也可以,最後會提到 //A a = new A(); //a.b(); } ft.show(fragment); } mCurrentShowFrag = fragment;//將show的fragment賦予mCurrentShowFrag ft.commit(); } //這是接口 public static AgainRequestCountListener againRequestCountListener; public static void setAgainRequestCountListener(AgainRequestCountListener againRequestCountListener) { MainActivity.againRequestCountListener = againRequestCountListener; } public interface AgainRequestCountListener { void againRequestCount(); }
MineFragment.java主要代碼
public class MineFragment extends Fragment implements MainActivity.AgainRequestCountListener { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_mine, container, false); MainActivity.setAgainRequestCountListener(this); checkNewVersion(); return view; } @Override public void againRequestCount() { //自己要做的操作 } }
其實第二種不用接口也可以,直接用普通的調用方法也行 像這樣:A a=new A(); a.b();