Android Spinner is not clickable or working while running app - android

I am relatively new to programming and recently started working with android. I have been breaking my brains all day over this problem I have with a spinner. I read several similar questions and found several solutions and examples but none of them work for me :(
package com.deitel.welcome;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.view.View;
import android.widget.AdapterView.OnItemSelectedListener;
public class Preferences extends Activity {
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preferences);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.preferences, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_profile) {
Intent intent = new Intent(Preferences.this, Profile.class);
startActivity(intent);
}
else if (id == R.id.action_home) {
Intent intent = new Intent(Preferences.this, HomeScreen.class);
startActivity(intent);
}
else if (id == R.id.action_calendar) {
Intent intent = new Intent(Preferences.this, CalendarActivity.class);
startActivity(intent);
}
else if (id == R.id.action_statistics) {
Intent intent = new Intent(Preferences.this, Statistics.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
public class MainActivity extends Activity {
private String[] states;
private Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
states = getResources().getStringArray(R.array.countries_list);
spinner = (Spinner) findViewById(R.id.country_spinner);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, states);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
}
And this is my customOnItemSelected java file:
package com.deitel.welcome;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
Toast.makeText(parent.getContext(),
"On Item Select : \n" + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
This is my resources file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="spinner_prompt">Choose a country</string>
<string-array name="country_arrays">
<item>Malaysia</item>
<item>United States</item>
<item>Indonesia</item>
<item>France</item>
<item>Italy</item>
<item>Singapore</item>
<item>New Zealand</item>
<item>India</item>
</string-array>
</resources>
And this is of course my XML file:
<?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:padding="10dip" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:text="#string/country_label"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Spinner
android:id="#+id/country_spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="#string/country_label" />
</LinearLayout>
Can anyone figure out what I did wrong?
Greetings! Rosa

This fragment of your code:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Adds listener without any logic because you didn;t provide any inside overriden methods. What you should do is add your custom listener like that:
spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener())

you have done nothing in your on item selected . try adding a toast message in your main activity's on item selected and why is there a need for creating a custom listener when you can use the default one?
try like this in your main activity:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(parent.getContext(),"spinner clicked",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
just try adding a toast in your default listener or else set the custom listener you have made.You are not setting it as your listener and hence nothing is happening.

Simple Spinner Example and Onclick listner
String[] tracks_time = { "3min", "5min", "10min" };
Spinner spinner_time = (Spinner)promptsView.findViewById(R.id.sp_time);
ArrayAdapter<String> sptime = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, tracks_time);
spinner_time.setAdapter(sptime);
spinner_time.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int position ,long arg3)
{
int index = parent.getSelectedItemPosition();
// get stuff as per index
}
public void onNothingSelected(AdapterView<?> arg0)
{
}
});

Thanks everyone! You are right... I found out that I actually created another class within my activity and did nothing in the original activity. Thanks for your help!
I kind of copied everything into the first class and added some stuff. Here is the code that worked for me in the end:
public class Preferences extends Activity {
protected CharSequence[] _options = { "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday" };
protected boolean[] _selections = new boolean[_options.length];
protected Button _optionsButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preferences);
_optionsButton = (Button) findViewById(R.id.button1);
_optionsButton.setOnClickListener(new ButtonClickHandler());
}
public class ButtonClickHandler implements View.OnClickListener {
public void onClick(View view) {
showDialog(0);
}
}
#Override
protected Dialog onCreateDialog (int id) {
return new AlertDialog.Builder(this)
.setTitle("Preferred Exercise Days")
.setMultiChoiceItems(_options, _selections,
new DialogSelectionClickHandler())
.setPositiveButton("OK", new DialogButtonClickHandler())
.create();
}
}
public class DialogSelectionClickHandler implements
DialogInterface.OnMultiChoiceClickListener {
public void onClick(DialogInterface dialog, int clicked,
boolean selected) {
Log.i("ME", _options[clicked] + " selected: " + selected);
}
}
public class DialogButtonClickHandler implements
DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int clicked) {
switch (clicked) {
case DialogInterface.BUTTON_POSITIVE:
String selected = "";
int i = 0;
for (boolean b : _selections) {
if (b) {
selected += _options[i] + " ;";
}
i++;
}
printSelectedDays();
Toast.makeText(Preferences.this, "Selected: " + selected,
Toast.LENGTH_SHORT).show();
break;
}
}
}
protected void printSelectedDays() {
for (int i = 0; i < _options.length; i++) {
Log.i("ME", _options[i] + " selected: " + _selections[i]);
}
}
The solution is kind of different but it is actually what I wanted to achieve in the first place so I hope someone can use this after all.

