吐司没有显示

时间:2015-06-01 07:02:09

标签: android toast

我想在actionItem()函数里面显示Toast。但它现在没有显示Toast。

如果我打电话

Context context = getApplicationContext();

在actionItem()之前,应用程序崩溃了。

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;


public class ShowWebViewActivity extends ActionBarActivity {

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

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_show_web_view, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        // int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        //        if (id == R.id.action_settings) {
        //            return true;
        //        }

        switch (item.getItemId()) {
            case R.id.action_settings:
                actionItem();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }

    }
// Context context = getApplicationContext() makes app to crash why??
    public void actionItem(){
// Toast function should call here. But not working
        Context context = getApplicationContext();
        Toast.makeText(context, "Action Setting Selected", Toast.LENGTH_LONG);
    }


}

6 个答案:

答案 0 :(得分:5)

应该是,

Toast.makeText(context, "Action Setting Selected", Toast.LENGTH_LONG).show();

答案 1 :(得分:4)

您的代码中缺少

Show()。请参考我的代码:

Toast.makeText(context, "Action Setting Selected", Toast.LENGTH_LONG).show();

答案 2 :(得分:3)

Toast.makeText(context, "Action Setting Selected", Toast.LENGTH_LONG);  

应该是:

Toast.makeText(context, "Action Setting Selected", Toast.LENGTH_LONG).show();  

你也会收到一个IDE警告

答案 3 :(得分:1)

缺少

show()使用以下代码

public void actionItem(){
// Toast function should call here. But not working
    Context context = getApplicationContext();
    Toast.makeText(context, "Action Setting Selected", Toast.LENGTH_LONG).show();
 }

答案 4 :(得分:1)

您错过了show()

Toast.makeText(context, "Action Setting Selected", Toast.LENGTH_LONG);

它应该是:

Toast.makeText(context, "Action Setting Selected", Toast.LENGTH_LONG).show();

答案 5 :(得分:0)

您错过了show()功能。

Toast.makeText(context, "Action Setting Selected", Toast.LENGTH_LONG).show();