Android 在 Fragment 中使用 Toast

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10770055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:53:54  来源:igfitidea点击:

Use Toast inside Fragment

androidandroid-fragmentsandroid-activitytoast

提问by mammadalius

I'm trying to show a Toast Message when user click on a Button inside a Fragment. The problem is I cannot access the activity to show the Toast on it.

当用户单击片段内的按钮时,我试图显示 Toast 消息。问题是我无法访问该活动以在其上显示 Toast。

Here's the source of Fragment:

以下是来源Fragment

    public class FrgTimes extends Fragment
    {
        ScrollView sv;
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) 
        {
            if (container == null) { return null; }

            sv = (ScrollView)inflater.inflate(R.layout.frg_times, container, false);

            btnTime1.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {

            //******  HERE's the PROBLEM  ********
            Toast.makeText(<The Activity>, "Please long press the key", Toast.LENGTH_LONG );

            }});

            return sv;
        }

and Here's what I've been tried.

这是我尝试过的。

Toast.makeText( getActivity()  , ...
Toast.makeText( getView().getContext()  , ...
Toast.makeText( getActivity().getApplicationContext()  , ...
Toast.makeText( sv.getContext()  , ...
Toast.makeText( sv.getRootView().getContext()  , ...

In Debug I can see that all of these codes run without any exception but no TOASTbeing displayed.

在调试中,我可以看到所有这些代码都运行无异常但没有TOAST显示。

回答by CommonsWare

You are not calling show()on the Toastyou are creating with makeText().

你是不是叫show()Toast你与创造makeText()

回答by user2564789

As stated by alfo888_ibg:

正如 alfo888_ibg 所述:

@Override
public void onClick(View arg0) {
   Toast.makeText(activity,"Text!",Toast.LENGTH_SHORT).show();
}

Just do:

做就是了:

    Toast.makeText(getActivity(),"Text!",Toast.LENGTH_SHORT).show();

this worked for me.

这对我有用。

回答by alfo888_ibg

To help another people with my same problem, the complete answer to Use Toast inside Fragment is:

为了帮助遇到同样问题的其他人,在 Fragment 中使用 Toast 的完整答案是:

Activity activity = getActivity();

@Override
public void onClick(View arg0) {

    Toast.makeText(activity,"Text!",Toast.LENGTH_SHORT).show();
}

回答by Sindri Tór

When making a toast in fragment do as following:

在片段中进行吐司时,请执行以下操作:

Toast.makeText(getActivity(),"Message", Toast.LENGTH_SHORT).show();

Toast.makeText(getActivity(),"Message", Toast.LENGTH_SHORT).show();

When class is extending fragment it is necessary to use getActivity()since fragment is a subclassof activity.

当类扩展片段时,有必要使用getActivity()因为片段是活动的子类

Cheerse

干酪

回答by andy bit1

You can get the current activity with getActivity()

您可以使用 getActivity() 获取当前活动

Toast.makeText(getActivity(),"Toast your message" ,Toast.LENGTH_SHORT).show();

回答by Ramesh

Making a Toast inside Fragment

在 Fragment 中制作吐司

 Toast.makeText(getActivity(), "Your Text Here!", Toast.LENGTH_SHORT).show();

OR

或者

    Activity activityObj = this.getActivity();

    Toast.makeText(activityObj, "Your Text Here!", Toast.LENGTH_SHORT).show();

OR

或者

Toast.makeText(this, "Your Text Here!", Toast.LENGTH_SHORT).show();

回答by Lakshan Vithana

When calling Toast inside android fragment:

在android片段中调用Toast时:

1. Activity mActivity=this.getActivity();  

2. Toast.makeText(mActivity,"Text you want to display",Toast.LENGTH_SHORT).show();

This works for me.

这对我有用。

回答by vaibhav3027

user2564789 said it right
But you can also use thisin the place of getActivity()
which will make your toast look like this

user2564789 说得对
但是你也可以用thisin getActivity()
which will make your toast like this


     Toast.makeText(this,"Message",Toast.LENGTH_SHORT).show();
    

回答by Khemraj

Unique Approach

独特的方法

(Will work for Dialog, Fragment, Even Util class etc...)

(适用于 Dialog、Fragment、Even Util 类等...)

ApplicationContext.getInstance().toast("I am toast");

ApplicationContext.getInstance().toast("I am toast");

Add below code in Application class accordingly.

相应地在 Application 类中添加以下代码。

public class ApplicationContext extends Application {

private static ApplicationContext instance;

@Override
public void onCreate() {
    super.onCreate();
    instance = this;
}

public static void toast(String message) {
    Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
}
}

回答by Alatey

A simple [Fragment] subclass.
Kotlin!
contextA - is a parent (main) Activity. Set it on create object.

一个简单的 [Fragment] 子类。
科特林!
contextA - 是父(主要)活动。在创建对象上设置它。

class Start(contextA: Context) : Fragment() {

var contextB: Context = contextA;

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    val fl = inflater.inflate(R.layout.fragment_start, container, false)

    // only thet variant is worked on me
    fl.button.setOnClickListener { view -> openPogodaUrl(view) }

    return fl;
}

fun openPogodaUrl(view: View) {        
    try {
        pogoda.webViewClient = object : WebViewClient() { // pogoda - is a WebView
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                view?.loadUrl(url)
                return true
            }
        }
        pogoda.loadUrl("http://exemple.com/app_vidgets/pogoda.html");
    }
    catch (e: Exception)
    {
        Toast.makeText(contextB, e.toString(), Toast.LENGTH_LONG).show();
    }
}

}

}