如何通过 Intent 转移到 nex Activity

Posted

技术标签:

【中文标题】如何通过 Intent 转移到 nex Activity【英文标题】:How can I move to nex Activity through Intent 【发布时间】:2021-06-12 06:44:19 【问题描述】:

我正在尝试制作银行应用程序,并且正在尝试制作 Success Activity,当我尝试从 MainActivity.java 移动到 SuccessActivity.java 时,我得到一个空白页。

这是我的 MainActivity.java:

package com.example.bankapp.ui;


import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.bankapp.R;
import com.example.bankapp.data.AccountRepository;
import com.example.bankapp.databinding.ActivityMainBinding;
import com.example.bankapp.domain.BankAccount;
import com.example.bankapp.domain.SuccessPayment;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;

public class MainActivity extends AppCompatActivity 

    private ActivityMainBinding binding;
    private BankAccount bankAccount;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        bankAccount = new AccountRepository().getAccount();
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        bindBankDataToRadioButtons(bankAccount);
        bindBankDataToViews(bankAccount);
        binding.rbGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() 
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) 
                binding.bnpagar.setEnabled(true);
                if (checkedId == R.id.rbotraCantidad) 
                    binding.etnuevaCantidad.setVisibility(View.VISIBLE);
                    binding.ingreseCantidad.setVisibility(View.VISIBLE);
                 else 
                    binding.etnuevaCantidad.setVisibility(View.GONE);
                    binding.ingreseCantidad.setVisibility(View.GONE);
                
            
        );

        binding.bnpagar.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                double amountToPay = getAmountToPay();
                if (amountToPay == -1.0) 
                    showToastMessage(getString(R.string.err_cantidadIncorrecta));
                 else if (amountToPay <= bankAccount.getAccountBalance()) 
                    SuccessPayment successPayment = makePayment(amountToPay, bankAccount);
                    Intent intent = new Intent(getApplicationContext(), SuccessActivity.class);
                    intent.putExtra("SUCCESS_EXTRA", successPayment);
                    startActivity(intent);
                    finish();

                 else 
                    showToastMessage(getString(R.string.err_saldoInsuficiente));
                
            
        );
    




    private double getAmountToPay() 
        double amount;
        switch (binding.rbGroup.getCheckedRadioButtonId()) 
            case R.id.rbdeudaActual:
                amount = bankAccount.getCurrentDebt();
                break;
            case R.id.rbsinInteres:
                amount = bankAccount.getMinimumPaymentDue();
                break;
            case R.id.rbpagoMinimo:
                amount = bankAccount.getPaymentDue();
                break;
            default:
                amount = getAmountFromEditText(binding.etnuevaCantidad);
        
        return amount;
    

    private double getAmountFromEditText(EditText editText) 
        try 
            String text = editText.getText().toString();
            return Double.parseDouble(text);
         catch (NumberFormatException e) 
            return -1.0;
        
    

    private void bindBankDataToRadioButtons(BankAccount bankAccount) 
        binding.rbdeudaActual.setText(
                getString(R.string.label_deudaActual, bankAccount.getCurrentDebt())
        );
        binding.rbsinInteres.setText(
                getString(R.string.label_sinInteres, bankAccount.getMinimumPaymentDue())
        );
        binding.rbpagoMinimo.setText(
                getString(R.string.label_pagoMinimo, bankAccount.getPaymentDue())
        );
    

    private void bindBankDataToViews(BankAccount bankAccount) 
        binding.cardLayout.tvAccountName.setText(bankAccount.getAccountName());
        //El string label_peso_sign pide un número, por eso el método getString recibe
        //un segundo parámetro, que en este caso es el accountBalance.
        binding.cardLayout.tvAccountBalance.setText(getString(R.string.label_peso_sign, bankAccount.getAccountBalance()));
        binding.cardLayout.tvAccountNumber.setText(bankAccount.getAccountNumber());
        binding.cardLayout.tvCardName.setText(bankAccount.getCardName());
        binding.cardLayout.tvCardNumber.setText(bankAccount.getCardNumber());
        binding.cardLayout.tvCurrentDebtAmount.setText(getString(R.string.label_peso_sign, bankAccount.getCurrentDebt()));
        binding.cardLayout.tvClosingDateBalanceAmount.setText(getString(R.string.label_peso_sign, bankAccount.getClosingDateBalance()));
        binding.cardLayout.tvPaymentDate.setText(bankAccount.getPaymentDueDate());
    


    private void showToastMessage(String message) 
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    

    private SuccessPayment makePayment(double amount, BankAccount bankAccount) 
        String date = new SimpleDateFormat(
                "dd 'de' MMMM 'de' yyyy",
                new Locale("es", "MX")
        ).format(new Date(Calendar.getInstance().getTimeInMillis()));
        String referenceNumber = UUID.randomUUID().toString().substring(0, 10);
        // amount -> double
        // date -> String
        // referenceNumber -> String
        // bankAccount -> BankAccount
        return new SuccessPayment(
                amount,
                date,
                referenceNumber,
                bankAccount
        );
    



