【发布时间】:2013-03-05 14:41:00
【问题描述】:
我正在编写一个使用 NFC 读取存储在其上的一些数据的应用程序。我的应用程序使用 Fragments 并且 Fragment 不附带 onNewIntent() 方法。因为,我正在读取的数据是通过处理 NFC 相关操作的单独类完成的,所以我唯一需要做的就是更新 Fragment 中的 TextView。但是,此实现也可用于将新 Intent 传递给 Fragment。
这是我当前使用接口的实现。在收到新的 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 Fragment,其中包含在读取 NFC 时需要更新的 TextView:
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);
}
}
此代码的工作方式与我的应用程序的预期完全一样,但我想知道是否有更好的方法来处理来自 Fragments 的新 Intent?
【问题讨论】:
-
结帐此链接看起来与您的要求相似stackoverflow.com/questions/17144512/…
标签: android android-intent android-fragments