two spinners that rely on one spinner for array/entries - android

Hi I am making a converter app (just like the one when you google "temperature converter") So I have one spinner making two other spinners show the same array. I know theres code out there for this but i have not found some that deals with many different arrays. For instance I need one Spinner to be able to make the two other spinners show the same array but i have many different arrays to pic from (temperature/length/mass/speed/volume/area/time)
strings.xml
<string-array name="units">
<item>Temperature</item>
<item>Length</item>
<item>Mass</item>
<item>Speed</item>
<item>Volume</item>
<item>Area</item>
<item>Time</item>
</string-array>
<string-array name="Temperature">
<item>Celsius</item>
<item>Fahrenheit</item>
</string-array>
<string-array name="Mass">
<item>Metric Ton</item>
<item>Kilogram</item>
<item>Gram</item>
<item>Milligram</item>
<item>Pound</item>
<item>Ounce</item>
</string-array>
<string-array name="Length">
<item>Kilometer</item>
<item>Meter</item>
<item>Centimeter</item>
<item>Millimeter</item>
<item>Mile</item>
<item>Yard</item>
<item>Foot</item>
<item>Inch</item>
</string-array>
<string-array name="Speed">
<item>Miles/Hour</item>
<item>Feet/Sec</item>
<item>Meters/Sec</item>
<item>Km/Hour</item>
<item>Knot</item>
</string-array>
<string-array name="Time">
<item>Nanosecond</item>
<item>Microsecond</item>
<item>Meters/Sec</item>
<item>Km/Hour</item>
<item>Knot</item>
</string-array>
<string-array name="Area">
<item>Square km</item>
<item>Square meter</item>
<item>Square mile</item>
<item>Hectare</item>
<item>Acre</item>
<item>Square yard</item>
<item>Square foot</item>
<item>Square inch</item>
</string-array>
<string-array name="Area2">
<item>Square km</item>
<item>Square meter</item>
<item>Square mile</item>
<item>Hectare</item>
<item>Acre</item>
<item>Square yard</item>
<item>Square foot</item>
<item>Square inch</item>
</string-array>
Layout Xml File
<Spinner
android:id="#+id/selector1"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/editText1" />
<Spinner
android:id="#+id/spinner_unit"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="73dp"
android:entries="#array/units" />
<Button
android:id="#+id/equelsbutton"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/editText1"
android:background="#color/clear"
android:text="#string/equels"
android:textSize="40sp" />
<Spinner
android:id="#+id/selector2"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/selector1" />
<TextView
android:id="#+id/textView1"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/editText1"
android:layout_alignLeft="#+id/selector2"
android:layout_marginLeft="15dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
Converter_Activity
import android.app.Activity;
import android.os.Bundle;
import android.widget.Spinner;
public class Converter_Activity extends Activity {
public Spinner spinnerunits;
public Spinner spinnerpicker1;
public Spinner spinnerpicker2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.conveter_activity);
spinnerunits = (Spinner) findViewById(R.id.spinner_unit);
spinnerpicker1 = (Spinner) findViewById(R.id.selector1);
spinnerpicker2 = (Spinner) findViewById(R.id.selector2);
}
}
Thanks

Hi i modified the Converter_Activity.java class. Please try with the latest source code. Its working fine for me. Hope it should helpful for you. Thanks.
Converter_Activity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class Converter_Activity extends Activity {
public static Spinner spinnerunits;
public static Spinner spinnerpicker1;
public static Spinner spinnerpicker2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinnerlayout);
spinnerunits = (Spinner) findViewById(R.id.spinner_unit);
spinnerpicker1 = (Spinner) findViewById(R.id.selector1);
spinnerpicker2 = (Spinner) findViewById(R.id.selector2);
ArrayAdapter <String> arrayUnits = new ArrayAdapter <String> (getBaseContext(),android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.units));
arrayUnits.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerunits .setAdapter(arrayUnits);
spinnerunits.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
if(spinnerunits.getSelectedItem().equals("Temperature"))
{
ArrayAdapter <String> s1 = new ArrayAdapter <String> (getBaseContext(),android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Temperature));
s1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerpicker2.setAdapter(s1);
spinnerpicker1.setAdapter(s1);
}else if(spinnerunits.getSelectedItem().equals("Mass"))
{
ArrayAdapter <String> s2 = new ArrayAdapter <String> (getBaseContext(),android.R.layout.simple_spinner_item,getResources().getStringArray(R.array.Mass));
s2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerpicker2.setAdapter(s2);
spinnerpicker1.setAdapter(s2);
}
else if(spinnerunits.getSelectedItem().equals("Speed"))
{
ArrayAdapter <String> s3 = new ArrayAdapter <String> (getBaseContext(),android.R.layout.simple_spinner_item,getResources().getStringArray(R.array.Speed));
s3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerpicker2.setAdapter(s3);
spinnerpicker1.setAdapter(s3);
}
else if(spinnerunits.getSelectedItem().equals("Area"))
{
ArrayAdapter <String> s4 = new ArrayAdapter <String> (getBaseContext(),android.R.layout.simple_spinner_item,getResources().getStringArray(R.array.Area));
s4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerpicker2.setAdapter(s4);
spinnerpicker1.setAdapter(s4);
}
else if(spinnerunits.getSelectedItem().equals("Time"))
{
ArrayAdapter <String> s5 = new ArrayAdapter <String> (getBaseContext(),android.R.layout.simple_spinner_item,getResources().getStringArray(R.array.Time));
s5.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerpicker2.setAdapter(s5);
spinnerpicker1.setAdapter(s5);
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
}
}
Please try this code and let me know. Thanks.

