set onClickListener for spinner item? - android

I have spinner which populates from database:
catSpinner = (Spinner) findViewById(R.id.spinner1);
cursor = dataAdapter.getAllCategory();
startManagingCursor(cursor);
String[] from = new String[] { DataAdapter.CATEGORY_COL_NAME };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter catAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_dropdown_item, cursor, from,to, 0);
catAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
catAdapter.notifyDataSetChanged();
catSpinner.setAdapter(catAdapter);
And I want to call AlertDialog when I select last item(Add new category...).
After I added new category I want that "item(Add new category...)" was the last again.
How I can do this?

You SHOULD NOT call OnItemClickListener on a spinner. A Spinner does not support item click events. Calling this method will raise an Exception. Check this.
You can apply OnItemSelectedListener instead.
Edit :
spinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
String selectedItem = parent.getItemAtPosition(position).toString();
if(selectedItem.equals("Add new category"))
{
// do your stuff
}
} // to close the onItemSelected
public void onNothingSelected(AdapterView<?> parent)
{
}
});
As far as adding "Add new category" to the end of the list is concerned, I think you should better go for custom adapter in which after adding all your items, you can add that constant ("Add new category") to end of array so that it should come last always.

Hook to OnItemClickListener of Spinner. Then check whether the selected item is "Add new category".
If yes, show the dialog to add the new item.
While adding the new item,
Remove the last item "Add new category".
Add the new category entered.
Then Add the item "Add new category" again.
This will make the "Add new category" item as last one.
Code Sample :
layout main.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="10" >
<Spinner
android:id="#+id/cmbNames"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
layout spinner_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Activity class :
public class MainActivity extends Activity {
private static final String NAME = "name";
private static final String ADD_NEW_ITEM = "Add New Item";
private SimpleAdapter adapter;
private Spinner cmbNames;
private List<HashMap<String, String>> lstNames;
private int counter;
private OnItemSelectedListener itemSelectedListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
HashMap<String, String> map = lstNames.get(arg2);
String name = map.get(NAME);
if (name.equalsIgnoreCase(ADD_NEW_ITEM)) {
lstNames.remove(map);
counter++;
addNewName(String.valueOf(counter));
addNewName(ADD_NEW_ITEM);
adapter.notifyDataSetChanged();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
populateList();
cmbNames = (Spinner) findViewById(R.id.cmbNames);
adapter = new SimpleAdapter(this, lstNames, R.layout.spinner_item,
new String[] { NAME }, new int[] { R.id.tvName });
cmbNames.setAdapter(adapter);
cmbNames.setOnItemSelectedListener(itemSelectedListener);
}
private void populateList() {
lstNames = new ArrayList<HashMap<String, String>>();
addNewName("abc");
addNewName("pqr");
addNewName("xyz");
addNewName(ADD_NEW_ITEM);
}
private void addNewName(String name) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(NAME, name);
lstNames.add(map);
}
}

Related

error with AutoCompleteTextView on choosing Item

I am working with auto Complete Text View. when I choose item from it, it is displaying first Item instead of showing selected item.
here is my code
Utilities.setAutoCompleteTextViewAdapter(this, districtsNameList, district);
district.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
//selectedDistrict = (String) adapterView.getItemAtPosition(position);
selectedDistrict = districtsNameList.get(position);
Log.d("tag","============positioj===="+position)
Log.d("tag", "22222222222222222222222222===" + selectedDistrict);
district.setText(selectedDistrict);
}
});
and it is the adapter Method
public static void setAutoCompleteTextViewAdapter(Context context, ArrayList<String> arrayList,
AutoCompleteTextView autoCompleteTextView) {
int layoutItemId = android.R.layout.simple_dropdown_item_1line;
ArrayAdapter<String> adapter = new ArrayAdapter<>(context, layoutItemId, arrayList);
autoCompleteTextView.setAdapter(adapter);
autoCompleteTextView.setThreshold(0);
}
// have you increased the size of Threshold
public static void setAutoCompleteTextViewAdapter(Context context, ArrayList<String> arrayList,
AutoCompleteTextView autoCompleteTextView) {
int layoutItemId = android.R.layout.simple_dropdown_item_1line;
ArrayAdapter<String> adapter = new ArrayAdapter<>(context, layoutItemId, arrayList);
autoCompleteTextView.setAdapter(adapter);
// here you have to change the code
autoCompleteTextView.setThreshold(3);
}
Make Custom textview for show selected item text, have look
list_view_row.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp" >
<TextView
android:id="#+id/textViewItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="Item name here..."
android:textSize="15dp" />
</RelativeLayout>
now set adapter like this:
myAdapter = new YourAdapter(this, R.layout.list_view_row_item, list);
myAutoComplete.setAdapter(myAdapter);
Now implement itemClick listener like this:
myAutoCompleteText.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View arg1, int pos, long id) {
RelativeLayout rl = (RelativeLayout) arg1;
TextView tv = (TextView) rl.getChildAt(0);
myAutoComplete.setText(tv.getText().toString());
}
});

