创建碎片为时已晚



我正在开发我的第一个Android应用程序。我刚刚发现了Fragments,我需要它们来创建ViewPager,以在我的活动之间创建良好的转换,但我担心现在实现它已经太晚了。

我必须把我所有的代码(MainActivity(放在我的MainFragment中?或者只是一些我不知道我必须保存在MainActivity中的片段

这是我的代码

public class MainActivity extends FragmentActivity {
ObjectAnimator anim;
ObjectAnimator anim2;
private int display, result, detect = 0;
private NfcAdapter nfcAdapter;
private ImageButton nfcButton;
private PendingIntent pendingIntent;
private ImageButton qrButton;
private TextView text;
private SlidrInterface slidr;
private ImageButton webButton;
float x1, x2, y1, y2;
String link = null;
public final int CUSTOMIZED_REQUEST_CODE = 0x0000ffff;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
slidr = Slidr.attach(this);
setDetect(1);
setContentView((int) R.layout.activity_main);
this.text = (TextView) findViewById(R.id.text);
this.nfcAdapter = NfcAdapter.getDefaultAdapter(this);
this.nfcButton = (ImageButton) findViewById(R.id.nfc_button);
this.anim = ObjectAnimator.ofFloat(this.nfcButton, "scaleX", new float[]{0.9f});
this.anim2 = ObjectAnimator.ofFloat(this.nfcButton, "scaleY", new float[]{0.9f});
IntentIntegrator integrator = new IntentIntegrator(this);
this.nfcButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setDisplay(1);
manageBlinkEffect();
}
});
this.pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {                                   // RESULTAT DU SCAN QR CODE
if (requestCode != CUSTOMIZED_REQUEST_CODE && requestCode != IntentIntegrator.REQUEST_CODE) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
switch (requestCode) {
case CUSTOMIZED_REQUEST_CODE: {
Toast.makeText(this, "REQUEST_CODE = " + requestCode, Toast.LENGTH_LONG).show();
break;
}
default:
break;
}
IntentResult result = IntentIntegrator.parseActivityResult(resultCode, data);
if (result.getContents() != null) {
Log.d("MainActivity", "Scanned");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Résultat du scan :");
if (URLUtil.isValidUrl(result.getContents())) {                                                                      // si url...
builder.setNeutralButton("Visiter", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setPositiveButton("Fermer", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { }
});
builder.setNegativeButton("Copier", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Texte copié", result.getContents());
clipboard.setPrimaryClip(clip);
}
});
} else {                                                                                                             // si plain text...
builder.setNeutralButton("Copier", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Texte copié", result.getContents());
clipboard.setPrimaryClip(clip);
}
});
builder.setPositiveButton("Fermer", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { }
});
}
builder.setMessage(result.getContents().toString());
builder.create().show();
}
}

public void manageBlinkEffect() {                                                                           // ANIMATION DU LOGO SENZU SUITE A UN CLIC
anim.setDuration(1000);
anim.setRepeatMode(ValueAnimator.REVERSE);
anim.setRepeatCount(9);
anim.start();
anim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationCancel(animation);
if (getRes() != 1){
Animation shake = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.shake);
Toast.makeText(getApplicationContext(), "Aucun badge n'a été détécté !", Toast.LENGTH_SHORT).show();
nfcButton.startAnimation(shake);
}
}
});
anim2.setDuration(1000);
anim2.setRepeatMode(ValueAnimator.REVERSE);
anim2.setRepeatCount(9);
anim2.start();
}
public void onResume() {
super.onResume();
Intent intent = getIntent(); // Recuperer l'intent actuel
NdefMessage[] msgs;
if (getDetect() == 1 && (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction()))) { // si l'application a ete lancee via une detection NFC du device  (ACTION_NDEF_DISCOVERED, voir AndroidManifest)
Parcelable[] rawMessages =
intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES");
if (rawMessages != null) { // si NDEF dans le scan
setDisplay(1);
resolveIntent(intent); // parser le scan NFC
}  else {
byte[] empty = new byte[0];
byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
byte[] payload = NdefMessageParser.dumpTagData(tag).getBytes();
NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
msgs = new NdefMessage[] {msg};
setDetect(0);
getResult(msgs);
}
}
NfcAdapter nfcAdapter2 = this.nfcAdapter;
if (nfcAdapter2 != null) {
if (!nfcAdapter2.isEnabled()) {
showWirelessSettings();
}
this.nfcAdapter.enableForegroundDispatch(this, this.pendingIntent, (IntentFilter[]) null, (String[][]) null);
}
}
private void showWirelessSettings() {
Toast.makeText(this, "Veuillez activer le service NFC", Toast.LENGTH_SHORT).show();
startActivity(new Intent("android.settings.WIRELESS_SETTINGS"));
}
public void onPause() {
setDetect(0);
super.onPause();
}