Related

Advice with DatePicker code structure Android Studio

So I'm very new to android programming, and have no real experience with software building however I do have a basic background with PHP so I get some of the theory behind it all.
I'm currently making a basic Form activity that will store the entries into a DB, which can be recalled in another activity where it can be viewed and edited etc etc.
I have found lots of helpful advice to get to where I am but currently having trouble with how I need to structure the code to implement the DatePicker dialog, the problem I'm facing is the example code for the date picker has
public class MainActivity extends Activity implements OnClickListener {
Where as the code in my project is public class New extends ActionBarActivity {
So when I edit the line to "implements OnClickListener" my spinner drop downs don't like it.
I have tried entering the code in without the "implements OnClickListener"
Please take a look at what I have and point me in the right direction, I need to understand where its going wrong and how it should be structured.
public class New extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
//Product List
Spinner productList = (Spinner) findViewById(R.id.product);
String[] products = new String[] { "1", "2", "3" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, products);
productList.setAdapter(adapter);
productList.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Log.v("products", (String) parent.getItemAtPosition(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
//Reason List
Spinner reasonList = (Spinner) findViewById(R.id.reason);
String[] reasons = new String[] { "A", "B", "C" };
ArrayAdapter<String> adapters = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, reasons);
reasonList.setAdapter(adapters);
reasonList.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Log.v("reasons", (String) parent.getItemAtPosition(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
//Start Date Picker
private EditText StartDate;
private DatePickerDialog StartdatePickerDialog;
private SimpleDateFormat dateFormatter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
findViewsById();
setDateTimeField();
}
private void findViewsById() {
StartDate = (EditText) findViewById(R.id.startdate);
StartDate.setInputType(InputType.TYPE_NULL);
StartDate.requestFocus();
}
private void setDateTimeField() {
StartDate.setOnClickListener(this);
Calendar newCalendar = Calendar.getInstance();
StartdatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
StartDate.setText(dateFormatter.format(newDate.getTime()));
}
}, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
#Override
public void onClick(View view) {
if(view == StartDate) {
StartDatePickerDialog.show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_new, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Unless I'm mistaken, try removing the implements OnClickListener from your activity and replacing
StartDate.setOnClickListener(this);
with
StartDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(view == StartDate) {
StartDatePickerDialog.show();
}
}
});
and removing the onclick method in Start Date Picker. Basically, what implements OnClickListener does is that it can be attached to components (the EditText, in this case) which, when clicked, will be redirected to your implementation of onClick. You're replacing your Activity listener (which can be used by any component in that activity via setOnClickListener(this)) with a specific listener designed for the StartDate alone. Note how your spinners all have onItemSelectedListeners, which work on the same basic principle.
Words are hard, let me know if that doesn't make sense.

switch case with two spinners and audio player

In my activity i have two spinners, one image view and two buttons.
depending on first spinner the second spinners should change. and while selecting birds in first spinner the second spinner should show parrot peacock etc. while selecting parrot in second spinner i should get the image of parrot.
till this i am getting.
but now what i want is while i press a button then i should get the voice of parrot.
in this code when i am pressing the button i am getting the same voice for every picture change in second spinner
public class MainActivity extends Activity {
ImageView displayIV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
;
Button b1;
b1=(Button)findViewById(R.id.button1);
Spinner friend = (Spinner) findViewById(R.id.spinner1);
final Spinner subFriend = (Spinner) findViewById(R.id.spinner2);
displayIV=(ImageView)findViewById(R.id.imageView1);
final ArrayList<String> friend_options = new ArrayList<String>();
final ArrayList<String> subfriend_options = new ArrayList<String>();
friend_options.add("Nuz");
friend_options.add("Dur");
friend_options.add("Tara");
friend_options.add("Sama");
ArrayAdapter<String> friendAdapter = new ArrayAdapter<String>(
getApplicationContext(), android.R.layout.simple_spinner_item,
friend_options);
friend.setAdapter(friendAdapter);
ArrayAdapter<String> subFriendAdapter = new ArrayAdapter<String>(
getApplicationContext(),
android.R.layout.simple_spinner_item,subfriend_options);
subFriend.setAdapter(subFriendAdapter);
friend.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View view,
int position, long id) {
String friendName =
friend_options.get(position).toString();
resetFriend(friendName);
// subFriend.setAdapter(null);
}
private void resetFriend(String friendName) {
subfriend_options.removeAll(subfriend_options);
if (friendName.equals("Nuz")) {
subfriend_options.add("Nuz_1");
subfriend_options.add("Nuz_2");
subfriend_options.add("Nuz_3");
subfriend_options.add("Nuz_4");
} else if (friendName.equals("Dur")) {
subfriend_options.add("Dur_1");
subfriend_options.add("Dur_2");
subfriend_options.add("Dur_3");
subfriend_options.add("Dur_4");
} else if (friendName.equals("Tara")) {
subfriend_options.add("Tara_1");
subfriend_options.add("Tara_2");
subfriend_options.add("Tara_3");
subfriend_options.add("Tara_4");
} else {
subfriend_options.add("Sama_1");
subfriend_options.add("Sama_2");
subfriend_options.add("Sama_3");
subfriend_options.add("Sama_4");
}
ArrayAdapter<String> subFriendAdapter = new
ArrayAdapter<String>( getApplicationContext(),
android.R.layout.simple_spinner_item,
subfriend_options);
subFriend.setAdapter(subFriendAdapter);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
subFriend.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
arg0.getItemAtPosition(arg2);
final ImageView im =
(ImageView)findViewById(R.id.imageView1);
String s=((TextView)arg1).getText().toString();
if(s.equals("Tara_1")){
im.setImageDrawable(getResources().getDrawable(R.drawable.crow));
}
if(s.equals("Tara_2"))
im.setImageDrawable(getResources().getDrawable(R.drawable.india1));
if(s.equals("Tara_3"))
im.setImageDrawable(getResources().getDrawable(R.drawable.peacock));
if(s.equals("Tara_4"))
im.setImageDrawable(getResources().getDrawable(R.drawable.robin1));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//MediaPlayer mMediaPlayer = MediaPlayer.create(this,
R.raw.Kalimba);
MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.abc);
mp.start();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
In the setOnClickListener method of your button, b1, you need to know which image has been selected on the spinner (your description is a little bit confusing so i don't have clear exactly which spinner is going to change the sound that you app has to reproduce).
Anyway, let think that the spinner is "friend_options".
In you setOnClickListener we have to know which item has been selected for the user when click on the button, right? And depending of which item was selected, we will play one specific sound.
So....
Another important poin is that you should create the variable of the mediaplayer outside of the onclickListener, like a class variable:
//Class variable:
public MediaPlayer mp;
In the onCreate method you should initialize the MediaPlayer component:
public void onCreate()
{
MediaPlayer.create(MainActivity.this, R.raw.abc); //Default sound, it is not
//importat because we are going
//to chain the value of the
//file to reproduce in the next
//step.
}
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Here we are going to take the item selected:
String itemSelected = spinner.getSelectedItem().toString();
int soundToPlayId=0;
if(itemSelected.equals("Nuz"))
{
soundToPlayId = R.raw.Kalimba ;
}
else if(itemSelected.equals("Dur"))
{
soundToPlayId = R.raw.abc;
}
// etc etc etc --> you should put all the sound associated to all the
// friends
//And now you only have to reproduce if the item was selected properly:
if(soundToPlayId !=0) //if the id is different to 0:
{
mp = MediaPlayer.setDataSource(MainActivity.this, soundToPlayId);
mp.start();
}
}
});
Let see if it is working!!! Ask me if you have any doubt...and if the answer is correct, vote me and check as correct!!! (I need points, thanks!)

