【问题标题】:I have created a Fragment but don't know what to put inside我已经创建了一个片段,但不知道里面放什么
【发布时间】:2020-02-20 08:41:13
【问题描述】:

我已经实现了一个 NFC(扫描标签)应用程序,但现在我必须创建与我的 MainActivity 一起使用的片段,因为我想在未来实现 ViewPager

问题是我真的是初学者,我的代码变得太大而无法知道我必须在Activity 中输入什么以及我必须在Fragment 中输入什么

我试图理解的一周......

这是我的代码

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 ImageButton webButton;
    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();
        }
    }

我不知道我是否必须在我的 Fragment 中转移我的onResumeonPause

真的迷路了……

【问题讨论】:

  • 如果我理解正确,你试着学习如何使用 ViewPager,对吧?
  • 是的,我的目标是能够通过滑动手指来滑动活动,并有一个很好的过渡。显然,只有 ViewPager 可以做到这一点。
  • 这与我回答的stackoverflow.com/questions/60302675/… 几乎相同。如果没有额外的细节,很难说应该去哪里。您需要告诉我们所有 Fragment 将要做什么以及您希望每个 Fragment 如何响应正在呈现的 NFC 卡。
  • 我只是想用过渡滑动活动...我不知道为什么使用片段是这样做的唯一方法..
  • 目前您只有一个逻辑屏幕,即转换为 1 个片段,要在片段之间滑动,您需要超过 1 个片段。您需要让我们了解这些其他片段将要做什么以及如果提供 NFC 卡它们应该如何表现

标签: android android-fragments android-activity


【解决方案1】:

我认为您需要分阶段进行更改

我会了解 viewpager 和 Fragments 的工作原理,请先查看 https://abhiandroid.com/materialdesign/viewpager 获取教程

下一阶段是创建带有nfcButton 的第一个片段,但不要尝试将其与 NFC 东西链接起来。

这是因为处理 NFC 的起点必须在 Activity 中,因为您要重写 Activity 方法来执行此操作。

这基本上是将下面的代码放入片段的onViewCreated 方法中,并将与按钮相关的 xml 移动到片段的 xml 中

this.text = (TextView) findViewById(R.id.text);
        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});
        this.nfcButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // setDisplay should not be used at this stage
                // setDisplay(1);
                manageBlinkEffect();
            }
        });

还将方法manageBlinkEffect() 移动到片段中。

您现在也应该在getResult 中发表评论

this.anim.cancel();
this.anim2.cancel();

然后在主xml文件中设置你的viewpager

暂时注释掉这几行的原因是因为这些需要Activity到Fragment的通信,你应该明白https://developer.android.com/training/basics/fragments/communicating

下一阶段是将您的按钮连接回 setDetect 标志(替换注释掉的 setDetect() 行)

即带有 nfcButton 的 Fragment 必须告诉 MainActivity 开始处理它发送的任何 NFC 数据

然后getResult 中的 MainActivity 需要告诉带有 nfc 的 Fragment 停止动画它的 Button 如果带有按钮的 Fragment 正在显示并且 Fragment 已启动并正在运行。这次又是从 Activity 到 Fragment 的 Fragment 通信。

【讨论】:

  • 感谢您的帮助,我会阅读您的帖子几次!但是...为什么在两个活动之间获得过渡动画如此困难..?我很失望
  • 基本上,Activity 是 Android 中的独立功能单元,因为它们可以被深度链接并由操作系统转换,并回到更简单的时代以实现兼容性。在屏幕之间切换的方式有很多,操作系统不可能全部支持。
  • 好的,谢谢,关于我的片段,我唯一需要放在里面的是我的 nfc 按钮吗?扫描结果等呢?
  • 为简单起见,我将它留在了 AlertDialog 中,因为它会从 MainActivity 的屏幕上弹出。您可以通过多种不同方式显示 NFC 扫描的结果,包括在带有 nfcButton 的片段中显示它或任何其他片段或 Activity 但是这样做,您需要将该数据从 MainActivity 发送到您想要的其他片段/Activity显示它。在从 Fragment 启动的 AlertDialog 中显示它是浪费精力,因为它不会增加任何好处,因为对话框显示在屏幕的 viewpager 部分。
【解决方案2】:

首先你应该在 XML 中添加 ViewPager;

那么;

在你的活动中定义你的viewpager;

viewPager = findViewById(R.id.viewpager_main)

然后用它来设置viewpager

setupViewPager(viewPager)

像这样创建 setupViewPager 函数;

private fun setupViewPager(viewPager: ViewPager) {
        val adapter = ViewPagerAdapter(supportFragmentManager)
        adapter.addFragment(
            MainFragment(),
            "Fragment1"
        )
adapter.addFragment(
            SecondFragment(),
            "Fragment2"
        )
        viewPager.adapter = adapter}

片段的简单示例;

class MainFragment() : Fragment() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    retainInstance = true
}

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? =
    inflater.inflate(R.layout.info_screen_fragment, container, false)

/* info_screen_fragment is your xml for this fragment */
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

    }
}

我用 Kotlin 编写的代码。但我习惯了这个代码。简单而灵活。

【讨论】:

  • 谢谢!以及在哪里定义 XML ?我将所有代码复制/粘贴到我的片段中?
  • R.layout.info_screen_fragment 是您片段的 xml。检查 MainFragment()。您不需要复制/粘贴,只需更改 info_screen_fragments 而不是您的 xml。或者在 setupViewPager 函数中,你应该添加你的片段而不是 MainFragment
  • 所以我可以在不将所有代码转移到片段中的情况下实现 viewpager?
  • 如果你想将你的代码片段转移到片段,它不是必需的,但是你想将你的代码活动转移到片段,你必须转移你的代码。
  • 我想要的只是用滑动手指手势在我的活动之间滑动:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-14
  • 2020-08-18
相关资源
最近更新 更多