【问题标题】:Show toast soon as activity is visible活动可见时立即显示 toast
【发布时间】:2018-12-30 07:00:33
【问题描述】:

每当活动对用户可见但消息根本不显示时,我都会尝试显示敬酒。

我有活动 X,它在某些时候调用:

    Intent t = new Intent(this, MainActivity.class);
    t.putExtra( "toast", getString(R.string.subscribingInBackground));
    t.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    startActivity(t);
    finish();

在 MainActivity 上,除了我还有很多其他的东西:

@Override
    public void onResume() {
        super.onResume();
        if (this.adView != null) {
            this.adView.resume();
        }


            String toast = getIntent().getStringExtra("toast");
            if (toast != null)
                Toast.makeText(this, toast, Toast.LENGTH_LONG).show();

    }

toast 始终为空

我做错了什么?

【问题讨论】:

  • 我已经通过调试检查了 toast 是否为空
  • 您没有调用 show() 函数 (Toast.makeText(...).show())。这不会使 toast 不为空,但仍然。
  • 我注意到我在 makeText 之后忘记了.show(),但由于toast 始终为空,所以还没有工作
  • 请尝试使用get string from xml as getResources().getString(R.string.subscribingInBackground);

标签: android android-intent activity-lifecycle android-toast


【解决方案1】:

您的FLAG_REORDER_TO_FRONT 表明您认为该活动已经存在。如果是这样,将使用onNewIntent() 调用该活动,并且传递给onNewIntent()Intent 将拥有您的额外功能。 getIntent() 返回最初用于创建活动的Intent

【讨论】:

  • 您的假设是正确的,活动已经存在。但你没有解释我怎样才能得到newIntent
  • @RafaelLima:你覆盖了onNewIntent()Intent 作为参数提供。
【解决方案2】:
use this code

package com.example.abc.introscreen;

import android.content.Intent;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent t = new Intent(this,MainActivity.class);
        t.putExtra( "toast", "Hello");
        startActivity(t);

        }

    @Override
    public void onResume() {

        String toast = getIntent().getStringExtra("toast");

        if (toast != null)
            Toast.makeText(this, toast, Toast.LENGTH_LONG).show();
        super.onResume();

    }


}




    enter code here

【讨论】:

    【解决方案3】:

    您可以覆盖onNewIntent() 以获取您在ActivityX 中使用的Intent 来启动MainActivity

    引用documentation 上的Activity

    请注意,getIntent() 仍然返回原始 Intent。您可以使用setIntent(Intent) 将其更新为这个新的 Intent。

    因此您可以按如下方式覆盖onNewIntent()

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }
    

    然后你的Toast就会显示出来。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-16
      • 1970-01-01
      • 2020-03-13
      • 1970-01-01
      • 1970-01-01
      • 2011-08-10
      相关资源
      最近更新 更多