android setOnItemClickListener not respond when comes back from another activity

I have a listview in my activity.
first time I click listview item, it works fine.
when I press back button and comes back to this activity, I can't click on the item anymore.
this listview works fine with android2.
when i test with android 4, happens this problem.
I found this kind of problem here, and I've tried all 'descendentFocusabilty' thing,
but not solved yet.
I know i shouldn't post almost same question. but i couldn't find any answer works fine there.
please help me solve this problem.
here is my child1 activity
public class TabChild1 extends NavigationActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabchild1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
adapter.add("red");
adapter.add("green");
adapter.add("blue");
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
ListView listView = (ListView) parent;
String item = (String) listView.getItemAtPosition(position);
Intent intent = new Intent(TabChild1.this, TabChild2.class);
int iNum = position;
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
goNextHistory("TabChild2", intent);
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}
here is my NavigationActivity
public class NavigationActivity extends Activity {
public void goNextHistory(String id, Intent intent) {
NavigationGroupActivity parent = ((NavigationGroupActivity) getParent());
View view = parent.group.getLocalActivityManager()
.startActivity(id,intent)
.getDecorView();
parent.group.replaceView(view);
}
#Override
public void onBackPressed() {
NavigationGroupActivity parent = ((NavigationGroupActivity) getParent());
parent.back();
}
}
here is my NavigationGroupActivity
public class NavigationGroupActivity extends ActivityGroup {
ArrayList<View> history;
NavigationGroupActivity group;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
history = new ArrayList<View>();
group = this;
}
public void changeView(View v) {
history.remove(history.size() - 1);
history.add(v);
setContentView(v);
}
public void replaceView(View v) {
history.add(v);
setContentView(v);
}
public void back() {
if(history.size() > 1) {
history.remove(history.size() - 1);
setContentView(history.get(history.size() - 1));
} else {
finish();
}
}
#Override
public void onBackPressed() {
group.back();
return;
}
}
and my child1 layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
i think You have to use finish() inside the onBackPressed() method of class TabChild1. and comment the line parent.back() inside the onBackPressed() method of class NavigationActivity.
I think this will work for you.