Related

write multiple strings to a file and add a new line

I'm building a basic app that you choose from a spinner, select a color and click save. If the color you're looking for isn't in the spinner, you press a button and you can type it in to the EditText.
I'm trying to make it so I can write both the chosen spinner/edittext color and the date inside of the "colors.txt" file. at the moment, there are no errors but when i launch the app on my android it instantly crashes.
Colorchooser.java
package com.example.scalendar;
import java.io.IOException;
import java.io.OutputStreamWriter;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
public class Colorchooser extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_colorchooser);
}
public void writetoFile(String str) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("colors.txt", Context.MODE_PRIVATE));
outputStreamWriter.write("colorstring , datestring");
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.colorchooser, menu);
return true;
}
}`
And here is my Strings.XML file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">SCalendar</string>
<string name="action_settings">Settings</string>
<string name="color_prompt">What was todays color?</string>
<string name="SaveButtonText">Save To Calendar</string>
<string name="textfieldhint">Enter color</string>
<string name="otherbuttontext">Color not listed</string>
<string name="othercolorexplanationtext">Dont see the color here? Click the button below and type it yourself.</string>
<string-array name="color_arrays">
<item>Select a color:</item>
<item>Purple</item>
<item>Orange</item>
<item>Green</item>
<item>Red</item>
<item>Blue</item>
<item>Pink</item>
<item>Brown</item>
<item>Yellow</item>
<item>Black</item>
<item>White</item>
</string-array>
<string name="colorstring">
colorSpinner = findViewById(R.id.colorSpinner)
colorSpinner.getSelectedItem().toString()
</string>
<string name="datestring">
SimpleDateFormat formatter = new SimpleDateFormat("dd_MM_yyyy");
Date now = new Date();
String fileName = formatter.format(now).toString();
</string>
</resources>`
And here's my Mainactivity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="Colorchooser" >
<Spinner
android:id="#+id/colorSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:entries="#array/color_arrays"
android:prompt="#string/color_prompt" />
<TextView
android:id="#+id/othercolorexplaination"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/colorSpinner"
android:layout_below="#+id/colorSpinner"
android:layout_marginTop="15dp"
android:text="#string/othercolorexplanationtext"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/ButtonSave"
style="#style/AppTheme"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/othercolorexplaination"
android:layout_alignParentBottom="true"
android:layout_marginBottom="62dp"
android:onClick="writetoFile(String getcolor)"
android:text="#string/SaveButtonText" />
<EditText
android:id="#+id/othercolor"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/ButtonSave"
android:layout_below="#+id/otherbutton"
android:layout_marginTop="42dp"
android:ems="10"
android:focusable="false"
android:hint="#string/textfieldhint"
android:inputType="textEmailAddress" >
</EditText>
<Button
android:id="#+id/otherbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/othercolorexplaination"
android:layout_centerHorizontal="true"
android:layout_marginTop="24dp"
android:onClick="othercolor.focusableInTouchMode(true)"
android:text="#string/otherbuttontext" />
</RelativeLayout>`
It seems you have some major misunderstandings on the relation between Java strings vs string variables, and string variables vs string resources:
This:
outputStreamWriter.write("colorstring , datestring");
Will always write "colorstring, datestring" to your file, so the file will look like:
colorstring, datestring
colorstring, datestring
colorstring, datestring
You cannot expect Java code in your string resources to be executed:
<string name="colorstring">
colorSpinner = findViewById(R.id.colorSpinner)
colorSpinner.getSelectedItem().toString()
</string>
Strings in your resources are Constants. There is no way to change them at run time.

Change text color of simple ListView Multiple choice Android

I am developing an app for cricket. My requirement is like this, if i select team 1 the list of available country name has to display and if i select a country name as India the list of player from India has to displayed and in that i have select a multiple players from that. I have done everything. But my problem is i am using android.R.layout.simple_list_item_multiple_choice for selecting players. I am using simple list view and the background of that list is black image. And my listview is like that
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="8.5"
android:cacheColorHint="#00000000"
/>
Now the problem is the listview value is showing black in color. Already i have black background image. And the value also black in color. So its not looking good. How to change the color of listview values to white without changing o custom adapter.
And this is my adapter class
adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,playersName);
lvview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lvview.setAdapter(adapter);
You have to create Custome TextView to change color of all ListView items, instead of passing default android.R.layout.simple_list_item_multiple_choice to ArrayAdapter you should pass custom list item XML, which has different TextColor attribute.
For example, created custom_list_item.xml under folder Layout:
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/textView"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="center_vertical"
android:checkMark="?android:attr/listChoiceIndicatorSingle"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:textColor="#FF00FF"
/>
Then passed it to adapter like as below:
new ArrayAdapter<String>(this, R.layout.custom_list_item, playersName);
EDITED:
Here is the code which is working fine i have tested.
lv.setAdapter(new ArrayAdapter<String>(this, R.layout.custom_list_item, playersName));
lv.setBackgroundColor(Color.BLACK);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> p_arg0, View p_arg1, int p_arg2, long p_arg3)
{
my_sel_items = new String("Selected Items");
SparseBooleanArray a = lv.getCheckedItemPositions();
for (int i = 0; i < a.size(); i++) {
if (a.valueAt(i)) {
my_sel_items = my_sel_items + ","
+ (String) lv.getAdapter().getItem(i);
}
}
Log.v("values", my_sel_items);
}
});
Layout of listview
<ListView
android:id="#+id/android:list"
android:layout_marginTop="60dip"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="#000000"
/>
styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
...other styles
//add this
<style name="ListFont" parent="#android:style/Widget.ListView">
<item name="android:textColor">#FFFFFF</item>
</style>
...other styles
</resources>
at layout xml put this attribute style="#style/ListFont" to listview
check below code:
package com.example.mapsdemo;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
public class MainActivity extends Activity {
ArrayList<String> a = new ArrayList<String>();
private ListView lView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fillarray();
lView = (ListView) findViewById(R.id.listView1);
lView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, a));
lView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lView.setOnItemClickListener(new OnItemClickListener() {
private String my_sel_items;
public void onItemClick(AdapterView arg0, View arg1, int arg2,
long arg3) {
// List list = new ArrayList();
my_sel_items = new String("Selected Items");
SparseBooleanArray a = lView.getCheckedItemPositions();
for (int i = 0; i < a.size(); i++) {
if (a.valueAt(i)) {
my_sel_items = my_sel_items + ","
+ (String) lView.getAdapter().getItem(i);
}
}
Log.v("values", my_sel_items);
}
});
}
private void fillarray() {
// TODO Auto-generated method stub
a.clear();
a.add("a");
a.add("b");
a.add("c");
a.add("d");
a.add("e");
}
}
your result in Log
03-26 12:25:06.106: V/values(3301): Selected Items,a
03-26 12:25:06.810: V/values(3301): Selected Items,a,b
03-26 12:25:07.466: V/values(3301): Selected Items,a,b,c
03-26 12:25:08.136: V/values(3301): Selected Items,a,b,c,d
Edited:
check this link you can use whatever font colour & listview background colour in this code.
Luksprog solution is acceptable and not difficult. But without the line
if (position == 1)

How to get multiple selected items from a ListActivity in Android

I am basically trying to get which items have been selected within a multiple choice enabled ListActivity. I am sure that there are many beginning Android programmers that would love this to be clarified. This app runs fine until it gets to the FOR loop and tries to assign the values of the multi-choice items to ArrayList 'items'. I'm simply trying to use Toast to see if the multi-choice items are being assigned to the Arraylist 'items'. The app crashes when the button is clicked. testing is done in android 2.2 emulator
Here is my Main.xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<Button android:id="#+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Selected Items" />
<ListView android:id="#android:id/list" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:choiceMode="multipleChoice"
android:textFilterEnabled="true" android:fastScrollEnabled="true" >
</ListView>
</LinearLayout>
and here is the code
package com.tests.TestCode;
import android.app.ListActivity;
import android.os.Bundle;
import java.util.ArrayList;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String[] list = {"wrenches","hammers","drills","screwdrivers","saws","chisels","fasteners"};
// Initializing An ArrayAdapter Object for the ListActivity
final ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.simple_list_item_multiple_choice, list);
setListAdapter(adapter);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ListView thelistview = (ListView) findViewById(android.R.id.list);
ArrayList<String> items = null;
SparseBooleanArray checkedItems = thelistview.getCheckedItemPositions();
if (checkedItems != null) {
for (int i=0; i<checkedItems.size(); i++) {
if (checkedItems.valueAt(i)) {
String item = adapter.getItem(checkedItems.keyAt(i)).toString();
items.add(item);
}
}
Toast.makeText(getBaseContext(), items.toString(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "checkedItems == null", Toast.LENGTH_LONG).show();
}
}
});
}
}
Much obliged to anyone that can provide a good answer as to the best way to go about accomplishing this ListActivity scenario, or anyone that can explain why the app crashes at the point of assignment to the ArrayList. Thanks!
Your items list is null and you try to use it before initializing it.
You need to use items = new ArrayList<String>(); somewhere before trying to use it, or you will keep getting NullPointerExceptions.

How to Change List View Text color

In my application I want to change the list view text color. In this case I am using XML file for list view. Is it possible? If yes then give the example.
gender.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#drawable/topelg"
>
<ListView
android:id="#+id/android:list"
android:layout_marginTop="60dip"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="#000000"
/>
</LinearLayout>
Egender.java
package com.Elgifto;
import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
public class Egender extends ListActivity{
Button b1;
ListView lv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gender);
// b1=(Button) findViewById(R.id.butt1);
b1=new Button(this);
b1.setText("Done");
//b1.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
lv=(ListView) findViewById(android.R.id.list);
lv.addHeaderView(b1);
b1.setOnClickListener(new OnClickListener(){
public void onClick(View v)
{
// To send a result, simply call setResult() before your
// activity is finished.
finish();
}
});
lv.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice, GENDER));
lv.setBackgroundColor(Color.BLACK);
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lv.setTextFilterEnabled(true);
}
private static final String[] GENDER = new String[] {
"Male","Female"
};
}
If you would like to change color of all ListView items, instead of passing default android.R.layout.simple_list_item_single_choice to ArrayAdapter you should pass custom list item XML, which has different TextColor attribute.
For example, created custom_list_item.xml under folder Layout:
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/text1"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="center_vertical"
android:checkMark="?android:attr/listChoiceIndicatorSingle"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:textColor="#FF0000"
/>
Then passed it to adapter:
new ArrayAdapter<String>(this, R.layout.custom_list_item, stringList)
I've got list, were all items are red.

android preferences in main layout

I have a problem with the preferences.
I created this simple project :
start.java:
package example.ex;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class start extends Activity {
Intent intent;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void preferences (View view){
intent = new Intent(getApplicationContext(), Preferences.class);
startActivity(intent);
}
}
Preferences.java:
package example.ex;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class Preferences extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
the main activity is the start, from which we go (via a button) to Preferences.
Preferences display the preferences( a list with a pop-up) .
Layout :
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="preferences"
android:onClick="preferences" />
</LinearLayout>
preferenze.xml:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TableRow>
<TextView
android:text="List Selection:"
android:paddingRight="5px"
/>
<TextView android:id="#+id/list"
/>
</TableRow>
</TableLayout>
in values i put arrays.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="country">
<item>U.S. (United States of America)</item>
<item>Italia (Italy)</item>
</string-array>
<string-array name="codice_paese">
<item>US</item>
<item>IT</item>
</string-array>
</resources>
Finally, I created a preferences.xml (in a folder xml in res) :
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Simple Preferences">
<ListPreference android:key="list" android:title="Selection Dialog"
android:summary="Click to pop up a list to choose from"
android:entries="#array/country" android:entryValues="#array/codice_paese"
android:dialogTitle="Choose a country" />
</PreferenceCategory>
</PreferenceScreen>
then: I have a main and then I go to a page of Preferences.
I would like to put directly into the main preferences (instead of the button) and use one Activity
but I can not do it in any way ..
please you have any suggestions?
thanks!
try something like this using SharedPreferences and Spinner instead
package com.example.spinnerpref;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
public class SpinnerPref extends Activity
{
int countrypos;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
countrypos = prefs.getInt("countrypos", 0);
setContentView(R.layout.main);
Spinner countryspinner = (Spinner) findViewById(R.id.country);
ArrayAdapter<CharSequence> countryadapater = ArrayAdapter.createFromResource(
this, R.array.country, android.R.layout.simple_spinner_item);
countryadapater.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
countryspinner.setAdapter(countryadapater);
countryspinner.setOnItemSelectedListener(new countrySelector());
class countrySelector implements OnItemSelectedListener
{
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
countrypos = pos;
}
public void onNothingSelected(AdapterView<?> parent) {}
}
PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
.edit().putInt("countrypos", countrypos).commit();
}
}
something along those lines should be neater for what you are doing.

Categories

Resources