这是我的 Activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:orientation="vertical">

    <include
        android:id="@+id/cardLayout"
        layout="@layout/card_layout" />

    <RadioGroup
        android:layout_
        android:layout_
        android:id="@+id/rbGroup">

        <RadioButton
            android:id="@+id/rbdeudaActual"
            android:layout_
            android:layout_
            android:layout_marginTop="10dp"
            android:layout_marginStart="10dp"
            android:text="@string/label_deudaActual" />

        <RadioButton
            android:id="@+id/rbpagoMinimo"
            android:layout_
            android:layout_
            android:layout_marginTop="10dp"
            android:layout_marginStart="10dp"
            android:text="@string/label_pagoMinimo" />

        <RadioButton
            android:id="@+id/rbsinInteres"
            android:layout_
            android:layout_
            android:layout_marginStart="10dp"
            android:layout_marginTop="10dp"
            android:text="@string/label_sinInteres" />

        <RadioButton
            android:id="@+id/rbotraCantidad"
            android:layout_
            android:layout_
            android:layout_marginStart="10dp"
            android:layout_marginTop="10dp"
            android:text="@string/label_otraCantidad" />
        <TextView
            android:layout_
            android:layout_
            android:textColor="@color/black"
            android:layout_marginTop="10dp"
            android:layout_marginStart="5dp"
            android:text="@string/label_nuevaCantidad"
            android:id="@+id/ingreseCantidad"/>

        <EditText
            android:id="@+id/etnuevaCantidad"
            android:layout_marginStart="5dp"
            android:layout_
            android:layout_
            android:inputType="number"
            android:imeOptions="actionDone">
        </EditText>

    </RadioGroup>

    <Space
        android:id="@+id/espacio"
        android:layout_
        android:layout_
        android:layout_weight="1" />
    <Button
        android:id="@+id/bnpagar"
        android:layout_
        android:layout_
        android:text="@string/label_pagar" />

</LinearLayout>

这是我的成功Activity.java:

package com.example.bankapp.ui;

import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.bankapp.R;
import com.example.bankapp.databinding.ActivitySuccessBinding;
import com.example.bankapp.domain.SuccessPayment;


public class SuccessActivity extends AppCompatActivity 

    private ActivitySuccessBinding binding;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) 
        binding = ActivitySuccessBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_success);
        SuccessPayment payment = getIntent().getParcelableExtra("SUCCESS_EXTRA");
    

这是我的 ActivitySuccess.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView2"
        android:layout_
        android:layout_
        android:contentDescription="@string/label_current_debt"
        tools:srcCompat="@tools:sample/avatars" />
</LinearLayout>

这是我的 Android 清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bankapp">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.BankApp">

        <activity android:name=".ui.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".ui.SuccessActivity" > </activity>




</application>

</manifest>

【问题讨论】:

您检查过您的 logcat 是否有任何错误? 【参考方案1】:

首先我不知道你为什么使用这种方法来膨胀布局,而不是仅仅使用 setContentview 方法并将活动作为上下文添加到相应的 xml 中。

第二次尝试在你的 onCreate 方法中保持对 super.onCreate 的调用

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) 
     super.onCreate(savedInstanceState);        

    binding = ActivitySuccessBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());
    setContentView(R.layout.activity_success);
    SuccessPayment payment = getIntent().getParcelableExtra("SUCCESS_EXTRA");

【讨论】:

以上是关于如何通过 Intent 转移到 nex Activity的主要内容,如果未能解决你的问题,请参考以下文章

intent用法

Android项目实战(四十):Andoird 7.0+ 安装APK适配

C++学习(二九三)Android的Intent

如何通过 Intent 从 SD 卡打开 PDF

android 中如何使用intent通过传递变量传递数据

如何通过 Intent 向现有联系人添加电话号码?