Android 3 Spinners

First of I'm a novice. I've been through the example of how to create a spinner, and I've searched this site and the Internet for how to create multiple spinners with the list in the 2nd spinner being dependant upon the first spinner and the 3rd spinner list being dependent upon the selection in the 2nd. However I cannot find a tutorial or solution anywhere.
Could someone provide some help to as to how this would be done (a tutorial would be great :))
Basically A list in Spinner1 could be 'Manufacturer', on selection Produces a list of 'Models' in Spinner2 and from the selection of Model in spinner2 produces a list of 'Issues' in Spinner3.
Any help would be great,
Thanks in advanced.
See here this demo have Two Spinner and works
so onItemSelected method you can check your fisrt,second,third spinner value and set as per your requires.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Spinner spinner1,spinner2,spinner3;
public static final String AP_DISTRICTS = "Andhra Pradesh";
public static final String TN_DISTRICTS = "Tamil Nadu";
public static final String TG_DISTRICTS = "Telangana";
public static final String VC_DISTRICTS = "Victoria";
public static final String TS_DISTRICTS = "Tasmania";
public static final String QL_DISTRICTS = "Queens Land";
public static final String KR_DISTRICTS = "Karachi";
public static final String LH_DISTRICTS = "Lahore";
public static final String SI_DISTRICTS = "Sindh";
public static final String SELECT_COUNTRY = "--Select Country--";
public static final String SELECT_STATE = "--Select State--";
public static final String SELECT_DISTRICT = "--Select District--";
String[] country = {SELECT_COUNTRY, "India", "Australia", "Pakistan"};
String[] indiaStates = {SELECT_STATE, AP_DISTRICTS, TN_DISTRICTS, TG_DISTRICTS};
String[] australiaStates = {"SELECT_STATE", VC_DISTRICTS, TS_DISTRICTS, QL_DISTRICTS};
String[] pakistanStates = {"SELECT_STATE", KR_DISTRICTS, LH_DISTRICTS, SI_DISTRICTS};
String[] apDistricts = {SELECT_DISTRICT, "Nellore", "Chittoor", "Prakasam"};
String[] tnDistricts = {SELECT_DISTRICT, "Chennai", "Thiruvallur", "Kanchipuram"};
String[] tgDistricts = {SELECT_DISTRICT, "Hyderabad", "Secunderabad", "Ranga Reddy"};
String[] vicDistricts = {SELECT_DISTRICT, "Ballarat South", "Ballarat North", "Ballarat East"};
String[] tsDistricts = {SELECT_DISTRICT, "Tasmania East", "Tasmania West", "Tasmania South"};
String[] qsDistricts = {SELECT_DISTRICT, "Queens Land East", "Queens Land West", "Queens Land North"};
String[] krDistricts = {SELECT_DISTRICT, "Karachi East", "Karachi North", "Karachi South"};
String[] lhDistricts = {SELECT_DISTRICT, "Lahore South", "Lahore East", "Lahore North"};
String[] siDistricts = {SELECT_DISTRICT, "Sindh West", "Sindh North", "Sindh East"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner1 = (Spinner) findViewById(R.id.spinner_item1);
spinner2 = (Spinner) findViewById(R.id.spinner_item2);
spinner3 = (Spinner) findViewById(R.id.spinner_item3);
spinner1.setSelection(0);
spinner2.setSelection(0);
spinner3.setSelection(0);
setSpinner(spinner1, country);
setSpinner(spinner2, indiaStates);
setSpinner(spinner3, apDistricts);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, country);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (i){
case 0:
Toast.makeText(MainActivity.this, "please Select Country", Toast.LENGTH_SHORT).show();
spinner1.setSelection(0);
spinner2.setSelection(0);
spinner3.setSelection(0);
break;
case 1:
setSpinner(spinner2, indiaStates);
break;
case 2:
setSpinner(spinner2, australiaStates);
break;
case 3:
setSpinner(spinner2, pakistanStates);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String selectedItem = adapterView.getSelectedItem().toString();
if (spinner1.getSelectedItemPosition() == 0) {
Toast.makeText(MainActivity.this, "please Select Country", Toast.LENGTH_SHORT).show();
spinner2.setSelection(0);
spinner3.setSelection(0);
return;
}
if (i == 0){
spinner3.setSelection(0);
return;
}
switch (selectedItem){
case AP_DISTRICTS:
setSpinner(spinner3, apDistricts);
break;
case TN_DISTRICTS :
setSpinner(spinner3, tnDistricts);
break;
case TG_DISTRICTS:
setSpinner(spinner3, tgDistricts);
break;
case VC_DISTRICTS:
setSpinner(spinner3, vicDistricts);
break;
case TS_DISTRICTS:
setSpinner(spinner3, tsDistricts);
break;
case QL_DISTRICTS:
setSpinner(spinner3, qsDistricts);
break;
case KR_DISTRICTS:
setSpinner(spinner3, krDistricts);
break;
case LH_DISTRICTS:
setSpinner(spinner3, lhDistricts);
break;
case SI_DISTRICTS :
setSpinner(spinner3, siDistricts);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
spinner3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (spinner2.getSelectedItemPosition() == 0 || spinner1.getSelectedItemPosition() == 0) {
Toast.makeText(MainActivity.this, "please Select State", Toast.LENGTH_SHORT).show();
spinner2.setSelection(0);
spinner3.setSelection(0);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void setSpinner(Spinner spinner2, String[] states) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, states);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Specify the layout to use when the list of choices appears
spinner2.setAdapter(adapter);
}
}
You can do this by handling onItemSelected event.
you can store your data in database or in arrays and on selection you can populate particular array in particular spinner.
this is straight from one of my app's (actually the first app i ever wrote) so its not pretty but it works
package com.skyesmechanical.OilProductionLogApp;
import android.app.Activity;
import android.app.AlertDialog;
import android.database.Cursor;
import android.database.SQLException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
import java.io.IOException;
public class test extends Activity {
/** Called when the activity is first created. */
public String spinnerPipeLengthText = "";
public String spinnerNaturalGasText = "";
public String spinnerPropaneGasText = "";
public Spinner spinnerPipeLength;
public Spinner spinnerTypeGas;
public Spinner spinnerSupplyPressure;
public static Integer spinnerPipeLengthInt = 0;
public static Integer spinnerTypeGasInt = 0;
public static Integer spinnerPropaneGasInt = 0;
public static Integer spinnerSupplyPressureInt = 0;
public static Integer finalRow = 0;
public boolean supplyPressureVisible = false;
public boolean pipeLengthVisible = false;
static TextView textViewSize15;
static TextView textViewSize19;
static TextView textViewSize25;
static TextView textViewSize31;
static TextView textViewSize37;
static TextView textViewSize46;
static TextView textViewSize62;
static TextView textViewSupplyPressure;
static TextView textViewSelectPipeLength;
public static Integer baseTableRowNumber = 0;
public static Cursor cursorResult;
// these to int's keep a false Toast message from appearing
private int intSpinnerCountGas = 0;
private int intSpinnerCountSupply = 0;
private int intSpinnerCountLength = 0;
private static final int NO_OF_EVENTS_GAS = 1;
private static final int NO_OF_EVENTS_SUPPLY = 1;
private static final int NO_OF_EVENTS_LENGTH = 1;
#Override
public void onCreate (Bundle state) {
super.onCreate(state);
setContentView(R.layout.main);
//check if app just started or is being restored from memory
if (state != null ) {
//app is being restored from memory, not executed from scratch
//initialize the fields to the last used;
supplyPressureVisible = state.getBoolean("supplyPressureVisible");
pipeLengthVisible = state.getBoolean("pipeLengthVisible");
spinnerTypeGasInt = state.getInt("spinnerTypeGasInt");
spinnerSupplyPressureInt = state.getInt("spinnerSupplyPressureInt");
spinnerPipeLengthInt = state.getInt("spinnerPipeLengthInt");
finalRow = state.getInt("finalRow");
Toast.makeText(getApplicationContext(), "savedInstanceState != null", Toast.LENGTH_LONG).show();
} //end if
// call doInBackground
new LoadDataBaseTask().doInBackground();
mainProgram ();
} // end onCreate
// performs database query outside GUI thread
private class LoadDataBaseTask extends AsyncTask<Object, Object, Cursor> {
DataBaseHelper myDbHelper = new DataBaseHelper(CSSTPipeSizingActivity.this);
// perform the database access
#Override
protected Cursor doInBackground (Object... params) {
try {
myDbHelper.createDataBase();
}
catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}
catch(SQLException sqle) {
throw sqle;
}
return myDbHelper.getData();
} // end method doInBackground
// use the Cursor returned from the doInBackground method
#Override
protected void onPostExecute(Cursor result) {
//myDbHelper.changeCursor(result); // set the adapter's Cursor
myDbHelper.close();
} // end method onPostExecute
} // end class LoadDataBaseTask
public void mainProgram () {
spinnerTypeGas = (Spinner) findViewById(R.id.spinnerTypeGas);
spinnerSupplyPressure = (Spinner) findViewById(R.id.spinnerSupplyPressure);
spinnerPipeLength = (Spinner) findViewById(R.id.spinnerPipeLength);
spinnerSupplyPressure.setVisibility(View.INVISIBLE);
textViewSelectPipeLength.setVisibility(View.INVISIBLE);
spinnerPipeLength.setVisibility(View.INVISIBLE);
if (supplyPressureVisible == true) spinnerSupplyPressure.setVisibility(View.VISIBLE);
else spinnerSupplyPressure.setVisibility(View.INVISIBLE);
if (pipeLengthVisible == true) spinnerPipeLength.setVisibility(View.VISIBLE);
else spinnerPipeLength.setVisibility(View.INVISIBLE);
//Sets up the spinnerTypeGas spinner
ArrayAdapter<CharSequence> adapterTypeGas = ArrayAdapter.createFromResource(
this, R.array.TypeGas, android.R.layout.simple_spinner_item);
adapterTypeGas.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerTypeGas.setAdapter(adapterTypeGas);
//Sets up the spinnerPipeLength spinner
ArrayAdapter<CharSequence> adapterPipeLength = ArrayAdapter.createFromResource(
this, R.array.PipeLength, android.R.layout.simple_spinner_item);
adapterPipeLength.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerPipeLength.setAdapter(adapterPipeLength);
// Listens for changes in the selected item in each spinner
spinnerTypeGas.setOnItemSelectedListener(new GASOnItemSelectedListener());
spinnerSupplyPressure.setOnItemSelectedListener(new SupplyOnItemSelectedListener());
spinnerPipeLength.setOnItemSelectedListener(new MyOnItemSelectedListener());
} // end mainProgram
public void SpinnerNatGas() {
ArrayAdapter<CharSequence> adapterSupplyPressure = ArrayAdapter.createFromResource(
this, R.array.NaturalGas, android.R.layout.simple_spinner_item);
adapterSupplyPressure.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSupplyPressure.setAdapter(adapterSupplyPressure);
adapterSupplyPressure.notifyDataSetChanged();
} // end SpinnerNatGAs ()
public void SpinnerProGas () {
ArrayAdapter<CharSequence> adapterSupplyPressure = ArrayAdapter.createFromResource(
this, R.array.PropaneGas, android.R.layout.simple_spinner_item);
adapterSupplyPressure.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSupplyPressure.setAdapter(adapterSupplyPressure);
adapterSupplyPressure.notifyDataSetChanged();
} // end SpinnerProGAs ()
public class GASOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// this prevents false firing of Toast messages
if (intSpinnerCountGas < NO_OF_EVENTS_GAS) {
intSpinnerCountGas++;
} // end if
else {
spinnerTypeGasInt = spinnerTypeGas.getSelectedItemPosition();
if(spinnerTypeGasInt == 1) {
//populate spinnerSupplyPressure accordingly
SpinnerNatGas();
} // end if
else if(spinnerTypeGasInt == 2) {
//populate spinnerSupplyPressure accordingly
SpinnerProGas();
} // end else if
if (spinnerTypeGasInt != 0) {
spinnerSupplyPressure.setVisibility(View.VISIBLE);
textViewSupplyPressure.setVisibility(View.VISIBLE);
spinnerSupplyPressure.setSelection(0);
spinnerPipeLength.setSelection(0);
supplyPressureVisible = true;
} // end else if
else {
spinnerSupplyPressure.setVisibility(View.INVISIBLE);
textViewSupplyPressure.setVisibility(View.INVISIBLE);
textViewSelectPipeLength.setVisibility(View.INVISIBLE);
spinnerPipeLength.setVisibility(View.INVISIBLE);
supplyPressureVisible = false;
pipeLengthVisible = false;
}// end else
}// end if for false Toast message at app launch
} // end onItemSelected
public void onNothingSelected(AdapterView<?> arg0) {
// nothing to do
} // end onNothingSelected
} // end class GASOnItemSelectedListener
public class SupplyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// this prevents false firing of Toast messages
if (intSpinnerCountSupply < NO_OF_EVENTS_SUPPLY) {
intSpinnerCountSupply++;
} // end if
else {
spinnerSupplyPressureInt = spinnerSupplyPressure.getSelectedItemPosition();
if (spinnerSupplyPressureInt != 0) {
textViewSelectPipeLength.setVisibility(View.VISIBLE);
spinnerPipeLength.setVisibility(View.VISIBLE);
pipeLengthVisible = true;
spinnerPipeLength.setSelection(0);
} // end if
else {
textViewSelectPipeLength.setVisibility(View.INVISIBLE);
spinnerPipeLength.setVisibility(View.INVISIBLE);
pipeLengthVisible = false;
} // end else
}// end if for false Toast message at app launch
} // end onItemSelected
public void onNothingSelected(AdapterView<?> arg0) {
// nothing to do
} // end onNothingSelected
} // end class SupplyOnItemSelectedListener
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
if (intSpinnerCountLength < NO_OF_EVENTS_LENGTH) {
intSpinnerCountLength++;
} // end if
else {
// This also gives the Row to look in the database for the CFH
baseTableRowNumber = 0;
spinnerPipeLengthInt = spinnerPipeLength.getSelectedItemPosition();
//spinnerPipeLengthText = spinnerPipeLength.getSelectedItem().toString();
// calculates the base table row number and stores it in variable baseTableRowNumber
if (spinnerTypeGasInt == 1) {// Natural Gas is selected
baseTableRowNumber = (spinnerSupplyPressureInt - 1) * 18;
}
else if (spinnerTypeGasInt == 2) { // Propane is selected
baseTableRowNumber = 198 + (spinnerSupplyPressureInt - 1) * 18;
} // end else if
showResults();
} // end else for check if firing at inializing
} // end onItemSelected
public void onNothingSelected(AdapterView<?> arg0) {
// nothing to do
} // end onNothingSelected
} // end class MyOnItemSelectedListener
public void showResults () {
if (CSSTPipeSizingActivity.cursorResult != null) {
finalRow = (baseTableRowNumber + spinnerPipeLengthInt);
if (finalRow < 0) {
finalRow = 0;
}
if (finalRow == 0) {
textViewSize15.setText(String.valueOf("0"));
textViewSize19.setText(String.valueOf("0"));
textViewSize25.setText(String.valueOf("0"));
textViewSize31.setText(String.valueOf("0"));
textViewSize37.setText(String.valueOf("0"));
textViewSize46.setText(String.valueOf("0"));
textViewSize62.setText(String.valueOf("0"));
} // end if
else {
cursorResult.moveToPosition(finalRow);
textViewSize15.setText(String.valueOf(cursorResult.getInt(1)));
textViewSize19.setText(String.valueOf(cursorResult.getInt(2)));
textViewSize25.setText(String.valueOf(cursorResult.getInt(3)));
textViewSize31.setText(String.valueOf(cursorResult.getInt(4)));
textViewSize37.setText(String.valueOf(cursorResult.getInt(5)));
textViewSize46.setText(String.valueOf(cursorResult.getInt(6)));
textViewSize62.setText(String.valueOf(cursorResult.getInt(7)));
} // end else
} // end if
} //end showResults
} // end class CSSTPipeSizingActivity
In the first three lines of the mainProgram() method I declare my three spinners and then begin to populate them. when the user selects a choice from spinnerTypeGas then the next spinner (spinnerSupplyPressure) becomes visible. then when the user selects an item from that spinnerSupplyPressure the third spinner (spinnerPipeLenght) becomes visible. Data is then displayed that is retrieved from a database. Each spinner gets its array list from the string.xml file

