0

I am using the following code. Although the code is working fine. I want to get string from string.xml file without initialising strings in Java code? I have no clue on what to do. Also I want to make the following: On particular list item click it starts a new activity?

package com.example.listviewexample;
import java.util.Arrays;
import java.util.List;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ListActivity {

    final List<String> elements = Arrays.asList("Element 1", "Element 2", "Element 3",
            "Element 4", "Element 5");

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        ListView listView = getListView();
        listView.setTextFilterEnabled(true);    
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                R.layout.activity_main,elements);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                Toast.makeText(getApplicationContext(),
                        ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
            }``
        });
    }
}
2

2 Answers 2

1

define the Array into your arrays.xml

<?xml version="1.0" encoding="utf-8"?>  
    <resources>  
     <array name="myArray">  
    <item>Element 1</item>  
    <item>Element 2</item>  
    <item>Element 3</item>  
    <item>Element 4</item>  
    <item>Element 5</item>  
     </array>
</resources>

Load the elements:

String[] elements = getResources().getStringArray(R.array.myArray);  
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_main,elements);
Sign up to request clarification or add additional context in comments.

2 Comments

where to define the array? in the string.xml file only or somewhere else. Thanks for help
into the values/arrays.xml
0

As Jorgesys says you should declare it in your values/arrays.xml

If you need different translations for this strings, you should create this arrays.xml in his respective values folder.

See Android Localization link for more help about this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.