custom spinner with last item as a link

I want a Spinner which contains last Item as "Add more items"
and when i click on it, then i can add next item. The item i have added should get displayed in spinner list and will have same last item as "Add more items"..
I tried using Adapter but how can i keep last element as "Add more items"
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position == spinner.getItemIdAtPosition(spinner.getCount()))
// my code for adding item to list using Adapter
else
// spinner.setSelection();
}
did i wrote anything wrong??
any help??..Thanks ...
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:dropDownVerticalOffset="2dp"
android:dropDownWidth="500sp"
android:spinnerMode="dropdown" />
</RelativeLayout>
MainActivity.java :
public class MainActivity extends Activity {
private Spinner spinner;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<String> data = new ArrayList<String>();
for (int i = 0; i < 5; i++) {
data.add("item " + i);
}
data.add("Add New Item");
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, data);
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
tv.setText(spinner.getSelectedItem().toString());
if (spinner.getSelectedItem().toString().equals("Add New Item")) {
data.remove(position);
data.add(position, "item " + position);
data.add((position + 1), "Add New Item");
updateAdapter(data);
Toast.makeText(getApplicationContext(), "item " + position,
Toast.LENGTH_LONG).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
public void updateAdapter(ArrayList<String> data) {
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,
data);
adapter.notifyDataSetChanged();
}
}

Change Image of Imageview onItemClickListener of ListView in android

I am using Custom ListView to show image and text and that is using Cursor. Now, onItemClickListener(), I want to change Image of ImageView and I also want to change textColor of TextView. And I want to disable that Item from click on which user Click. I have tried several things but none of them worked.
How to do this ?
XML Code:
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/queimg"
android:src="#drawable/ic_answer" />
<TextView
android:id="#+id/option"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="14dp"
android:layout_toRightOf="#+id/icon"
android:text="hello" />
Java Code :
final List<String> lstOption = new ArrayList<String>();
ArrayList<Map<String, String>> arrlist = new ArrayList<Map<String, String>>();
Map<String, String> m = null;
if (option != null) {
if (option.moveToFirst()) {
do {
lstOption.add(option.getString(option
.getColumnIndex("Option")));
m = new HashMap<String, String>();
m.put("option",
option.getString(option.getColumnIndex("Option")));
arrlist.add(m);
} while (option.moveToNext());
}
}
SimpleAdapter adapter = new SimpleAdapter(this, arrlist,
R.layout.topicwisequestion, new String[] { "option" },
new int[] { R.id.option });
lvTWOptions.setAdapter(adapter);
lvTWOptions.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selection[position] = true;
((ImageView)view.findViewById(R.id.icon)).setImageResource(R.drawable.yourImageResourceId);
((TextView)view.findViewById(R.id.option)).setTextColor(Color.BLUE);
}
Try this code, hope it will help.
final boolean[] selection = new boolean[arrlist.length];
SimpleAdapter adapter = new SimpleAdapter(this, arrlist, R.layout.topicwisequestion, new String[] { "option" },new int[] { R.id.option }){
#Override
public boolean isEnabled(int position) {
return !(selection[position]);
}
}
The simplest way to achive that is to extend the BaseAdaptor class and use a custom item in list.

Generate background colour in listView from database