public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
if (getDetect() != 1) {
resolveIntent(intent);
}
}
private void resolveIntent(Intent intent) {                                                                 // DETECTION NFC ET PARSING NDEF
NdefMessage[] msgs;
String action = intent.getAction();
Log.d("Infos", getIntent().toString());
Log.d("Infos", "display = " + display);
if (getDisplay() != 1) {
Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
nfcButton.startAnimation(shake);
Toast.makeText(this, "Veuillez lancer un scan", Toast.LENGTH_LONG).show();
return;
}
else if ("android.nfc.action.TAG_DISCOVERED".equals(action) || "android.nfc.action.TECH_DISCOVERED".equals(action) || "android.nfc.action.NDEF_DISCOVERED".equals(action)) {
setRes(1);
Parcelable[] rawMsgs = intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES");
if (rawMsgs != null) {
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];
}
} else {
byte[] empty = new byte[0];
byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
byte[] payload = NdefMessageParser.dumpTagData(tag).getBytes();
NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
msgs = new NdefMessage[] {msg};
}
if (getDisplay() == 1) {
getResult(msgs);
}
}
}
private void getResult(NdefMessage[] msgs) {                                                            // MODAL AVEC RESULTAT DU SCAN NFC
if (msgs != null && msgs.length != 0) {
final StringBuilder tmp_builder = new StringBuilder();
List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]);
int size = records.size();
for (int i = 0; i < size; i++) {
tmp_builder.append(records.get(i).str());
tmp_builder.append("n");
}
System.out.println(tmp_builder.toString());
this.anim.cancel();
this.anim2.cancel();
setDisplay(0);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Resultat du scan :");
builder.setNeutralButton("Visiter", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
/*  Intent i = new Intent(MainActivity.this, RightActivity.class);
link = tmp_builder.toString();
i.putExtra("url", link);
startActivity(i);*/
}
});
builder.setNegativeButton("Copier", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Texte copié", link);
clipboard.setPrimaryClip(clip);
}
});
builder.setPositiveButton("Fermer", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {}
});
builder.setMessage(tmp_builder.toString());
builder.create().show();
}
}

这是一个读取NFC标签的应用程序

当意向传递给您的活动时,NFC读取框架(至少newIntent和前台调度的启用(应该在活动中,然后您可以将接收到的意向数据传递给Fragment以处理实际数据。

此外,在"活动"中处理newIntent可以提供更好的用户体验,您并不真的希望操作系统在您的应用程序上启动另一个屏幕,因为用户在不使用NFC的片段中将NFC卡带入范围。因此,应用程序应始终进行注册,以在所有屏幕中处理您想要的卡类型,然后在"活动"中决定是否始终使用NFC数据或根据激活的片段进行有条件的操作(可以在"活动或每个片段"中进行选择(。在"活动"中完成这一部分意味着减少对每个片段的代码复制和粘贴。

onActivityResult也是如此,最初在"活动"中处理,然后根据需要传递给碎片,具体取决于您希望如何处理这些

最新更新