Question

How can I make toast onItemClickListener that use String for message? I am making app that support multiple languages, and I want to show toast on different languages. For that I need to use Strings. So How can I get string for toast and show it?

list.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,
             int position, long id) {
            switch (position) {
            case 0:
                showtost();
                break;
              }
            return true;

I tried with some methods but it didn't work.

private void showtost() {
            // TODO Auto-generated method stub
            Toast.makeText(this,
                    .getResources().getString(R.string.alarm),
                    Toast.LENGTH_SHORT).show();

            return;
            }

The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (new AdapterView.OnItemLongClickListener(){}, 

String, int)

Was it helpful?

Solution

You need to change this to be a reference to the context, e.g. if in an activity use:

MyActivity.this

Or inside a fragment use:

getActivity()

Then the example you posted will work.

OTHER TIPS

Yes, you can do it like this:

Toast.makeText(context, R.string.hello_world, Toast.LENGTH_LONG).show();

here hello_world can be replaced with your String ID from the strings.xml.

you have to mention getActivity() over there.

private void showtost() {
            // TODO Auto-generated method stub
            Toast.makeText(getActivity(),
                    .getResources().getString(R.string.alarm),
                    Toast.LENGTH_SHORT).show();

            return;
            }

for multilanguage support; you can define strings.xml in values folder and you can add different folder name as values-tr(this is for turkish). and then you can set your string like this:

String my_toast_string=context.getString(R.string.my_string);

then you can put your toast like this:

Toast.makeText(getActivity(),my_toast_string, Toast.LENGTH_SHORT).show();

You can get the string with;

String x= getResources().getString(R.string.language);

and you can make folders in res with language settings and change your string file in there:

folder res/values-cn you make a string file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="language">cn</string>
</resources>

and if you make a folder res/values-en you make a string file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="language">en</string>
</resources>

and now if you set your Item on a clocklistener and add folowing code:

Toast.makeText(context, language, Toast.LENGTH_SHORT).show();

the output is "cn" if your language device is chinese and "en" if english

i suggest to make a default value in the folder res/values

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top