java
java

Reputation: 149

casting the string id to string object

I want implement the following code and I need a Persian string to display in the screen using the Toast class. But android studio does not accept. I have a Persian string in string.xml and I want display it using Toast object. I do not know what to do?

String name;
name = (String) findViewById(R.string.stringname);// does not accept

Also please say me, Which method I should use to display the content of the string.xml using Toast class

Upvotes: 1

Views: 71

Answers (3)

slorangex
slorangex

Reputation: 1394

To create Toast object you need to have context and string. Context can be

Context context = MainActivity.this;

or

Context context = getActivity();

Then you create your Toast like this:

Toast.makeText(context, getString(R.strings.your_string_id), Toast.LENGHT_SHORT).show();

To learn more about Toasts read the documentation. And about resources, check out this link

Upvotes: 0

Bala Saikrupa Puram
Bala Saikrupa Puram

Reputation: 721

 String arr[] = getResources().getStringArray(R.array.stringname);
    for (int i = 0; i < arr.length; i++) {
            Toast.makeText(getBaseContext(),arr[i], Toast.LENGTH_LONG).show();  
    }

use this code you will get the output

Upvotes: 1

kamituel
kamituel

Reputation: 35960

Try using the Context.getString() method:

String name = getString(R.string.stringname);

The Activity.findViewById() would not work, because string resources are not views.

This article covers string resources in Android.

Upvotes: 0

Related Questions