Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you reference strings from strings.xml in code?

I'm using the following code to update an image switcher and corresponding strings when the next button is clicked,but I'm having trouble referencing the strings from the res/strings folder in the GetMyString().

For example one of my strings is named cutString.How do I reference it instead of YOUR_STRING_01? Is there a simple way to do call the string or is there a flaw in this implementation?

 btnNext.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
        // TODO Auto-generated method stub
        currentIndex++;
        // If index reaches maximum reset it
        if(currentIndex==messageCount)
        currentIndex=0;
        imageSwitcher.setImageResource(imageIds[currentIndex]);
        tView.setText(getMyString(clicks++));
        }
        });

        //method called to update textview strings.
        public String getMyString(int variable){
            switch(variable){
                case 1:
                    return YOUR_STRING_01;
                    break;
                case 2:
                    return YOUR_STRING_02;
                    break;
                case 3:
                    return YOUR_STRING_03;
                    break;
            }
like image 937
Brian Var Avatar asked Jan 30 '26 11:01

Brian Var


1 Answers

So I notice that your implementation doesnt necessarily have reference to a context so you will need to do something like this.

//method called to update textview strings.
    public String getMyString(final int variable, final Context applicationContext){
        switch(variable){
            case 1:
                return applicationContext.getResources().getString(R.string.something);
                break;
            case 2:
                return applicationContext.getResources().getString(R.string.something2);
                break;
            case 3:
                return applicationContext.getResources().getString(R.string.something3);
                break;
        }

    }
like image 73
Tony Avatar answered Feb 01 '26 04:02

Tony