在工作中我們經常會遇到Activity和Fragment交互,傳遞數據是比較容易實現,但是要用到Activity和Fragment之間互相改變彼此的UI,網上關於這個問題的解決方法還是很少的,我也沒遇到合適的解決方案,自己在前人的基礎上研究後創造了一種方法。使Activity和Fragment共享一個Handler,然後發送消息通知彼此更新。別的也不多說了,例子代碼如下,
這是Activity的代碼:
package com.example.fragmentandactivity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.FragmentActivity; import android.view.KeyEvent; import android.widget.Toast; public class MainActivity extends FragmentActivity { private Handler mHandler; private long lastPressBack; private boolean isFirstPressBack = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_content, new HomeFragment()) .commit(); } public boolean onKeyDown(int keyCode, KeyEvent event) { super.onKeyDown(keyCode, event); if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { if(HomeFragment.changeText){ Message msg = mHandler.obtainMessage(); msg.what =0; mHandler.sendMessage(msg); HomeFragment.changeText=false; return false; } if (!isFirstPressBack) { if (System.currentTimeMillis() - lastPressBack > 2 * 1000) { lastPressBack = System.currentTimeMillis(); } else { finish(); } } lastPressBack = System.currentTimeMillis(); Toast.makeText(this,getString(R.string.exit_app),Toast.LENGTH_SHORT).show(); isFirstPressBack = false; return false; } return false; } public void setHandler(Handler handler) { mHandler = handler; } }
這是Fragment的代碼:
package com.example.fragmentandactivity; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class HomeFragment extends Fragment{ private TextView text; private MainActivity mActivity; public static boolean changeText=true; Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: text.setText(ChangedFragment); break; } } }; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.home_fragment, null); text=(TextView)view.findViewById(R.id.text); return view; } public void onAttach(Activity activity) { super.onAttach(activity); mActivity = (MainActivity) activity; mActivity.setHandler(handler); } public void onDestroy(){ super.onDestroy(); changeText=true; } }