我在寫一個應用程序,它使用NFC讀取存儲在其上的一些數據。我的應用程序使用片段和片段不帶onNewIntent()方法。因爲我正在閱讀的數據是用我處理NFC相關操作的單獨類完成的,所以我需要做的唯一事情就是更新Fragment中的TextView。然而,這個實現也可以用來將新的Intent傳遞給片段。在片段中處理onNewIntent
這是我目前使用的接口。收到新Intent並與NFC相關的檢查成功後,我打電話給聽衆。這是主持Fragment的FragmentActivity。
public class Main extends FragmentActivity implements
ActionBar.OnNavigationListener {
private Bundle myBalanceBundle;
private NFC nfcObj;
private NewBalanceListener newBlanceListener;
@Override
public void onNewIntent(Intent intent) {
setIntent(intent);
}
@Override
protected void onResume() {
getNFCState();
super.onResume();
}
private void getNFCState() {
//Other NFC related codes
else if (nfc_state == NFC.NFC_STATE_ENABLED){
readNFCTag();
}
}
private void readNFCTag() {
//Other NFC related codes
if (getIntent().getAction().equals(NfcAdapter.ACTION_TECH_DISCOVERED)) {
nfcObj.setTag((Tag) getIntent().getParcelableExtra(
NfcAdapter.EXTRA_TAG));
nfcObj.readQuickBalance();
transitQuickReadFragment(nfcObj.getCurrentBalance());
}
}
private void transitQuickReadFragment(String balance) {
// Creates a balance bundle and calls to select MyBalance Fragment if it
// is not visible. Calls listener is it is already visible.
if (actionBar.getSelectedNavigationIndex() != 1) {
if (myBalanceBundle == null)
myBalanceBundle = new Bundle();
myBalanceBundle.putString(Keys.BALANCE.toString(), balance);
actionBar.setSelectedNavigationItem(1);
} else {
newBlanceListener.onNewBalanceRead(balance);
}
}
@Override
public boolean onNavigationItemSelected(int position, long id) {
// Other fragment related codes
fragment = new MyBalance();
fragment.setArguments(myBalanceBundle);
newBlanceListener = (NewBalanceListener) fragment;
// Other fragment related codes
}
// Interface callbacks. You can pass new Intent here if your application
// requires it.
public interface NewBalanceListener {
public void onNewBalanceRead(String newBalance);
}
}
這是應查看mybalance片段,其具有的TextView需要每當NFC讀取進行更新:
public class MyBalance extends Fragment implements NewBalanceListener {
private TextView mybalance_value;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Other onCreateView related code
Bundle bundle = this.getArguments();
if (bundle != null)
mybalance_value.setText(bundle.getString(Keys.BALANCE.toString(),
"0.00"));
else
mybalance_value.setText("0.00");
//Other onCreateView related code
}
@Override
public void onNewBalanceRead(String newBalance) {
mybalance_value.setText(newBalance);
}
}
此代碼完全像預期爲我的應用程序的工作,但我想知道是否有更好的從碎片處理新的意圖的方式?
結帳這個鏈接看起來類似於你的要求http://stackoverflow.com/questions/17144512/pass-intent-to-my-fragment?noredirect=1&lq=1 – 2016-07-20 08:44:56