- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有两个 Activity A Activity 和B Activity ,在B Activity 内部有一个 fragment ,我在其中填充了一个列表BlogRecycleadapter 类中的项目。
当互联网不可用时,在 B Activity 中,它显示“检查互联网”,但是当我按后退按钮并移至 A Activity 时,仍然会出现 toast 消息.
如何隐藏 Toast 消息,使其不出现在第一个 Activity (即 A Activity )上?
我的RecycleViewAdapter
类是
BlogRecyclerAdapter.java
package com.nepalpolice.cdp;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import de.hdodenhof.circleimageview.CircleImageView;
import static com.android.volley.VolleyLog.TAG;
import static com.nepalpolice.cdp.webfaq.isNetworkStatusAvialable;
public class BlogRecyclerAdapter extends RecyclerView.Adapter<BlogRecyclerAdapter.ViewHolder> {
public List<BlogPost> blog_list;
public Context context;
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth firebaseAuth;
private PopupWindow popWindow;
public BlogRecyclerAdapter(List<BlogPost> blog_list){
this.blog_list = blog_list;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.blog_list_item, parent, false);
context = parent.getContext();
firebaseFirestore = FirebaseFirestore.getInstance();
firebaseAuth = FirebaseAuth.getInstance();
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.setIsRecyclable(false);
final String blogPostId = blog_list.get(position).BlogPostId;
final String currentUserId = firebaseAuth.getCurrentUser().getUid();
String desc_data = blog_list.get(position).getDesc();
holder.setDescText(desc_data);
String image_url = blog_list.get(position).getImage_url();
String thumbUri = blog_list.get(position).getImage_thumb();
holder.setBlogImage(image_url, thumbUri);
String user_id = blog_list.get(position).getUser_id();
//User Data will be retrieved here...
firebaseFirestore.collection("Users").document(user_id).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
String userName = task.getResult().getString("name");
String userImage = task.getResult().getString("image");
holder.setUserData(userName, userImage);
} else {
//Firebase Exception
}
}
});
try {
long millisecond = blog_list.get(position).getTimestamp().getTime();
String dateString = DateFormat.format("MM/dd/yyyy", new Date(millisecond)).toString();
holder.setTime(dateString);
} catch (Exception e) {
Toast.makeText(context, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
//Get Likes Count
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").addSnapshotListener(((Main2Activity) context),new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (e!=null) {
Log.w(TAG, "listening failed",e);
return;
}
if(!documentSnapshots.isEmpty()){
int count = documentSnapshots.size();
holder.updateLikesCount(count);
} else {
holder.updateLikesCount(0);
}
}
});
if (InternetStatus.getInstance(holder.blogLikeBtn.getContext()).isOnline()) {
//Get Likes
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).addSnapshotListener(((Main2Activity) context), new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {
if (e != null) {
Log.w(TAG, "listening failed", e);
return;
}
if (documentSnapshot.exists()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.blogLikeBtn.setImageDrawable(context.getDrawable(R.mipmap.action_like_accent));
} else {
holder.blogLikeBtn.setImageDrawable(context.getResources().getDrawable(R.mipmap.action_like_accent));
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.blogLikeBtn.setImageDrawable(context.getDrawable(R.mipmap.action_like_gray));
} else {
holder.blogLikeBtn.setImageDrawable(context.getResources().getDrawable(R.mipmap.action_like_gray));
}
}
}
});
}else{
Toast.makeText(context, "Check Internet", Toast.LENGTH_SHORT).show();
}
//Likes Feature
if (InternetStatus.getInstance(holder.blogLikeBtn.getContext()).isOnline()) {
holder.blogLikeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(!task.getResult().exists()){
Map<String, Object> likesMap = new HashMap<>();
likesMap.put("timestamp", FieldValue.serverTimestamp());
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).set(likesMap);
} else {
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).delete();
}
}
});
}
});
}else{
Toast.makeText(context, "Check Internet", Toast.LENGTH_SHORT).show();
}
if (InternetStatus.getInstance(holder.blogCommentBtn.getContext()).isOnline()) {
holder.blogCommentBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent commentIntent = new Intent(context, CommentsActivity.class);
context.startActivity(commentIntent);
}
});
}else{
Toast.makeText(context, "Check Internet", Toast.LENGTH_SHORT).show();
}
}
@Override
public int getItemCount() {
return blog_list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private View mView;
private TextView descView;
private ImageView blogImageView;
private TextView blogDate;
private TextView blogUserName;
private CircleImageView blogUserImage;
private ImageView blogLikeBtn;
private TextView blogLikeCount;
private ImageView blogCommentBtn;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
blogLikeBtn = mView.findViewById(R.id.blog_like_btn);
blogCommentBtn = mView.findViewById(R.id.blog_comment_icon);
}
public void setDescText(String descText){
descView = mView.findViewById(R.id.blog_desc);
descView.setText(descText);
}
public void setBlogImage(String downloadUri, String thumbUri){
blogImageView = mView.findViewById(R.id.blog_image);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.image_placeholder);
if (!((Activity) context).isFinishing()) {
Glide.with(context).applyDefaultRequestOptions(requestOptions).load(downloadUri).thumbnail(
Glide.with(context).load(thumbUri)
).into(blogImageView);
}
}
public void setTime(String date) {
blogDate = mView.findViewById(R.id.blog_date);
blogDate.setText(date);
}
public void setUserData(String name, String image) {
blogUserImage = mView.findViewById(R.id.blog_user_image);
blogUserName = mView.findViewById(R.id.blog_user_name);
blogUserName.setText(name);
RequestOptions placeholderOption = new RequestOptions();
placeholderOption.placeholder(R.drawable.profile_placeholder);
if (!((Activity) context).isFinishing()) {
Glide.with(context).applyDefaultRequestOptions(placeholderOption).load(image).into(blogUserImage);
}
}
public void updateLikesCount(int count){
blogLikeCount = mView.findViewById(R.id.blog_like_count);
blogLikeCount.setText(count + " Likes");
}
}
}
我的 MainActivity 类是
package com.nepalpolice.cdp;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
final Context context = this;
private boolean exit = false;
Dialog dialog;
private Menu mymenu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Fragment fragment = new main();
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
//Create Dialog
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
mymenu = menu;
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_refresh:
Intent intent = new Intent(MainActivity.this, UpdateService.class);
startService(intent);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageView iv = (ImageView)inflater.inflate(R.layout.iv_refresh, null);
Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotate_refresh);
rotation.setRepeatCount(Animation.INFINITE);
iv.startAnimation(rotation);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
item.setActionView(iv);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
new UpdateTask(this).execute();
}
return true;
}
return super.onOptionsItemSelected(item);
}
public void resetUpdating()
{
// Get our refresh item from the menu
MenuItem m = mymenu.findItem(R.id.action_refresh);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if(m.getActionView()!=null)
{
// Remove the animation.
m.getActionView().clearAnimation();
m.setActionView(null);
}
}
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.store) {
String url = "https://play.google.com/store/apps/developer?id=Sagar%20Rawal&hl=en";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
} else if (id == R.id.contact) {
Intent activity_about = new Intent(this, profile.class);
startActivity(activity_about);
}
else if (id == R.id.tetris) {
Intent activity_about = new Intent(this, MenuActivity.class);
startActivity(activity_about);
}
else if (id == R.id.tictac) {
Intent activity_about = new Intent(this, MainMenuScreen.class);
startActivity(activity_about);
}
else if (id == R.id.home) {
main fragment = new main();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_frame, fragment, "Main");
fragmentTransaction.commit();
fragmentTransaction.addToBackStack(null);
}
else if (id == R.id.email) {
Intent activity_about = new Intent(this, Sendemail.class);
startActivity(activity_about);
} else if (id == R.id.call) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:+9779868336847"));
startActivity(intent);
} else if (id == R.id.share) {
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/pl" +
"ain");
String shareBodyText = "Your shearing message goes here";
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject/Title");
intent.putExtra(android.content.Intent.EXTRA_TEXT, shareBodyText);
startActivity(Intent.createChooser(intent, "Share Via"));
} else if (id == R.id.rate) {
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=com.nepalpolice.mnemonics&hl=en" + getPackageName())));
}
catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,
(Uri.parse("https://play.google.com/store/apps/details?id=com.faraksoch.sagar.eroutine&hl=en"))));
}
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void onBackPressed() {
if (exit)
new AlertDialog.Builder(this)
.setTitle("Really Exit?")
.setMessage("Are you sure you want to exit?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// MainActivity.super.onBackPressed();
finish();
moveTaskToBack(true);
}
}).create().show();
else {
FragmentManager fm = getSupportFragmentManager();
fm.popBackStack();
if (getSupportFragmentManager().getBackStackEntryCount() ==1) {
finish();
}
exit = true;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
exit = false;
}
}, 800);
}
}
}
提前致谢。
最佳答案
发生的情况是,您的 Activity 中有三个地方可以调用它:
InternetStatus.getInstance(holder.blogLikeBtn.getContext()).isOnline()
如果你没有网络,你会调用这行代码三次,并且会创建依次出现的三个toast;一个接一个:
Toast.makeText(context, "Check Internet", Toast.LENGTH_SHORT).show();
您应该尝试合并您的代码,以便 toast 只显示一次。考虑以下代码:
if (InternetStatus.getInstance(holder.blogLikeBtn.getContext()).isOnline()) {
//Get Likes
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).addSnapshotListener(((Main2Activity) context), new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {
if (e != null) {
Log.w(TAG, "listening failed", e);
return;
}
if (documentSnapshot.exists()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.blogLikeBtn.setImageDrawable(context.getDrawable(R.mipmap.action_like_accent));
} else {
holder.blogLikeBtn.setImageDrawable(context.getResources().getDrawable(R.mipmap.action_like_accent));
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.blogLikeBtn.setImageDrawable(context.getDrawable(R.mipmap.action_like_gray));
} else {
holder.blogLikeBtn.setImageDrawable(context.getResources().getDrawable(R.mipmap.action_like_gray));
}
}
}
});
holder.blogLikeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(!task.getResult().exists()){
Map<String, Object> likesMap = new HashMap<>();
likesMap.put("timestamp", FieldValue.serverTimestamp());
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).set(likesMap);
} else {
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).delete();
}
}
});
}
});
holder.blogCommentBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent commentIntent = new Intent(context, CommentsActivity.class);
context.startActivity(commentIntent);
}
});
}else{
Toast.makeText(context, "Check Internet", Toast.LENGTH_SHORT).show();
}
}
关于java - 如何隐藏Toast消息的显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49519211/
这个问题在这里已经有了答案: How to prevent Multiple Toast Overlaps (8 个答案) 关闭 6 年前。 我有很多按钮。点击它们中的每一个,我都会显示一个 toa
我想为 Windows Phone 8.1 开发一个包含本地“通知”的通用应用程序。 我想要做的是在 toast 控件的扭结中向用户显示所有消息(错误、信息、警告)。 一切都在本地完成,无需通过标准通
有没有办法在 ionic 2 toast 中设置文本消息的样式? 我试过这个: let toast = Toast.create({ message: "Some text on
我有一个附加到按钮的函数,按下该按钮将从数组列表中删除一个项目,然后显示一个提示“项目已删除!”。如果我多次按下删除按钮,那么所有的 toast 都会显示出来,使其看起来像一个非常长的 toast 显
我在这里读到过此类问题,但答案似乎不起作用。 当用户点击按钮时,我会显示一个Toast。当用户连续点击按钮时,即使用户退出 Activity ,toast 也会一次又一次地显示。 toast 的长度很
我有几个可以在 fragment 上单击的按钮。单击每个按钮后,我会显示一条 Toast 消息,每个按钮都完全相同。因此,如果你一个接一个地按下 5 个不同的按钮,你将叠加 5 个 toast 消息,
我有几个 SeekBar 和 onSeekBarProgressStop(),我想显示一个 Toast 消息。 但是,如果在 SeekBar 上我快速执行操作,那么 UI 线程会以某种方式阻塞并且 T
有没有办法在 android 中获取与特定 android Toast 对象关联的消息? toast=Toast.makeText(getAppContext(), message, Toast.LE
我正在创建我的自定义 toast,主要是因为我将它放在 GridView 上并且需要对其宽度进行一些控制。但我真的很喜欢标准 toast 上的淡蓝色光环,并希望恢复它(或者至少让我的自定义 toast
我正在使用 Espresso 测试一个应用程序。我有一个问题,是否可以等到当前没有 toast 显示。我的应用程序中有很多不同的 toast,但是在测试时我遇到了问题,因为据我所知,焦点已经转移到 t
这可能是一个新手问题,但我想知道为什么我们必须使用静态方法 (makeText) 来创建 Toast 而不是构造函数。 为什么我们必须使用这个: makeText(Context context, C
我想显示的 toast 少于 Toast.LENGTH_SHORT,因为我觉得它需要大约 2 秒。我只想显示 toast 半秒。 Toast.LENGTH_SHORT 和 Toast.LENGTH_L
我想向用户显示自定义 toast。但 toast.getView() 和 toast.setView() 在 android studio 中已弃用。 这是我的代码: Toast toast = To
如何在 WorkManager 中显示 toast do work()? 当我尝试时,它会抛出 Caused by: java.lang.RuntimeException: Can't create
我写了一个代码,它工作正常,但没有任何 toast 出现。 Activity 2: package com.example.kiit.questionme2; import android.conte
我刚刚开始学习 Android。我使用我的 MIUI 10 设备进行调试。 我已经学习了非常基础的 App Lifecycle Program。问题是,我正在使用 toasts 来显示何时调用每个方法
我有一条消息在执行后不会消失。我猜这与它处于循环中有关,但我不确定。有人可以帮我弄清楚为什么 toast 消息没有区别吗? @Override public void onClick(View v)
是否可以让手机在您的程序中收到任何 toast 消息时振动?还是必须在每个 toast 上插入振动命令? 干杯。 最佳答案 将此类添加到您的代码中: import android.content.Co
有谁知道为什么这个程序不显示 toast 消息? public class Main extends Activity implements OnClickListener{ /** Called w
我在我的应用程序中打印 Toast 消息以显示通知,但我想知道Toast.LENGTH_LONG 和 Toast.LENGTH_SHORT。我可以使用哪些其他值。 谁能告诉我这两个变量的值是多少? 最
我是一名优秀的程序员,十分优秀!