the adapter works fine, but i don't understand why the position in OnItemClick is always "0"
String[] regions = ct.getRegions();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, regions);
regionT.setAdapter(adapter);
regionT.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
int pos=position;
}
});
Don't ask me why, but the argument position in method OnItemClickListener.onItemClick holds the index relative to the AutoCompleteTextView's dropdown list, not the position in your adapter array (in your case regions)!
So, to find the item's real position you must get the string selected in the dropdown and find its index in the adapter array:
String[] regions = ct.getRegions();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, regions);
regionT.setAdapter(adapter);
regionT.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selected = (String) parent.getItemAtPosition(position);
int pos = Arrays.asList(regions).indexOf(selected);
}
});
I had the same issue: I couldn't manage to get the position, but I've figured out how to retrieve the whole object selected by the user (if any), having an ID field, which in my case is all I need.
The trick is not to use an ArrayAdapter<String> for the suggested items, but an ArrayAdapter<MyObject>, where MyObject overrides the toString() method.
For instance:
public class Country extends Object {
public int id;
public Country(int id) {
this.id = id;
}
#NonNull
#Override
public String toString() {
switch (id) {
case 0:
return "Albania";
case 1:
return "Romania";
case 2:
return "Ucraina";
case 3:
return "Russia";
default:
return "Unknwon";
}
}
}
...
private AutoCompleteTextView mNationAtv;
private Button mTestBtn;
private final Country[] COUNTRIES = {
new Country(0),
new Country(1),
new Country(2),
new Country(3)
};
...
// use object array for adapter
ArrayAdapter<Country> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_dropdown_item_1line, COUNTRIES);
mNationAtv.setAdapter(adapter);
mTestBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ArrayAdapter<Country> ada = (ArrayAdapter<Country>) mNationAtv.getAdapter();
int nItems = ada.getCount();
// default Country unknown
Country selItem = new Country(5);
if (nItems > 0) {
selItem = (Country) ada.getItem(0);
}
Log.d(TAG,
"onClick(): nItems=" + nItems + ", selItem.name=" + selItem.toString()
+ ", selItem.id=" + selItem.id);
}
});
...
Logs:
when the AutocompleteTextView value matches an item in the dropdown:
onClick(): nItems=1, selItem.name=Ucraina, selItem.id=2
when the value is blank:
onClick(): nItems=4, selItem.name=Albania, selItem.id=0
when the value isn't blank but doesn't match any item in the dropdown:
onClick(): nItems=0, selItem.name=Unknown, selItem.id=5
You might want to fetch this value in the OnItemClickListener()::onItemClick() method, invoked avery time the user clicks an item in the dropdown, or outside of it, i.e. for validation.
I put this in a simple example and it works correctly for me. See below:
package com.example.autocompletetv;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
public class AutoCompleteActivity extends ListActivity {
public static final String TAG = AutoCompleteActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_complete);
String[] regions = {"One", "Two", "Three", "Four", "Five"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, regions);
this.setListAdapter(adapter);
this.getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i(TAG, "postion was " + position);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.auto_complete, menu);
return true;
}
}
When I click I get:
12-09 19:13:30.617: I/AutoCompleteActivity(1883): postion was 2
12-09 19:13:31.997: I/AutoCompleteActivity(1883): postion was 3
12-09 19:13:34.687: I/AutoCompleteActivity(1883): postion was 4
12-09 19:13:37.028: I/AutoCompleteActivity(1883): postion was 0
Related
I want the onItemClickListener always works, but after it works for the first time, it doesn't work anymore.
This is my code in MainActivity.java
Please help, I can't seem to find problem.
Thank you
package com.noval.tugas_5;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
private ListView listView1;
private CustomAdapter adapter;
private final String[] textString = new String[]{"Game", "Genre Film", "Jenis Musik", "Mobil", "Motor", "Makanan", "Exit"};
private final String[] textStringGame = new String[]{"Mobile Legends", "Clash of Clans", "Dota II", "Call of Duty", "Masuk ke Jenis Musik", "Menu Utama"};
private final int[] drawableIds = new int[]{R.drawable.utama1, R.drawable.utama2, R.drawable.utama3,
R.drawable.utama4, R.drawable.utama5, R.drawable.utama6, R.drawable.exit};
private final int[] drawableIdsGame = new int[]{R.drawable.utama1, R.drawable.utama2, R.drawable.utama3,
R.drawable.utama4, R.drawable.utama5, R.drawable.exit};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView1 = (ListView) findViewById(R.id.menuList);
adapter = new CustomAdapter(MainActivity.this, textString, drawableIds);
listView1.setAdapter(adapter);
// membuat event click
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int posisi, long id) {
// Get the item that was clicked
// Menangkap nilai text yang diklik
Object o = adapter.getItem(posisi);
String pilihan = o.toString();
if (pilihan.equals("Game")) {
CustomAdapter adapter = new CustomAdapter(MainActivity.this, textStringGame, drawableIdsGame);
listView1.setAdapter(adapter);
} else if (pilihan.equals("Exit")) {
finish();
System.exit(0);
} else if (pilihan.equals("Menu Utama")) {
CustomAdapter adapter = new CustomAdapter(MainActivity.this, textString, drawableIds);
listView1.setAdapter(adapter);
}
}
});
}
}
I already try to find out what happen for hours.
You are doing it wrong.
listView onItemClickListener gets overwritten every time you modify the list adapter. So you have to initialize it every time you update the adapter.
You can do it recursively by using something like this -
public void initAdapter(ListView listview , CustomAdapter adapter){
listView.setAdapter(adapter);
// membuat event click
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int posisi, long id) {
// Get the item that was clicked
// Menangkap nilai text yang diklik
Object o = adapter.getItem(posisi);
String pilihan = o.toString();
if (pilihan.equals("Game")) {
CustomAdapter adapter = new CustomAdapter(MainActivity.this, textStringGame, drawableIdsGame);
initAdapter(listView,adapter);
} else if (pilihan.equals("Exit")) {
finish();
System.exit(0);
} else if (pilihan.equals("Menu Utama")) {
CustomAdapter adapter = new CustomAdapter(MainActivity.this, textString, drawableIds);
initAdapter(listView,adapter);
}//Add more options here
}
});
}
after adding the method, replace this entire code
listView1.setAdapter(adapter);
// membuat event click
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//your code ...
}
});
to this -
initAdapter(listView1,adapter);
Happy Coding!
please I'm trying to add understand how to add onItemClickListener to the followng code such that when "Smartphone Plans" is clicked, its activity starts and so on. I've seen other questions on StackOverflow relating to this question but do not understand how to go about them.
I've already added an onItemClickListener but do not understand how to set it to specific list items.
here is the code
package devchuks.com.rechargeit;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.app.ListActivity;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class EtisalatData extends AppCompatActivity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_etisalat_data);
listView = (ListView) findViewById(R.id.list);
String[] values = new String[] {
"Smartphone Plans",
"Internet Bundles",
"Weekend Plans",
};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
}
You can define your listView.setOnItemClickListener like this to go to different activity for clicking different element.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String item = listView.getItemAtPosition(position);
Toast.makeText(this,"You selected : " + item,Toast.LENGTH_SHORT).show();
if(position==0) {
// Do your code for clicking "Smartphone Plans" example
// startActivity(new Intent(getApplicationContext(),SmartphonePlans.class));
}
else if(position==1) {
// Do your code for clicking "Internet Bundles". example
// startActivity(new Intent(getApplicationContext(),InternetBundles.class));
}
else if(position==2) {
// Do your code for clicking "Weekend Plans". example
//startActivity(new Intent(getApplicationContext(),WeekendPlans.class));*/
}
});
onItemClick will be called whenever any of the list items are clicked. The position will be the position of the view in the Adapter.
Please refer -
How to handle the click event in Listview in android?
Thanks
Sriram
try this:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String text = values[position];
if(text.equals("Smartphone Plans")){ //your specific list item text
Intent i = new Intent(MainActivity.this, AnotherActivity.class);
i.putExtra("TEXT", text);
startActivity(i);
}
}
}
If this helps and is your concern
`
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String data = values[position];
switch(data){
case "Smartphone Plans":
// do somwthing
break;
// similarly for other two values.
}
}
});`
Below method give you a position of a clicked row. Take advantage of that and value from your array.
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Move your values array to member array or make it final to use
// in Anonymous class
final String selectedValue = values[position];
Intent intent = null
// Now add case and start activity
if("Smartphone Plans".equals(selectedValue)) {
intent = new Intent(EtisalatData.this, SmartPhonePlan.class);
}
else if("other Plans".equals(selectedValue)){
// other action
}
//... more cases and at the end start your activity if its not null
startActivity(intent);
}
I've created an array list and display it in a list view with simple list item multiple choice but i cannot check or tick the items on the list, when i click on the items nothing happens. Please check my code below and tell me what i am doing wrong.
package com.example.arrays;
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;
public class MainActivity extends Activity {
ListView showList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView show = (TextView)findViewById(R.id.txtShow);
final Random generate = new Random();
showList = (ListView)findViewById(R.id.listView1);
final String[] myAttraction = new String[4];
myAttraction[0]= "Walter Sisulu National Botanical Garden ";
myAttraction[1]= "Coca-Cola Dome";
myAttraction[2]= "Promusica Theatre";
myAttraction[3]= "Unisa Science Campus";
Button arrays = (Button)findViewById(R.id.button1);
arrays.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*int random = generate.nextInt(4);
String display = myAttraction[random];
show.setText(display);*/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_multiple_choice, myAttraction);
showList.setAdapter(adapter);
}
});
showList.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "long clicked pos: " + pos, Toast.LENGTH_LONG).show();
return true;
}
});
}
#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;
}
}
Add a OnItemClickListener like this to check/uncheck the CheckedTextView when user click on an item
showList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// change the checkbox state
CheckedTextView checkedTextView = ((CheckedTextView)view);
checkedTextView.setChecked(!checkedTextView.isChecked());
}
});
change your code as following....
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_multiple_choice, myAttraction);
showList.setAdapter(adapter);
arrays.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*int random = generate.nextInt(4);
String display = myAttraction[random];
show.setText(display);*/
}
});
showList.setOnItemClickListener(new OnItemClickListener() {
public boolean onItemClick(AdapterView<?> arg0, View arg1, int pos, long id) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "long clicked pos: " + pos, Toast.LENGTH_LONG).show();
return true;
}
});
Set choiceMode property of your list to multipleChoice. I'm implementing multiple choice list in such a way in my applications, and it surely works.
Change this
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_multiple_choice, myAttraction);
showList.setAdapter(adapter);
To this
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_multiple_choice, myAttraction);
showList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
showList.setAdapter(adapter);
Just Add this line if you have a ListView and have selected simple_list_item_multiple_choice and you are unable to interact with the checkbox.
YourListViewName.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
How to use ActionBarActivity of "android-support-v7-appcompat" in the activity which Extends the ListActivity.
For Example I have an Activity
public class xxxxxListActivity
extends ListActivity implements OnItemSelectedListener {
// ...................
}
In the above activity i want to use "ActionBarActivity" but as java dosent support multiple inheritance I am not able to get it working.
Here's an implementation of ActionBarListActivity:
public abstract class ActionBarListActivity extends ActionBarActivity {
private ListView mListView;
protected ListView getListView() {
if (mListView == null) {
mListView = (ListView) findViewById(android.R.id.list);
}
return mListView;
}
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
protected ListAdapter getListAdapter() {
ListAdapter adapter = getListView().getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
} else {
return adapter;
}
}
}
Just like regular ListActivity, you'll need a layout that contains a ListView with the ID android.R.id.list ("#android:id/list" in XML).
The spiel in getListAdapter() is to handle cases where header views have been added to the ListView. Seems like ListView sets its own adapter to a HeaderViewListAdapter, so we have to try and get the wrapped adapter to prevent casting errors.
Edit: Try adding this function to satisfy the need for onListItemClick:
protected void onListItemClick(ListView lv, View v, int position, long id) {
getListView().getOnItemClickListener().onItemClick(lv, v, position, id);
}
Maybe you can try to extend ActionBarActivity and for default layout for that activity set some layout that has ListView.
Something like this:
public class AlarmListActivity extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_with_list_view);
ListView lv = (ListView) findViewById(R.id.listView1);
// populate list view
}
}
and correcponding layout file:
<LinearLayout>
<ListView
android:id="#+id/listView1">
</ListView>
</LinearLayout>
Instead of creating the layout in XML, I decided to do it in code. The file a is a single drop in replacement in your code.
package com.stackoverflow.free.examples;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TableRow;
import android.widget.TextView;
/**
* based of https://raw.githubusercontent.com/android/platform_frameworks_base/d6c1919779acb042392615637b9007e0c4b89023/core/java/android/app/ListActivity.java
* Created by elcuco on 5/27/2014.
*/
#SuppressWarnings("UnusedDeclaration")
public class SupportListActivity extends ActionBarActivity {
protected ListAdapter mAdapter;
protected ListView mList;
protected TextView mEmptyMessage;
#Override
protected void onCreate(Bundle savedBundle)
{
super.onCreate(savedBundle);
mEmptyMessage = new TextView(this);
mEmptyMessage.setText("No results");
mList = new ListView(this);
mList.setEmptyView(mEmptyMessage);
LinearLayout ll = new LinearLayout(this);
ll.addView(mEmptyMessage, TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT);
ll.addView(mList, TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT);
setContentView(ll);
}
public void setListAdapter(ListAdapter adapter) {
synchronized (this) {
mAdapter = adapter;
mList.setAdapter(adapter);
}
}
/**
* Get the activity's list view widget.
*/
public ListView getListView() {
return mList;
}
/**
* Set the currently selected list item to the specified
* position with the adapter's data
*
* #param position the position on list to select
*/
public void setSelection(int position) {
mList.setSelection(position);
}
/**
* Get the position of the currently selected list item.
*/
public int getSelectedItemPosition() {
return mList.getSelectedItemPosition();
}
/**
* Get the cursor row ID of the currently selected list item.
*/
public long getSelectedItemId() {
return mList.getSelectedItemId();
}
private AdapterView.OnItemClickListener mOnClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
onListItemClick((ListView)parent, v, position, id);
}
};
/**
* This method will be called when an item in the list is selected.
* Subclasses should override. Subclasses can call
* getListView().getItemAtPosition(position) if they need to access the
* data associated with the selected item.
*
* #param l The ListView where the click happened
* #param v The view that was clicked within the ListView
* #param position The position of the view in the list
* #param id The row id of the item that was clicked
*/
protected void onListItemClick(ListView l, View v, int position, long id) {
}
}
my answer based on accepted one, and also contains onListItemClick implementation. But it has a problem with empty view.
public abstract class ActionBarListActivity extends ActionBarActivity {
private ListView mListView;
protected ListView getListView() {
if (mListView == null) {
mListView = (ListView) findViewById(android.R.id.list);
mListView.setOnItemClickListener(mOnClickListener);
}
return mListView;
}
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
protected ListAdapter getListAdapter() {
ListAdapter adapter = getListView().getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
return ((HeaderViewListAdapter) adapter).getWrappedAdapter();
} else {
return adapter;
}
}
protected void onListItemClick(ListView l, View v, int position, long id) { }
private AdapterView.OnItemClickListener mOnClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
onListItemClick((ListView) parent, v, position, id);
}
};
}
This solution is based on the accepted solution by #patrick. Here is the full code:
First the XML layout file activity_main.xml. Notice that I have an ListView with ID entryList
<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="com.example.MainActivity" >
<ListView
android:id="#+id/entryList"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ListView>
</RelativeLayout>
Next is my own ActionBarListActivity. You'd notice some changes. I wanted to make it generic and reusable as possible.
package com.example.api;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.HeaderViewListAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
public abstract class ActionBarListActivity extends ActionBarActivity {
private final class ListOnItemClickListener implements OnItemClickListener {
public void onItemClick(AdapterView<?> lv, View v, int position, long id) {
onListItemClick((ListView) lv, v, position, id);
// String str = ((TextView) arg1).getText().toString();
// Toast.makeText(getBaseContext(), str,
// Toast.LENGTH_LONG).show();
// Intent intent = new Intent(getBaseContext(),
// your_new_Intent.class);
// intent.putExtra("list_view_value", str);
// startActivity(intent);
}
}
private ListView mListView;
protected ListView getListView() {
if (mListView == null) {
initListView();
}
return mListView;
}
private void initListView() {
mListView = (ListView) findViewById(getListViewId());
if (mListView == null) {
throw new RuntimeException(
"ListView cannot be null. Please set a valid ListViewId");
}
mListView.setOnItemClickListener(new ListOnItemClickListener());
}
protected abstract int getListViewId();
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
protected void onListItemClick(ListView lv, View v, int position, long id) {
// No default functionality. To override
}
protected ListAdapter getListAdapter() {
ListAdapter adapter = getListView().getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
return ((HeaderViewListAdapter) adapter).getWrappedAdapter();
} else {
return adapter;
}
}
}
Next is my MainActivity extending the above class.
package com.example;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.example.api.ActionBarListActivity;
public class MainActivity extends ActionBarListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
#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;
}
#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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Log.d("click", "Position click " + position);
String item = (String) getListAdapter().getItem(position);
Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
}
#Override
protected int getListViewId() {
return R.id.entryList;
}
}
Basically, by overriding onListItemClick() you can say what to do when user accepts something.
Let me know your thoughts/issues in the comments.
Cheers
Add following line of code to your class and make sure that the class implements AdapterView.OnItemClickListener:
getListView().setOnItemClickListener(this);
I am very new to android. I want to use 2 spinners in my application, one shows the countries list, when any country is selected the other spinner should show the list of cities of that country. when city is selected some action is performed. plz help me with some sample code. thanks in anticipation
Here is something what we can use to add options to spinner2 w.r.t to spinner 1.
public class Activity extends Activity implements View.OnClickListener
{
private Spinner spinner0, spinner1, spinner2, spinner3;
private Button submit, cancel;
private String country[], state[], city[], area[];
Australia aus = new Australia();
Object object;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinner0 = (Spinner)findViewById(R.id.spinnerCountry);
spinner1 = (Spinner)findViewById(R.id.spinnerQ1);
spinner2 = (Spinner)findViewById(R.id.spinnerQ2);
spinner3 = (Spinner)findViewById(R.id.spinnerQ3);
submit = (Button)findViewById(R.id.btnSubmit);
cancel = (Button)findViewById(R.id.btnCancel);
submit.setOnClickListener(this);
cancel.setOnClickListener(this);
country = new String[] {"Select Country", "Australia", "USA", "UK", "New Zealand", "EU", "Europe", "China", "Hong Kong",
"India", "Malaysia", "Canada", "International", "Asia", "Africa"};
ArrayAdapter<String> adapter0 = new ArrayAdapter<String>(Activity.this, android.R.layout.simple_spinner_item, country);
adapter0.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner0.setAdapter(adapter0);
Log.i("AAA","spinner0");
spinner0.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View view1, int pos, long id)
{
Log.i("AAA","OnItemSelected");
int loc;
loc = pos;
switch (loc)
{
case 1:
state = aus.getState();
object = aus;
Log.i("AAA","ArrayAdapter1");
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(Activity.this, android.R.layout.simple_spinner_item, state);
adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner1.setAdapter(adapter1); Log.i("AAA","spinner1");
break;
default:
Log.i("AAA","default 0");
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg1)
{
Log.i("AAA","Nothing S0");
}
});
spinner1.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View view1, int pos, long id)
{
Log.i("AAA","OnItemSelected S1");
int loc = pos;
switch(loc)
{
case 1:
Log.i("AAA","Australia");
if(object.equals(aus))
{
city = aus.getType(loc);
}
else
{
break;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Activity.this, android.R.layout.simple_spinner_item, city);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner2.setAdapter(adapter); Log.i("AAA","spinner2");
break;
default:
Log.i("AAA", "default 1");
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
Log.i("AAA","Nothing S1");
}
});
spinner2.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long id)
{
int loc = pos;
switch (loc)
{
case 1:
if(object.equals(aus))
{
area = aus.getTitle(loc);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Activity.this, android.R.layout.simple_spinner_item, area);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner3.setAdapter(adapter); Log.i("","spinner3");
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
}// on-create
#Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.btnSubmit:
break;
case R.id.btnCancel:
finish();
break;
default:
break;
}
}
}
If you find this useful, then do give it up vote, so that others can find a good answer easily.
For each Country, you have to create a class for it, to just add State, City & Area. So that it doesn't become a mesh at a single at single page.
Have fun.
Regards,
Haps.
Here is a sample code which depicts the usage of spinner and action performed when spinner item is selected
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
public class MainActivity extends Activity {
Spinner spin;
String spin_val;
String[] gender = { "Male", "Female" };//array of strings used to populate the spinner
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);//setting layout
spin = (Spinner) findViewById(R.id.spinner_id);//fetching view's id
//Register a callback to be invoked when an item in this AdapterView has been selected
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
// TODO Auto-generated method stub
spin_val = gender[position];//saving the value selected
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
//setting array adaptors to spinners
//ArrayAdapter is a BaseAdapter that is backed by an array of arbitrary objects
ArrayAdapter<String> spin_adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, gender);
// setting adapteers to spinners
spin.setAdapter(spin_adapter);
}
}
To add a list of values to the spinner, you then need to specify a SpinnerAdapter in your Activity, which extends Adapter class.. A spinner adapter allows to define two different views: one that shows the data in the spinner itself and one that shows the data in the drop down list when the spinner is pressed.You can also download & refer to the complete spinner_demo example project for better understanding.
Check the following examples :
https://developer.android.com/guide/tutorials/views/hello-spinner.html
http://www.designerandroid.com/?cat=4