android - 将toast从一个活动传递到另一个活动

时间:2017-12-18 02:06:53

标签: android android-intent android-toast

不确定这是否有效,但我正在尝试从CustomerCall活动向RiderHome活动发送Toast消息。

一旦驾驶员选择取消。需要将Toast发送到RiderHome活动,说“驱动程序已取消请求”

可以这样做吗?

CustomerCall

btnCancel = (Button)findViewById(R.id.btnDecline);
    btnCancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

                cancelBooking();
        }
    });

}

private void cancelBooking() {

    Intent intent = new Intent(getBaseContext(), RiderHome.class);
    String cancel = "cancel"
    intent.putExtra("cancel", cancel);
    startActivity(intent);

    Toast.makeText(CustomerCall.this, "The Driver has cancelled 
    the request", Toast.LENGTH_LONG).show();
}

RiderHome

public class RiderHome extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener {


   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_home);

   }

}

2 个答案:

答案 0 :(得分:1)

你可以这样做 - :

private void cancelBooking() {

    Intent intent = new Intent(getBaseContext(), RiderHome.class);
    String cancel = "cancel"
    intent.putExtra("user_cancelled",cancel);
    startActivity(intent);

    Toast.makeText(CustomerCall.this, "The Driver has cancelled 
    the request", Toast.LENGTH_LONG).show();
}

在此传递中,一个字符串值表示驱动程序取消了请求

并且在RiderHome Activity中,您可以通过 - :

检查您是否获得了该值
Intent intent=getIntent();
intent.getExtras();

if(intent.hasExtra("user_cancelled"))
{

    You can print your toast here.

}

答案 1 :(得分:-1)

而不是(Toast with activity - Toast的生命在活动结束时死亡)

Toast.makeText(CustomerCall.this, "The Driver has cancelled 
the request", Toast.LENGTH_LONG).show();

to(使用上下文!!它会存活)

Toast.makeText(getBaseContext(), "The Driver has cancelled 
the request", Toast.LENGTH_LONG).show();