I have a listView generated from a database, is there a way to make a background colour or a picture to each "section" in the list:
if the first symbol in "Tip" is "W" the background should be Green, and if its "L" it should be red
Im thinking something like this, but i have no idea where to put it since it have to be done in every section:
tipvalue = BetsDbAdapter.KEY_TIP;
//Here to split the value to gain only "W" or "L"
String arrtip[] = tipvalue.split(" ", 2);
temptip = arrtip[0];
//then set background
if (temptip.equals("W")) {
getWindow().getDecorView().setBackgroundColor(Color.GREEN);
To the left is my listView and right is the xml file to make each "section" in the listview
Here is my database:
This is code generating the listView
public class StoredBets extends Activity {
private BetsDbAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.results);
dbHelper = new BetsDbAdapter(this);
dbHelper.open();
}
#Override
public void onStart(){
super.onStart();
displayListView();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.results, menu);
return true;
}
public void testknap1(View v) {
Intent myIntent = new Intent(StoredBets.this, Overview.class);
startActivity(myIntent);
}
private void displayListView() {
Cursor cursor = dbHelper.fetchAllStats();
String[] columns = new String[] {
BetsDbAdapter.KEY_SMATCH,
BetsDbAdapter.KEY_TIP,
BetsDbAdapter.KEY_BETAMOUNT,
BetsDbAdapter.KEY_BODDS
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.smatch,
R.id.tip,
R.id.bodds,
R.id.betamount,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.storedbets,
cursor,
columns,
to,
0);
ListView listView = (ListView) findViewById(R.id.listView2);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String betMatch =
cursor.getString(cursor.getColumnIndexOrThrow("smatch"));
Toast.makeText(getApplicationContext(),
betMatch, Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(StoredBets.this, SetWinVoidLoss.class);
myIntent.putExtra("id", id);
startActivity(myIntent);
}
});
}
}
EDIT 2:
#amal
This is the layout(results.xml) with the listview
<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=".StoredBets" >
<ListView
android:id="#+id/listView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignTop="#+id/button1" >
</ListView>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="180dp"
android:onClick="testknap1"
android:text="Button" />
</RelativeLayout>
you can get a fair idea from my code,
code snippet for displaying ListViews where the "curSelected" item has a different background:
final ListView lv = (ListView)findViewById(R.id.lv);
lv.setAdapter(new BaseAdapter()
{
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = new TextView(ListHighlightTestActivity.this);
convertView.setPadding(10, 10, 10, 10);
((TextView)convertView).setTextColor(Color.WHITE);
}
convertView.setBackgroundColor((position == curSelected) ?
Color.argb(0x80, 0x20, 0xa0, 0x40) : Color.argb(0, 0, 0, 0));
((TextView)convertView).setText((String)getItem(position));
return convertView;
}
public long getItemId(int position)
{
return position;
}
public Object getItem(int position)
{
return "item " + position;
}
public int getCount()
{
return 20;
}
});
This is a tutorial of how to write an adapter for a list view. amal is right, you can change the separate items in the list view in the getView() method.

How do I dynamically update a spinner using ArrayList?

I have created a Spinner that is populated with an ArrayList. I want to dynamically add values to the ArrayList, so the the Spinner populates dynamically. However, when I try to add values to my ArrayList, I get a NullPointerException.
What am I missing? Do I have to reset the adapter before amending the ArrayList?
Here is my code:
My spinner, arraylist, and adapter:
deleteselection = (Spinner)view.findViewById(R.id.deletespinner);
portfoliosdelete = new ArrayList<String>();
portfoliosdelete.add("Select Portfolio");
adapterdeletetype = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,portfoliosdelete){
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
View v = null;
// If this is the initial dummy entry, make it hidden
if (position == 0) {
TextView tv = new TextView(getContext());
tv.setHeight(0);
tv.setVisibility(View.GONE);
v = tv;
}
else {
// Pass convertView as null to prevent reuse of special case views
v = super.getDropDownView(position, null, parent);
}
// Hide scroll bar because it appears sometimes unnecessarily, this does not prevent scrolling
parent.setVerticalScrollBarEnabled(false);
return v;
}
};
adapterdeletetype.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
deleteselection.setAdapter(adapterdeletetype);
My code to dynamically update spinner:
else if(users.contains(usernull)){
pn1 = enterportfolioname.getText().toString();
user1 = new PortfolioRecord(pn1, "someemail#gmail.com");
users.remove(usernull);
users.add(user1);
portfoliosdelete.add(pn1); // <-- This causes a null pointer exception
adapterdeletetype.notifyDataSetChanged();
portfoliolist.invalidateViews();
Use the code below. This code will add a new item when the user selects and add a new item from the spinner.
Code sample:
layout main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="10" >
<Spinner
android:id="#+id/cmbNames"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
layout spinner_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Activity class:
public class MainActivity extends Activity {
private static final String NAME = "name";
private static final String ADD_NEW_ITEM = "Add New Item";
private SimpleAdapter adapter;
private Spinner cmbNames;
private List<HashMap<String, String>> lstNames;
private int counter;
private OnItemSelectedListener itemSelectedListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
HashMap<String, String> map = lstNames.get(arg2);
String name = map.get(NAME);
if (name.equalsIgnoreCase(ADD_NEW_ITEM)) {
lstNames.remove(map);
counter++;
addNewName(String.valueOf(counter));
addNewName(ADD_NEW_ITEM);
adapter.notifyDataSetChanged();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
populateList();
cmbNames = (Spinner) findViewById(R.id.cmbNames);
adapter = new SimpleAdapter(this, lstNames, R.layout.spinner_item,
new String[] { NAME }, new int[] { R.id.tvName });
cmbNames.setAdapter(adapter);
cmbNames.setOnItemSelectedListener(itemSelectedListener);
}
private void populateList() {
lstNames = new ArrayList<HashMap<String, String>>();
addNewName("abc");
addNewName("pqr");
addNewName("xyz");
addNewName(ADD_NEW_ITEM);
}
private void addNewName(String name) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(NAME, name);
lstNames.add(map);
}
}
Try to call delete on adapterdeletetype instead of the arraylist. If it fails, then please post your logcat output.

Categories

Resources