android-How to set the text size of list item in alert dialog

In My application one button is there when you click on that one alert dialog will be appear. that alert dialog consists of single choice list items. Here i want to set the text size of single choice list item.
is it possible? if yes how to do it.
The following is my code
sclist.java
package com.examples.scl;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class sclist extends Activity {
private static final int DIALOG_SINGLE_CHOICE = 1;
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_SINGLE_CHOICE:
return new AlertDialog.Builder(sclist.this)
.setIcon(R.drawable.alert_dialog_icon)
.setTitle("Single choice list")
.setSingleChoiceItems(R.array.select_dialog_items2, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked on a radio button do some stuff */
}
})
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked Yes so do some stuff */
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked No so do some stuff */
}
})
.create();
}
return null;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* Display a radio button group */
Button radioButton = (Button) findViewById(R.id.radio_button);
radioButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(DIALOG_SINGLE_CHOICE);
}
});
}
}
I just encountered this problem myself on a matching game I'm working on. My solution isn't simple but I wanted to use a custom font, and I didn't see an easy way to do it with the 2.2 Android interface (which is what I'm targeting). The trick is to attach an OnShowListener to the alert dialog before you show it. In that listener, get ListAdapter out of the ListView and wrap it with a proxy object that forwards all the calls except the getView. In that function, cast the View to a TextView, set the typeface and size, and return the view. Here's my code:
// Add your list with builder up here
AlertDialog alert = builder.create();
alert.setOnShowListener(new OnShowListener() {
#Override
public void onShow(DialogInterface alert) {
ListView listView = ((AlertDialog)alert).getListView();
final ListAdapter originalAdapter = listView.getAdapter();
listView.setAdapter(new ListAdapter()
{
#Override
public int getCount() {
return originalAdapter.getCount();
}
#Override
public Object getItem(int id) {
return originalAdapter.getItem(id);
}
#Override
public long getItemId(int id) {
return originalAdapter.getItemId(id);
}
#Override
public int getItemViewType(int id) {
return originalAdapter.getItemViewType(id);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = originalAdapter.getView(position, convertView, parent);
TextView textView = (TextView)view;
textView.setTypeface(MyFontUtil.getTypeface(MyActivity,MY_DEFAULT_FONT));
textView.setTextColor(Color.BLACK);
textView.setTextSize(25); // FIXIT - absolute size
return view;
}
#Override
public int getViewTypeCount() {
return originalAdapter.getViewTypeCount();
}
#Override
public boolean hasStableIds() {
return originalAdapter.hasStableIds();
}
#Override
public boolean isEmpty() {
return originalAdapter.isEmpty();
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
originalAdapter.registerDataSetObserver(observer);
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
originalAdapter.unregisterDataSetObserver(observer);
}
#Override
public boolean areAllItemsEnabled() {
return originalAdapter.areAllItemsEnabled();
}
#Override
public boolean isEnabled(int position) {
return originalAdapter.isEnabled(position);
}
});
}
});
alert.show();
If you want to see it in action look on the Android Market in a few weeks. Search for metaphyze (my publisher id). I haven't decided what to call it yet. (It's not "FlashMatch Chinese I Free". That was my first game. This is a kid's matching game. Play the game and tap the picture at the end. You'll see the AlterDialog with the style list.).
Good question. I believe you'd have to use the AlertDialog.Builder constructor that also takes a theme AlertDialog.Builder(Context context, int theme), see if you can see anything useful in that description, I've never tried it myself.

Categories

Resources