friends,
i am using following code to display list with radio buttons
now i want to select specific radio button of list by default so using setSelection property which does not work.
final String [] items=new String[]{"Item1","Item2","Item3","Item4"};
ArrayAdapter<string> ad=new ArrayAdapter<string>(this,android.R.layout.simple_list_item_single_choice,items);
list=(ListView)findViewById(R.id.List);
list.setAdapter(ad);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setSelection(2);
list.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
TextView txt=(TextView)findViewById(R.id.txt);
txt.setText(list.getItemAtPosition(arg2).toString());
}
}
);
please guide what mistake am i doing?
You'r looking for:
list.setItemChecked(2, true);
I might be completely off, but I think setSelection doesn't necessarely checks your item (as in checkbox, or radio), it navigates to it though.
As a workaround (maybe there is a more elegant solution) you can extend ArrayAdapter and set checked manually in a getView() method.
Add something like this to your class:
private static class MArrayAdapter extends ArrayAdapter<String> {
public Adapter(final Context context, final String[] objects) {
super(context, android.R.layout.simple_list_item_single_choice, objects);
}
#Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
final CheckedTextView view = (CheckedTextView) super.getView(position, convertView, parent);
view.setChecked(position == 2);
return view;
}
}
And change your way of getting an adapter to new MArrayAdapter(this, items);
P.S.
On my previous comment, my mistake, you better call setChoiceMode (it's just in my app, I call notifyDataSetChanged, so I don't really need it). I think your'r up to some weird behaviour without choice mode.
Related
I would like to change an item background color when clicked, in a simple listView. Here's my code:
boolean[] selectedItem = new boolean[listElement.length]
final ArrayList<String> list1 = new ArrayList<>();
Collections.addAll(list1, listElement);
final ListView mylist = (ListView) findViewById(R.id.listView);
final ArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, list1);
mylist.setAdapter(adapter);
mylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
int firstVisiblePosition = mylist.getFirstVisiblePosition();
int effectivePosition = pos - firstVisiblePosition;
if (!selectedItem[pos]) {
mylist.getChildAt(effectivePosition).setBackgroundColor(Color.parseColor("#66F44336"));
} else {
mylist.getChildAt(effectivePosition).setBackgroundColor(Color.parseColor("#EEEEEE"));
}
selectedItem[pos] = !selectedItem[pos];
}
});
When the list is short (no scroll involved) it works, when it's long it does not: the background color of the clicked item does change, but when I start to scroll the background color of every item starts to change, and I can't find any logic in those changes, they change and reverse without me even touching them, just by scrolling, wich is strange since the color should only change when onItemClick() is called, right? What am I missing?
You're missing the point that the ListView re-uses its item layouts when they go out of screen (i.e. you scroll the list).
You need to save the background for each of your item and set it once the view is requested. That happens inside of ListView adapter's getView.
A quick fix would be to use a custom adapter on the go:
final boolean[] selectedItem = new boolean[listElement.length];
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,
android.R.layout.simple_list_item_1, list1) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
if (selectedItem[position]) {
view.setBackgroundColor(Color.parseColor("#66F44336"));
} else {
view.setBackgroundColor(Color.parseColor("#EEEEEE"));
}
return view;
}
};
This lacks error checking but you should get the idea. Good luck!
SOLVED HERE IS THE SOLUTION ANSWER http://www.congdegnu.es/2011/06/02/spinners-en-android-tres-formas-de-poblarlos/
I'm populating a spinner from my sqlite database like this:
Cursor CS = newDB.rawQuery("Select ID AS _id, Name from Schools",null);
CS.moveToFirst();
do{
Schools.add(CS.getString(CS.getColumnIndex("_id")));
} while(CS.moveToNext());
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,Schools);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
My problem is that I only add an id but how can I add a value to that id so when the value get select I get the id ?
I think that "schools" is an array containing you own class "school".
You could add a propertie which contains the information.
Or you could use a 2 dimensional array.
Than you have to set up your arrayadapter to get the information (getter Method).
Hope it helps
Try Cursor Adapter
or
Take a global variable
Hashmap schoolmap=new Hashmap();
While inserting data to the list also add to Hashmap like this
CS.moveToFirst();
do{
Schools.add(CS.getString(CS.getColumnIndex("_id")));
schoolmap.put(CS.getString(CS.getColumnIndex("_id")),CS.getColumnIndex("_id"))
} while(CS.moveToNext());
onSpinner item click get the value like this
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
String value=((TextView)view).getText();
int id=Integer.parseInt(schoolmap.get(value));
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
Take a look at using a SimpleCursorAdapter for your spinner instead. Although this has been deprecated since API-11, so you may also want to think about using a LoaderManager with a CursorLoader.
An explanation on how to transition to a LoaderManager and CursorLoader can be found here:
How to transition from managedQuery to LoaderManager/CursorLoader?
I would recommend you start by using the SimpleCursorAdapter, then if confortable enough, move on to the other method.
1) Create an ArrayList<School>
2) Add all your Schools to the Arraylist
3) Create a custom adapter like this:
public class SchoolAdapter extends ArrayAdapter<School>{
public SchoolAdapter(Context ctx, List<School> schools){
super(ctx, 0, schools);
}
#Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
TextView tv;
if (convertView == null){
tv = new TextView(getContext());
} else {
tv = (TextView) convertView;
}
tv.setTextSize(16);
final School school = getItem(position);
tv.setText(school.toString());
return tv;
}
}
4) Use this in your activity:
final SchoolAdapter adapter = new SchoolAdapter(this, schools);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
School school = adapter.getItem(pos);
// Do whatever you want with your school
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
I have an app that has a SimpleCursorAdapter. I can get the content of the DB table to show up in the list but i'd like to do something when the item in the list is clicked. When i go to source in eclipse and try to override a clickListener there is nothing to override. I'm looking for a method to override like onListitemClick. How would i do ths?
Eclipse is also complain about the method onListItemClick, sayimg that it must override or implement a supertype method. If i delete the #Override annotation then that error goes, the list is displayed but no event is fired from touching an item in the list.
private class MyAdapter extends SimpleCursorAdapter {
public MyAdapter(Context context, int layout, Cursor c, String[] from,
int[] to) {
super(context, layout, c, from, to);
}
#Override
public
View getView(int position, View convertView, ViewGroup parent) {
Log.e(TAG, "inside myadapter getview");
View v = super.getView(position, convertView, parent);
if(v == null)
return null;
Cursor c = (Cursor)getItem(position);
String phoneName = c.getString(c.getColumnIndex(LoginValidate.C_PHONE_NAME));
String phoneNumber = c.getString(c.getColumnIndex(LoginValidate.C_PHONE_NUMBER));
((TextView)v.findViewById(R.id.phonename)).setText(phoneName );
((TextView)v.findViewById(R.id.phonenumber)).setText(phoneNumber);
((TextView)v.findViewById(R.id.phonename)).setTextColor(Color.BLACK);
((TextView)v.findViewById(R.id.phonenumber)).setTextColor(Color.BLACK);
return v;
}
}// end of adapter
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Log.e(TAG, "clicked an item in list");
}
The adapter doesn't have an onListItemClick() method by default, which is why the annotation is bothering it.
You have to tie in the onListItemClick() to the listView... try using it by
ListView list;
list.setOnListItemClick(listAdapter); //if your adapter implements OnListItemListener
or just like this
list.setOnListItemClickListener(new OnListItemClickListener()
{
#override
public void onClick(args)
{
listAdapter.onListItemClick(args); //you will want this to be the first or the last call here
//maybe some other stuff if you want here
}
}
and that should do it.
To sum up:
1) either implement the correct interface in your adapter and it will require the override annotation
2) leave the method exposed in the adapter and call it from a private onListItemClickListener attached to the listview.
Yes turtleboy,
you can do this by overriding a method in you Activity where the listview is placed.
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View arg1, int position, long arg3) {
//do what you want to do
}
});
I've a ListView and when the user clicks on one of its items I want that item to become blue. In order to do this, in the onCreate() method of the ListView activity, I've set a listener for the user clicks.
m_listFile=(ListView)findViewById(R.id.ListView01);
m_listFile.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
arg0.getChildAt(arg2).setBackgroundColor(Color.BLUE);
}
});
Everything works fine for the first visible items, but when I scroll the list, I've a
NullPointerException at arg0.getChildAt(arg2).setBackgroundColor(...), even if the arg2 value has the right item index position.
My ListView has a two lines item structure, when I load the ListView I use this adapter:
SimpleAdapter sa = new SimpleAdapter(
getApplicationContext(),
expsList,
R.layout.listelement,
new String[] { "screen_name","text" },
new int[] { R.id.Name, R.id.Value}) {
};
m_listFile.setAdapter(sa);
I don't understand how to solve this problem. Can I get some help?
You could extend SimpleAdapter like this:
private class MyAdapter extends SimpleAdapter {
public MyAdapter(Context context, List<? extends Map<String, ?>> data,
int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
v.setBackgroundColor(Color.BLACK); //or whatever is your default color
//if the position exists in that list the you must set the background to BLUE
if(pos!=null){
if (pos.contains(position)) {
v.setBackgroundColor(Color.BLUE);
}
}
return v;
}
}
Then in your activity add a field like this:
//this will hold the cliked position of the ListView
ArrayList<Integer> pos = new ArrayList<Integer>();
and set the adapter:
sa = new MyAdapter(
getApplicationContext(),
expsList,
R.layout.listelement,
new String[] { "screen_name","text" },
new int[] { R.id.Name, R.id.Value}) {
};
m_listFile.setAdapter(sa);
When you click the row:
public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
// check before we add the position to the list of clicked positions if it isn't already set
if (!pos.contains(position)) {
pos.add(position); //add the position of the clicked row
}
sa.notifyDataSetChanged(); //notify the adapter of the change
}
I guess you should use
arg0.getItemAtPosition(arg2).setBackgroundColor(Color.BLUE);
instead of
arg0.getChildAt(arg2).setBackgroundColor(Color.BLUE);
it is what the Android Developer Reference says here
I have created a spinner and the items of spinner comes from database. However, When I use
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
typeOFBCard = contactSpinner.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
When I call this listener and try to pick the chosen string of the spinner i get a reference of the sglite something like:
android.database.sqlite.SQLiteCursor#40535568
This is the return value of typeOfBCard.
However, on the spinner I can see normal string like "Work".
Here is how I initialized the spinner :
contactSpinner = (Spinner) findViewById(R.id.contactSpinner);
mobileText =(EditText) findViewById(R.id.mobileText);
mDbHelper = new DbAdapter(this);
mDbHelper.open();
cursor = mDbHelper.fetchAllBusinessCards();
startManagingCursor(cursor);
context =this;
contactSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
How ever on the spinner I can see normal string like "Work"
That is because you configured an Adapter on the Spinner, and the Adapter is pulling data out of the Cursor to display.
How to get spinner string value on android?
There is no "spinner string value". Spinners don't have strings. They have views. Those views might be instances of TextView, or they might be instances of ImageView, or they might be instances of a LinearLayout holding onto a TextView and an ImageView, or...
If you want to get data out of the Cursor, call getString() on the Cursor.
Every row in a spinner is a view but it's also a value/object from your source.
Try
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
// Parent == where the click happened.
typeOFBCard = parent.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}