OK, so I've been following a tutorial (http://javatechig.com/android/android-spinner-example) which is about creating Spinners and dynamically adding images (the locations of which are defined in the strings.xml file) to the view. Well that works fine but I'd like to extend the project so that I can include text arrays, again defined in the strings.xml file, to appear both before and after the image.
My code follows and, as you can see I'd like to substitute the 2 setText lines with references to the spinner item that I've already selected.
Any ideas? Thanks for your interest.
Thanks all for your input and I've now solved the problem and am showing some commented code below on how I resolved it...
public class MainActivity extends Activity {
private ImageView image;
private String[] states;
private Spinner spinner1;
private TypedArray imgs;
private String[] leaders;
private String[] descrip;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
states = getResources().getStringArray(R.array.countries);
imgs = getResources().obtainTypedArray(R.array.leader_photos);
// --- The following lines grab the problematic string arrays defined in
// strings.xml
leaders = getResources().getStringArray(R.array.leaders);
descrip = getResources().getStringArray(R.array.descrip);
image = (ImageView) findViewById(R.id.leaderPhoto);
spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, states);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// The variable index identifies what position the selected
// spinner is. TextView text... locks to the TextView defined in
// the activity_main.xml layout file. text.setText... loads the
// appropriate value from the leaders string array
int index = parent.getSelectedItemPosition();
TextView text = (TextView) findViewById(R.id.tv1);
text.setText(leaders[index]);
image.setImageResource(imgs.getResourceId(
spinner1.getSelectedItemPosition(), -1));
// See earlier comments above TextView tv1 for how this works
TextView text2 = (TextView) findViewById(R.id.tv2);
text2.setText(descrip[index]);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
Android - programatically adding text from strings.xml to TextView -
If I understood you right?
Resources resources = context.getResources();
String[] textString = resources.getStringArray(R.array.mytext);
Then you have the text in a string-vector - easy to put in a textView
Then in the xml-file
<string-array name = "mytext">
<item> ... text </item>
<item> ... text</item>
<item> ... text</item>
</string-array>
And in the textView-object
text.setText(textString[i]); // at position i
You can use the position you get into the OnClickListener of Spinner to get the particular Leader and Description of the that states as follows.
text.setText(leader[position]);
text2.setText(descrip[position]);
Related
I have a spinner:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int childposition, long id) {
textView.setText(spinner.getSelectedItem().toString());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
textView.setText("");
}
});
Above you'll see that textView - is my text object. I'm displaying a text item spinner in the textView when I click it. If I dont click the spinner then my textView must be textView.setText("");
But the spinner is always set text in my textView, even if I do not choose spinner.
Question
How can I accomplish this?:
If I dont choose item spinner, textView is empty: textView.setText("");
If I do choose the item spinner, textView gets: textView.setText(spinner.getSelectedItem().toString());
String item = parent.getItemAtPosition(childposition).toString(); //Get selected item
if(item.equals("spinner")){ // Check if it equals spinner
textView.setText(item); // Set text to item
}else{
textView.setText(""); // If it doesn't equal spinner set text to ""
}
If I understood the question right, putting this instead of textView.setText(spinner.getSelectedItem().toString()); and deleting content of onNothingSelected should do the trick.
UPDATE
I finally understood what you mean. To do this create your spinner like this and add "" as first choice in your string-array resource :
String[] newArray = getResources().getStringArray(R.array.yourArray);
List<String> myResArrayList = Arrays.asList(newArray);
ArrayList<String> spinnerItems = new ArrayList<String>(myResArrayList);
//Making adapter with ArrayList instead of String[] allows us to add/remove items later in the code
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, spinnerItems);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinnerItems.remove(0);
adapter.notifyDataSetChanged(); // Here we remove the first choice which is "" so the user won't be able to select empty.
I have written a program to display a ListView. The Activity contains an EditText with a search button and ListView below. I have defined the items inside string.xml to be displayed inside the ListView:
<string-array name="Name2">
<item>Name:Rohit Kumar</item>
<item>Name:Rohit Kumar</item>
<item>Name:Rohit Kumar</item>
<item>Name:Rohit Kumar</item>
<item>Name:Rohit Kumar</item>
<item>Name:Rohit Kumar</item>
</string-array>
<string-array name="Name3">
<item>Name:Arjun Narahari</item>
<item>Name:Arjun Narahari</item>
<item>Name:Arjun Narahari</item>
<item>Name:Arjun Narahari</item>
<item>Name:Arjun Narahari</item>
<item>Name:Arjun Narahari</item>
</string-array>
I have put it 6 times because inside my ListView I want to display the same name 6 times.
What my program does is, when I write "ar" inside my EditText and when I write "ro" or any timmed letter inside my EditText and click on search button, the results are displayed for the item which I have passed inside my custom adapter means for any case Arjun Narahari is only displayed and if I pass the rohit array, then for any case rohit is only displayed inside my ListView.
What I want my program to do is, when I write A or Ar inside my EditText and click on search button I want the results inside my ListView to be only starting from A or Ar and when I write R or Ro only those results should be displayed inside my ListView.
Please, need some help.
Will post my code here:
Result_Name.java
public class Result_Name extends Activity {
ImageView iv;
EditText etSearch;
private TextView txtNoResult;
ImageView imgSearch;
ResultsNameAdapter adapter;
ListView lv;
String[] name1, name2; // name3, name4, name5, name6;
String[] mobile0, mobile1; // mobile2, mobile3, mobile4, mobile5;
String[] age1, age2; // age3, age4, age5, age6;
String[] gender;
String[] diagname;
String[] year;
String PassedData;
int[] images = {
R.drawable.photo_bg,
R.drawable.photo_bg,
R.drawable.photo_bg,
R.drawable.photo_bg,
R.drawable.photo_bg,
R.drawable.photo_bg,
R.drawable.date,
R.drawable.b_list,
R.drawable.v_list,
R.drawable.g_list
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_listr_name);
iv = (ImageView) findViewById(R.id.imgBackReuslt);
etSearch = (EditText) findViewById(R.id.edtSearchName);
imgSearch = (ImageView) findViewById(R.id.imgSearchlist);
Resources res = getResources();
name1 = res.getStringArray(R.array.Name1);
name2 = res.getStringArray(R.array.Name2);
mobile0 = res.getStringArray(R.array.Mobile0);
mobile1 = res.getStringArray(R.array.Mobile1);
age1 = res.getStringArray(R.array.Age1);
age2 = res.getStringArray(R.array.Age2);
diagname = res.getStringArray(R.array.DiagnosisName);
gender = res.getStringArray(R.array.Gender);
year = res.getStringArray(R.array.year_array);
etSearch = (EditText) findViewById(R.id.edtSearchName);
etSearch = (EditText) findViewById(R.id.edtSearchName);
imgSearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (etSearch.getText().toString().trim().length() < 0) {
lv.setVisibility(View.GONE);
}
if (etSearch.getText().toString().trim().length() > 0) {
lv = (ListView) findViewById(R.id.lstResult);
adapter = new ResultsNameAdapter(getBaseContext(), name1,
name2, mobile0, mobile1, age1, age2, images, year,
diagname, gender);
lv.setAdapter(adapter);
}
}
});
The imgsearch is the image which I am using as a ClickListener and etsearch is my EditText. If my EditText is empty, my ListView is not visible and when my EditText has text with length > 0, my ListView is visible. This is where I want to change my things which I mentioned up.
I hope the requirements are clear.
Any suggestions are welcome.
What i want my program to do is , when i write A or Ar inside my edittext and click on search button i want the results inside my listview to be only starting from A or Ar and when i write R or Ro only those results should be displayed inside my listview
A good way for you to achieve this and make it efficient is to use a Trie data structure and you should look into that because explaining it is too broad for my SO answer.
Another way to reach to a simple solution would be to use the String.startsWith method:
String text = etSearch.getText().toString().trim();
// check for "Rohit Kumar" array
for(String name : name2) {
String nameWithoutLabel = name.substring(5); // skip the "Name:" part
if(nameWithoutLabel.startsWith(text)) {
// you will reach this point only if current nameWithoutLabel starts with the text from your EditText
// add nameWithoutLabel to your list view or where you need it
}
}
// same check for name3 which is the "Arjun Narahari" array
Another way you could check for Strings that start with a certain sequence is to use a regular expression:
// ...
if (nameWithoutLabel.matches("(" + text + ").*")) {
// ...
How you want to use the code above depends on how your ResultsNameAdapter is used and how you want to organize your data.
For example, what you can do is create a method out of the code above that finds Strings inside an array that starts with a certain text. Something like:
ArrayList<String> getMatches(String text, String[] names) {
ArrayList<String> list = new ArrayList<String>();
for(String name : names) {
String nameWithoutLabel = name.substring(5); // skip the "Name:" part
if(nameWithoutLabel.startsWith(text)) {
list.add(nameWithoutLabel);
}
}
return list;
}
Then you can call this method to find matches from whichever array you need to and store the matches in an ArrayList:
ArrayList<String> allMatches = new ArrayList<String>();
// ...
String text = etSearch.getText().toString().trim();
allMatches.addAll(getMatches(text, name2)); // add all matches from name2
allMatches.addAll(getMatches(text, name3)); // add all matches from name3
// now ArrayList allMatches contains all matches from arrays name2 and name3
Now you can use the ArrayList<String> allMatches to populate your ListView inside your ResultsNameAdapter...
I got a problem with reading items from string-array one by one. For example, i got string-array with 10 items:
<string-array name="arr">
<item>First</item>
<item>Second</item>
<item>...</item>
<item>Tenth</item>
</string-array>
So i know how to display items randomly, im using this code
Resources res = getResources();
myString = res.getStringArray(R.array.arr);
int length=myString.length;
int index=rgenerator.nextInt(length);
String q = myString[index];
tv = (TextView) findViewById(R.id.text);
tv.setText(q);
And in TextView on every button click it displays random item from array.
Problem is, how to make display item from string-array not randomly. Like, it starts from displaying First, then on click it displays Second, and so on untill end of array.
Please help!
You can't initialize your testArray field this way, because the application resources still aren't ready.
Change the code to:
package com.xtensivearts.episode.seven;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class Episode7 extends ListActivity {
String[] mTestArray;
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create an ArrayAdapter that will contain all list items
ArrayAdapter<String> adapter;
mTestArray = = getResources().getStringArray(R.array.testArray);
/* Assign the name array to that adapter and
also choose a simple layout for the list items */
adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
mTestArray);
// Assign the adapter to this ListActivity
setListAdapter(adapter);
}
}
Declare a variable
int currentIndex=0;
outside this onClick method.
In the
onClick(View v)
{
//Verify if only that btn is clicked
{
tv.setText(myString[(currentIndex++)%(myString.length)]);
}
}
Hope it works.
try
int i=0;
String q = myString[i];
i++;
strings.xml
<string-array name="month">
<item>Jan</item>
<item>Feb</item>
<item>Mar</item>
<item>Apr</item>
<item>May</item>
<item>Jun</item>
<item>Jul</item>
<item>Aug</item>
<item>Sep</item>
<item>Oct</item>
<item>Nov</item>
<item>Dec</item>
</string-array>
java
for (int i = 0; i < getResources().getStringArray(R.array.month).length; i++) {
Log.e("Array",""+getResources().getStringArray(R.array.month)[i]);
}
I have a custom ListActivity that acts as a multiple choice question, and I am trying to change the font of the items in the list. Here's what I have...
public class MultipleChoiceActivity extends ListActivity {
private TextView questionView;
private String[] items = { "a", "b", "c", "d" };
#Override
public void onCreate(Bundle savedInstanceState) {
//do some stuff like populate items array from db
setContentView(R.layout.multichoice_activity);
setListAdapter(new ArrayAdapter(this, R.layout.custom_list_item, items));
questionView = (TextView) findViewById(R.id.question);
Typeface typeFace=Typeface.createFromAsset(getAssets(),"fonts/Schalk.ttf");
questionView.setText(question);
questionView.setTypeface(typeFace);
}
public void onListItemClick(ListView parent, View v, int position, long id) {
userAnswer = position + 1;
}
So I have been able to set the TextView named "question" with the correct font from my assets, but I haven't been able to use that asset to set it for the elements in the list. Any ideas?
You need to set the TypeFace for each specific view you want. Usually this means, at a bare minimum, you need to set the TypeFace for each view in the adapter as opposed to the ListView itself.
I have a spinner, that uses an array from strings.xml
if the array has 5 strings (1,2,3,4,5), and i want the spinner to show second
string (2) as default value, is this possible?
I know i can re-arrange the strings order so that first one is 2,
but this doesn't look very good if spinner dialog appears as (2,1,3,4,5).
Or does the array have to be created within my activity programatically
and then use setPostion()?
I have tried this, but get a fault when creating array in activity.
Can anyone please give me an example of how to create array and use
it in spinner()
I have also searched on here for answers but cant seem to find what i need.
Thanks for looking....
I recommend you check: http://developer.android.com/resources/tutorials/views/hello-spinner.html
You should create an ArrayAdapter in your Activity.
From the above link:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.planets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
You can use
spinner.setSelection(adapter.getPosition(value)));
to set the position.
Cheers for reply.....
Didn't do what i needed, but have managed to solve my problem as follows..
First i created an array within my activity, instead of strings.xml.
String[] NoCore_Array = new String [5];
{
NoCore_Array[0] = "1";
NoCore_Array[1] = "2";
NoCore_Array[2] = "3";
NoCore_Array[3] = "4";
NoCore_Array[4] = "5";
}
Then i created the spinner using...
Spinner spnNoCore = (Spinner) findViewById(R.id.spinner_nocore);
Then created the adapter, using above array....
ArrayAdapter NoCoreAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, NoCore_Array);
spnNoCore.setAdapter(NoCoreAdapter);
Then set default position of the adapter as follows...
//Set Default Selection
spnNoCore.setSelection(1);
Then rest of spinner code for actions...
spnNoCore.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
//Get item from spinner and store in string conductorSize........
NoCore = parent.getItemAtPosition(pos).toString();
if (NoCore.equals(NoCore1)) { CoreNo = 1 ; }
if (NoCore.equals(NoCore2)) { CoreNo = 2 ; }
if (NoCore.equals(NoCore3)) { CoreNo = 3 ; }
if (NoCore.equals(NoCore4)) { CoreNo = 4 ; }
if (NoCore.equals(NoCore5)) { CoreNo = 5 ; }
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
});
Hope this may help other people who are having same problem with
setting default selection on Spinner.
However the layout of the dialog is not as good when done this way,
Radio buttons are missing, just looks like a text selection
with lines dividing the sections.