为时已晚,无法创建片段? [英] Too late to create Fragments?

查看:80
本文介绍了为时已晚,无法创建片段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发我的第一个Android应用程序.我只是来发现Fragments,我需要它们创建一个ViewPager来在我的活动之间创建良好的过渡,但是我担心实现这一点为时已晚.

I am working on my first Android application. I just came to discover Fragments and I need them to create a ViewPager to create nice transitions between my activities, but I fear that it's too late to implement that.

我必须将所有代码( MainActivity )放在MainFragment中吗?或者只是一些我不知道要保留在 MainActivity

I have to put all my code (MainActivity) in my MainFragment? Or just some pieces I don't know what I have to keep in my 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标签的应用

That's an App to read NFC tag

推荐答案

NFC读取框架(至少 newIntent 和启用前台分派)应在将Intent传递到Activity中时使用您的活动,然后可以将接收到的Intent数据传递给Fragment进行实际数据的处理.

The NFC reading Framework (at least newIntent and the enabling of foreground dispatch) should be in the Activity as the Intent is passed to your Activity, you could then pass the Intent data received to the Fragment for processing of the actual data.

还可以通过Activity中的 newIntent 来提供更好的用户体验,您真的不希望操作系统在您的应用上启动另一个屏幕,因为用户将NFC卡带入了范围内.使用NFC无法执行任何操作的片段.因此,应用程序始终应该注册以处理所有屏幕上所需的卡片类型,然后在活动中做出决定,确定它是否总是要对NFC数据执行某项操作,或者是否有条件地取决于活动的片段(该选择可以是在活动"或每个片段"中创建).在活动"中完成这一部分意味着减少了将代码复制和粘贴到每个Fragment的次数.

Also handling the newIntent in the Activity provides a better user experience, you don't really want the OS launching another screen over your app because the user brought the NFC card in to range while in a Fragment that is not doing anything with NFC. So the App always should register to handle the type of cards you want in all screens and then make a decision in the Activity if it is going to do something always with the NFC data or conditionally depending on what Fragment is active (that choice can be made in the Activity or Every Fragment). Doing that part in the Activity means less copy and paste of code to every Fragment.

onActivityResult 也是一样,最初在Activity中处理,然后根据需要传递给Fragments,具体取决于您要如何处理这些

The same goes for onActivityResult, handle initially in Activity and pass on as required to Fragments depending on how you want to handle these

这篇关于为时已晚,无法创建片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