Android MultiChoice Spinner with SearchView Functionality - android

Hope you doing well.
I am stuck with the problem to implement Search functionality in MultiChoice Spinner, As i implemented Spinner with Multiple Choice in that used AlertDialog to display Multiple Choice Items.
There is two option for adding Filter Functionality:
Add EditText in AlertDialog for search.
Add ListView and EditText with Custom Layout.
I've tried to implement both but didn't get complete solution.
In First Case I am getting an Layout Like following image (EditText
displaying in Bottom) and also getting problem with getFilter()
which is not working with EditText:
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(defaultText);
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View view = inflater.inflate(R.layout.alert_dialog_listview_search, null);
builder.setView(view);
EditText editText = (EditText) view.findViewById(R.id.alertSearchEditText);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) { }
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void afterTextChanged(Editable s) { }
});
builder.setMultiChoiceItems(items.toArray(new CharSequence[items.size()]), selected, this);
builder.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setOnCancelListener(this);
builder.show();
In Second Case I have created custom layout for AlertDialog as
below, but in this case i can't able to remains values when second
time opening dialog:
<?xml version="1.0" encoding="utf-8"?>
<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:gravity="center_horizontal" >
<EditText
android:id="#+id/alertSearchEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:hint="#string/type_to_search"
android:inputType="text" >
<requestFocus />
</EditText>
<ListView
android:id="#+id/alertSearchListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/alertSearchEditText"
android:layout_marginTop="5dp"
android:cacheColorHint="#null"
android:fadeScrollbars="true"
android:fastScrollEnabled="true"
android:textFilterEnabled="true" >
</ListView>
<TextView
android:id="#+id/alertSearchNotFound"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#EE0000"
android:visibility="gone" />
</RelativeLayout>
The following code is help me also for filtering ListView but don't know how to get and remains selected values.
MultiSpinner.java
package com.example.multiplechoicelistwithfilter;
import java.util.List;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
public class MultiSpinner extends Spinner implements OnMultiChoiceClickListener, OnCancelListener {
private List<String> items;
private boolean[] selected;
private String defaultText;
private MultiSpinnerListener listener;
public MultiSpinner(Context context) {
super(context);
}
public MultiSpinner(Context arg0, AttributeSet arg1) {
super(arg0, arg1);
}
public MultiSpinner(Context arg0, AttributeSet arg1, int arg2) {
super(arg0, arg1, arg2);
}
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked)
selected[which] = true;
else
selected[which] = false;
}
#Override
public void onCancel(DialogInterface dialog) {
// refresh text on spinner
StringBuffer spinnerBuffer = new StringBuffer();
for (int i = 0; i < items.size(); i++) {
if (selected[i] == true) {
spinnerBuffer.append(items.get(i));
spinnerBuffer.append(", ");
}
}
String spinnerText = "";
spinnerText = spinnerBuffer.toString();
if (spinnerText.length() > 2)
spinnerText = spinnerText.substring(0, spinnerText.length() - 2);
else
spinnerText = defaultText;
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),
// android.R.layout.simple_dropdown_item_1line,
// new String[] { spinnerText });
// setAdapter(adapter);
setPrompt(spinnerText);
// if(selected.length > 0)
// listener.onItemsSelected(selected);
}
#Override
public boolean performClick() {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(defaultText);
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View view = inflater.inflate(R.layout.alert_dialog_listview_search, null);
builder.setView(view);
final ListView listView = (ListView) view.findViewById(R.id.alertSearchListView);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_multiple_choice, items);
listView.setAdapter(adapter);
EditText editText = (EditText) view.findViewById(R.id.alertSearchEditText);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
//builder.setMultiChoiceItems(items.toArray(new CharSequence[items.size()]), selected, this);
builder.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SparseBooleanArray sp = listView.getCheckedItemPositions();
String str="";
for(int i=0;i<sp.size();i++)
{
str += items.get(sp.indexOfKey(sp.keyAt(i))) + ",";
}
Log.i("TAG", "" + str );
dialog.cancel();
}
});
builder.setOnCancelListener(this);
builder.show();
return true;
}
public void setItems(List<String> items, String allText, int position,
MultiSpinnerListener listener) {
this.items = items;
this.defaultText = allText;
this.listener = listener;
// all selected by default
selected = new boolean[items.size()];
for (int i = 0; i < selected.length; i++)
selected[i] = false;
if(position != -1)
{
selected[position] = true;
listener.onItemsSelected(selected);
onCancel(null);
}
}
public interface MultiSpinnerListener {
public void onItemsSelected(boolean[] selected);
}
// // Adapter Class
}

Related

Android: ListView with Search functionality and checkBox

I have implemented a listView with search functionality and checkBox. The problem is once I search from editText,once searched text is selected its taking the value from original listView and I am not getting the exact value what I want.
I found some solutions online but did not work. Please help me.
activity_invitecaretaker.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:dividerHeight="1dp"
android:layout_below="#+id/inputSearch"
android:layout_above="#+id/button_invite">
</ListView>
<EditText android:id="#+id/inputSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/search_caretaker"
android:inputType="text"
android:maxLines="1"
style="#style/EditTextCustomHolo"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<Button android:id="#+id/cancel_text"
android:text="#string/cancel_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignBottom="#+id/inputSearch"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/send_invite"
android:id="#+id/button_invite"
android:gravity="center"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignBottom="#android:id/android:list" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/skip_button"
android:id="#+id/button_skip"
android:gravity="center"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignBottom="#android:id/android:list" />
</RelativeLayout>
list_example_entry.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<CheckedTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/email_entry"/>
<CheckedTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/phone_entry"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkBox_listview"
android:layout_gravity="end"
android:layout_alignParentRight="true"/>
</RelativeLayout>
import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by on 2015-10-15.
*/
public class InviteCaretakers extends Activity implements AdapterView.OnItemClickListener {
private EditText inputSearch;
private ArrayAdapter<String> adapter;
private EditText edit;
private Button skipButton;
private Button inviteButton;
private Button cancelButton;
private Boolean test;
private String email;
private CheckBox cb;
private ListView lv ;
private TextView emailId;
private String emailOrg;
private String searchStr;
ArrayList<StringBuilder> checkedList;
private ArrayList<String> arraySort= new ArrayList<String>();
private ArrayList<String> checkedcontacts;
private MyAdapter ma ;
private int EL_Length;
ArrayList<String> emailList = new ArrayList<String>();
private LayoutInflater inflater;
final DeviceUtil deviceUtil=new DeviceUtil();
final String TAG = InviteCaretakers.class.getName();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.activity_invitecaretaker);
inputSearch = (EditText) findViewById(R.id.inputSearch);
searchStr = inputSearch.getText().toString();
skipButton = (Button) findViewById(R.id.button_skip);
skipButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent RemindInviteIntent = new Intent(getApplicationContext(), RemindInvite.class);
startActivity(RemindInviteIntent);
}
});
getEmailContact();
lv = (ListView) findViewById(R.id.list);
doSearch();
adapter = new ArrayAdapter<String>(this, R.layout.list_example_entry, R.id.email_entry, emailList);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)skipButton.getLayoutParams();
skipButton.getLayoutParams().width = (int) (deviceUtil.getScreenWidth(getApplicationContext())) * 53 / 100;
skipButton.setLayoutParams(params);
inviteButton = (Button) findViewById(R.id.button_invite);
RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams)inviteButton.getLayoutParams();
inviteButton.getLayoutParams().width = (int) (deviceUtil.getScreenWidth(getApplicationContext())) / 2;
inviteButton.setLayoutParams(params1);
//if checked status is true add to array thats-it
checkedcontacts = new ArrayList<String>();
System.out.println("no of checked boxes..." + ma.mCheckStates.size());
System.out.println("FINALOUT checkedlist EMAILList" + checkedcontacts);
int count = checkedcontacts.size();
Toast.makeText(getBaseContext(), "You have selected" + String.valueOf(ma.mCheckStates.size()) + "contacts!!!", Toast.LENGTH_SHORT).show();
//onclick of invite button- get count & value of radio
inviteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//StringBuilder checkedcontacts = new StringBuilder();
checkedcontacts = new ArrayList<String>();
System.out.println("no of checked boxes..." + ma.mCheckStates.size());
if ( ma.mCheckStates.size() != 0) {
for (int i = 0; i < emailList.size(); i++) {
test = ma.mCheckStates.get(i);
System.out.println("test......" + test);
if (test == true){
checkedcontacts.add(emailList.get(i).toString());
String email= emailList.get(i).toString();
System.out.println("Checked......" + emailList.get(i).toString());
getEmail();
checkedcontacts.addAll(arraySort);
adapter.notifyDataSetChanged();
}
}
}
//
}
});
//onclick of invite button- get count & value of radio
cancelButton = (Button)findViewById(R.id.cancel_text);
cancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
inputSearch.setText("");
}
});
} //oncreate
public void getEmail(){
System.out.println("FINAL-OUT CHECKED ARRAY" + checkedcontacts);
int count = checkedcontacts.size();
System.out.println("count"+count);
for (int j = 0; j < checkedcontacts.size(); j++) {
email= checkedcontacts.get(j).toString();
System.out.println("email inString" + email);
//if (!email.isEmpty()){
Pack pack = PackManager.getInstance(getApplicationContext()).activePack();
System.out.println("pack in inviteCare"+pack);
PackManager.getInstance(getApplicationContext()).inviteCareTakers(pack, email, new OnServerResponseListener<String, String>() {
#Override
public void onSuccess(String successParam) {
PackManager.getInstance(InviteCaretakers.this);
Intent intent = new Intent().setClass(InviteCaretakers.this, com.synclabs.dogsync.members.InviteSent.class);
InviteCaretakers.this.startActivity(intent);
Log.d(TAG, "SUCCESS inside inviteCareTakers");
getEmail();
for (int j = 1; j < checkedcontacts.size(); j++) {
email = checkedcontacts.get(j).toString();
System.out.println("email inside onSuccess" + email);
}
getEmail();
//finish();
}
#Override
public void onFailure(String failureParam) {
Log.d(TAG, "failure inside inviteCareTakers");
}
});
} // for
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
//from device contacts extract email Id's
public ArrayList<String> getEmailContact() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
Cursor cur1 = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (cur1.moveToNext()) {
String email = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
Log.e("Email INVITE", email);
//check if emailList already contains, if not there then add else don't add to list
if (!emailList.contains(email)) {
emailList.add(email);
}
}
cur1.close();
}
Log.e("EmailList INVITE1", String.valueOf(emailList));
EL_Length = emailList.size();
Log.e("length of arrayList", String.valueOf(EL_Length));
adapter = new ArrayAdapter<String>(this, R.layout.list_example_entry, R.id.email_entry, emailList);
}
return emailList;
}
public void addToList() {
edit = (EditText) findViewById(R.id.inputSearch);
if (edit != null ) {
emailList.add(edit.getText().toString());
adapter.notifyDataSetChanged();
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int rawContactID = ops.size();
// Adding insert operation to operations list
// to insert a new raw contact in the table ContactsContract.RawContacts
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
.build());
// Adding insert operation to operations list
// to insert Home Email in the table ContactsContract.Data
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, edit.getText().toString())
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_HOME)
.build());
try {
// Executing all the insert operations as a single database transaction
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
Toast.makeText(getBaseContext(), "Contact is successfully added", Toast.LENGTH_SHORT).show();
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
}
}
public void doSearch() {
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
inputSearch = (EditText) findViewById(R.id.inputSearch);
searchStr = inputSearch.getText().toString();
System.out.println("searchStr inside onTextChanged"+ searchStr);
arraySort.clear();
int textlength = inputSearch.getText().length();
for (int i = 0; i < emailList.size(); i++) {
if (textlength <= emailList.get(i).length()) {
if (inputSearch.getText().toString().equalsIgnoreCase
((String) emailList.get(i).subSequence(0, textlength))) {
//get the index of value in new array_sort and store it in a variable for check
System.out.println("EmailList index" + emailList.indexOf(emailList.get(i).toString()));
emailOrg = emailList.get(i).toString();
System.out.println("emailOrg" + emailOrg);
arraySort.add(emailOrg);
}
}
}
//this is needed for searching through
adapter = new ArrayAdapter<String>(InviteCaretakers.this, R.layout.list_example_entry, R.id.email_entry, emailList);
lv.setAdapter(adapter);
adapter.getFilter().filter(s.toString());
adapter.notifyDataSetChanged();
//
// not existing = add to array and list call if it matches email id structure
Validation va = new Validation();
if (va.isValidEmailId(searchStr)) {
getEmailContact();
addToList();
Log.e("length EL AFTER ADDING", String.valueOf(EL_Length));
}
System.out.println("array_sort items" + arraySort);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
//
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
MyAdapter()
{
mCheckStates = new SparseBooleanArray(emailList.size());
mInflater = (LayoutInflater)InviteCaretakers.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return emailList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.list_example_entry, null);
TextView tv= (TextView) vi.findViewById(R.id.email_entry);
cb = (CheckBox) vi.findViewById(R.id.checkBox_listview);
tv.setText(emailList.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
System.out.println("hello...........");
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}

How to get Item in ListView when click on CheckBox

I have added the checkBoxView to my ListView
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<TextView
android:id="#+id/textViewWord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/fstRow"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textViewTranslate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textViewWord"
android:layout_below="#+id/textViewWord"
android:textColor="#ff1009"
android:text="#string/scndRow"
android:textAppearance="?android:attr/textAppearanceMedium" />
<CheckBox
android:id="#+id/starCheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:button="#android:drawable/btn_star"
android:focusable="false"
/>
</RelativeLayout>
here is my code
package com.wts.ui;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
public final static int REQUEST_CODE = 1;
private WordsDBAdapter dbAdapter;
private SimpleCursorAdapter dataAdapter;
private Button button;
private EditText editWord;
private EditText editTranslate;
private ListView listView;
private String selectedWord;
private Cursor cursor;
//context menu
private final static int IDM_EDIT = 101;
private final static int IDM_DELETE = 102;
//options menu
private static final int IDM_ABOUT = 201;
private static final int IDM_EXIT = 202;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbAdapter = new WordsDBAdapter(this);
dbAdapter.open();
button = (Button)findViewById(R.id.buttonAddWord);
listView = (ListView)findViewById(R.id.listWords);
displayListView();
registerForContextMenu(listView);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Add some words, please",
Toast.LENGTH_LONG).show();
}
});
//================ListView onLongClick========================
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
cursor = (Cursor)listView.getItemAtPosition(arg2);
selectedWord = cursor.getString(0);
return false;
}
});
//================Button onClick========================
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
editWord = (EditText)findViewById(R.id.editWord);
editTranslate = (EditText)findViewById(R.id.editTranslate);
String word = editWord.getText().toString();
String translate = editTranslate.getText().toString();
if(word.length() > 0 && translate.length() > 0){
dbAdapter.insertWord(word,translate , "noDscrpt");
displayListView();
editWord.setText("");
editTranslate.setText("");
}
}
});
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId() == R.id.listWords) {
String[] menuItems = getResources().getStringArray(
R.array.contextMenuItems);
menu.add(Menu.NONE, IDM_EDIT, Menu.NONE, menuItems[0]);
menu.add(Menu.NONE, IDM_DELETE, Menu.NONE, menuItems[1]);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case IDM_EDIT:
Intent intent = new Intent(this, EditActivity.class);
intent.putExtra(getResources().getString(R.string.fstRow),
cursor.getString(1));
intent.putExtra(getResources().getString(R.string.scndRow),
cursor.getString(2));
intent.putExtra(getResources().getString(R.string.thrdRow),
cursor.getString(3));
startActivityForResult(intent, REQUEST_CODE);
break;
case IDM_DELETE:
dbAdapter.deleteWord(selectedWord);
displayListView();
break;
}
return true;
}
#SuppressWarnings("deprecation")
private void displayListView() {
Cursor cursor = dbAdapter.fetchAllWords();
String[] columns = new String[] {
WordsDBAdapter.KEY_WORD,
WordsDBAdapter.KEY_TRANSLATION,
};
int[] to = new int[] {
R.id.textViewWord,
R.id.textViewTranslate,
};
dataAdapter = new SimpleCursorAdapter(this, R.layout.word_info, cursor,
columns, to);
listView.setAdapter(dataAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
String[] menuItems = getResources().getStringArray(R.array.options_menu_items);
menu.add(Menu.NONE,IDM_ABOUT,Menu.NONE,menuItems[1]);
menu.add(Menu.NONE,IDM_EXIT,Menu.NONE,menuItems[2]);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item)
{
switch(item.getItemId())
{
case IDM_ABOUT:
{
Intent intent = new Intent(MainActivity.this,AboutActivity.class);
startActivity(intent);
break;
}
case IDM_EXIT:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
break;
}
return true;
}
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent intent)
{
if(resultCode == RESULT_OK && requestCode == REQUEST_CODE)
{
if(intent.hasExtra(getResources().getString(R.string.fstRow)))
{
dbAdapter.changeValue(
selectedWord,
intent.getExtras().getString(getResources().getString(R.string.fstRow)),
intent.getExtras().getString(getResources().getString(R.string.scndRow)),
intent.getExtras().getString(getResources().getString(R.string.thrdRow))
);
displayListView();
}
}
}
}
How to get listViewItem that holds CheckBox that I have been clicked ?
Do i Need to set OnClickListener on CheckBox? but what next ?
Please help
thnx!
You should create your custom adapter , and you can catch your checkbox its getView method
public class CustomListAdapter extends ArrayAdapter<String> {
private Activity context;
private ListItemRow itemRow;
private String[] list;
private LayoutInflater layoutInflater;
public CustomListAdapter(Activity context, String[] list) {
super(context, R.layout.main, list);
this.context = context;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
itemRow = new ListItemRow();
layoutInflater = context.getLayoutInflater();
rowView = layoutInflater.inflate(R.layout.word_info, null, true);
itemRow.starCheck= (ChechBox) rowView.findViewById(R.id.starCheck);
itemRow.textViewTranslate= (TextView) rowView.findViewById(R.id.textViewTranslate);
} else {
itemRow = (ListItemRow) rowView.getTag();
}
itemRow.starCheck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
itemRow.textViewTranslate.setText("starCheck clicked");
}
});
return rowView;
}
private class ListItemRow {
private ChechBox starCheck;
private TextView textViewTranslate;
}
}

How to add EditText in listview and get its value dynamically in all the rows?

I have Checkbox and EditText and a Textview in a listView. It gets value for the text view from a list. Checkbox will be checked dynamically. In the same way EditText also can be entered dynamically. Now my problem is, When i scroll the list view (up and down) after entering the text in the Edit text, I could not get the typed value. I check the check box also like that. But using the position, I set it correct. I Could not know How to set the EditText value to the list properly. Please help me. Here is my code:
main.xml: (Main xml for launch)
<?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" >
<ListView
android:id="#+id/my_list"
android:layout_width="fill_parent"
android:layout_height="250px" />
<Button
android:text="Save"
android:id="#+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
row.xml: (ListView Row)
<?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="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/label"
android:textSize="30sp"/>
<CheckBox
android:id="#+id/check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText
android:text=""
android:id="#+id/txtAddress"
android:layout_width="150px"
android:layout_height="wrap_content"/>
</LinearLayout>
Model.Java: (It is the POJO class)
package com.checkboxlistview;
public class Model {
private String name;
private boolean selected;
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public void setName(String name) {
this.name = name;
}
public Model(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
MyAdapter.Java: (This is used to Hold the view in the list view using the converter and holder)
package com.checkboxlistview;
import java.util.List;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
public class MyAdapter extends ArrayAdapter<Model> implements TextWatcher {
private final List<Model> list;
private final Activity context;
int listPosititon;
public MyAdapter(Activity context, List<Model> list) {
super(context, R.layout.row, list);
this.context = context;
this.list = list;
}
static class ViewHolder {
protected TextView text;
protected CheckBox checkbox;
protected EditText address;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
listPosititon = position;
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.row, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.label);
viewHolder.checkbox = (CheckBox) convertView
.findViewById(R.id.check);
viewHolder.address = (EditText) convertView
.findViewById(R.id.txtAddress);
viewHolder.checkbox
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
int getPosition = (Integer) buttonView.getTag();
//Here we get the position that we have set for the checkbox using setTag.
list.get(getPosition).setSelected(
buttonView.isChecked());
// Set the value of checkbox to maintain its state.
}
});
viewHolder.address.addTextChangedListener(this);
convertView.setTag(viewHolder);
convertView.setTag(R.id.label, viewHolder.text);
convertView.setTag(R.id.check, viewHolder.checkbox);
convertView.setTag(R.id.txtAddress, viewHolder.address);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkbox.setTag(position); // This line is important.
viewHolder.text.setText(list.get(position).getName());
viewHolder.checkbox.setChecked(list.get(position).isSelected());
if (list.get(position).getAddress() != null) {
viewHolder.address.setText(list.get(position).getAddress() + "");
} else {
viewHolder.address.setText("");
}
return convertView;
}
#Override
public void afterTextChanged(Editable s) {
list.get(listPosititon).setAddress(s.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
}
MainActivity.java (This is the activity):
package com.checkboxlistview;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView listView;
Button btnSave;
ArrayAdapter<Model> adapter;
List<Model> list = new ArrayList<Model>();
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.my_list);
btnSave = (Button)findViewById(R.id.btnSave);
adapter = new MyAdapter(this,getModel());
listView.setAdapter(adapter);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < list.size(); i++) {
Toast.makeText(getBaseContext(), "Name : "+list.get(i).getName() +" Selected: "+list.get(i).isSelected(), Toast.LENGTH_SHORT).show();
}
}
});
}
private List<Model> getModel() {
list.add(new Model("Linux"));
list.add(new Model("Windows7"));
list.add(new Model("Suse"));
list.add(new Model("Eclipse"));
list.add(new Model("Ubuntu"));
list.add(new Model("Solaris"));
list.add(new Model("Android"));
list.add(new Model("iPhone"));
list.add(new Model("Java"));
list.add(new Model(".Net"));
list.add(new Model("PHP"));
return list;
}
}
There is no error in the code. It runs well. I could maintain the checkbox position and display at the same position even I scroll up and down. But I could not get and set the EditText value properly. Please Help me out.
Thanks in advance.
you can achieve this using the custom list view.
find the example of listview with edittext is here
Easy and beautiful solution to handle EditText with listView:
(Does not require holder or RecycleView or anything else)
Brief explaination:
1) In getView method when you inflate the view, apply the myTextWatcher the editText. Pass this EditText to the myTextWatcher()
2) Inside getView Method find that EditText and set position as editText.setTag [Each time. not only when the view was inflated.]
3) Define MyTextWatcher. It should have reference to EditText on which it is applied.
4) myTextWatcher.onTextChanged() will read the tag set to the editText and do the required work
Modify your getView() method of Adapter class:
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
if(convertView==null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.single_row_layout,parent,false);
EditText et = convertView.findViewById(R.id.idEditText);
et.addTextChangedListener(new MyTextWatcher(et));
}
//This is again required to find reference to EditText... so that 'position' can be applied on to it as 'tag' EACH time.
EditText editText = (EditText) convertView.findViewById(R.id.idEditText);;
//This tag will be used inside onTextChanged()
editText.setTag(position);
}
Define your MyTextWatcher class as:
private class MyTextWatcher implements TextWatcher{
//int position;
EditText et;
public MyTextWatcher(EditText editText){
this.et = editText;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(et.getTag()!=null){
// This is required to ensure EditText is edited by user and not through program
if(et.hasFocus()){
int position = (int)et.getTag();
String newText = et.getText()+"";
//Implement your actions here........
//you can get require things/ views from listView.getChildAt(position)..
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
}
Just keep viewHolder.address.setTag(position) and it works perfect cheers.
Adapter Class:
package com.qzick.adapter;
import java.util.ArrayList;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import com.example.qzick.R;
import com.qzick.model.Get_All_Class_Model;
public class Get_Class_Adapter extends BaseAdapter {
protected ArrayList<Get_All_Class_Model> get_class_details;
LayoutInflater inflater;
Context context;
private int x = 1;
public Get_Class_Adapter(Context context,
ArrayList<Get_All_Class_Model> get_class_details) {
this.get_class_details = get_class_details;
this.inflater = LayoutInflater.from(context);
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return get_class_details.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return get_class_details.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = this.inflater.inflate(
R.layout.activity_adapter_class_ll, parent, false);
holder.textclass = (TextView) convertView
.findViewById(R.id.text_class_ll);
holder.txtid = (TextView) convertView.findViewById(R.id.text_id_ll);
holder.checkclass = (CheckBox) convertView
.findViewById(R.id.check_class_LL);
holder.edtsection = (EditText) convertView
.findViewById(R.id.edttxt_addsection_ll);
holder.checkclass
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
int getPosition = (Integer) buttonView.getTag();
get_class_details.get(getPosition).setChecked(
buttonView.isChecked());
notifyDataSetChanged();
}
});
convertView.setTag(holder);
convertView.setTag(R.id.check_class_LL, holder.checkclass);
convertView.setTag(R.id.edttxt_addsection_ll, holder.edtsection);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkclass.setTag(position);
holder.edtsection.setTag(position);
holder.edtsection.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
int pos = (Integer) holder.edtsection.getTag();
get_class_details.get(pos).setEdtsections(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
holder.txtid.setText(get_class_details.get(position).getId());
holder.textclass.setText(get_class_details.get(position).getText());
holder.edtsection.setText(get_class_details.get(position)
.getEdtsections());
holder.textclass.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
x++;
if (x % 2 == 0) {
holder.checkclass.setChecked(false);
} else {
holder.checkclass.setChecked(true);
}
}
});
holder.checkclass.setChecked(get_class_details.get(position)
.isChecked());
return convertView;
}
private class ViewHolder {
TextView textclass, txtid;`enter code here`
CheckBox checkclass;
EditText edtsection;
}
}

how can i get the editText data from the Alertdailog.builder?

package com.nil.in;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class SettingsMod extends Activity {
/** Called when the activity is first created. */
private ListView listview;
private String lv_arr[] = { "change password", "change contact details" };
String old_password = "rajesh";
// EditText input;
// TextView name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homesettings);
listview = (ListView) findViewById(R.id.View1_homesettings);
listview.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, lv_arr));
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
// get the position where the user clicked on the ListView
if (position == 0) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(
SettingsMod.this);
alertbox.setMessage("Password change!");
alertbox.setView(LayoutInflater.from(SettingsMod.this)
.inflate(R.layout.passwordchange, null));
alertbox.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
System.out.println("Save clicked");
// getting the editText data from the Dailog
Context mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater
.inflate(
R.layout.passwordchange,
(ViewGroup) findViewById(R.id.LinearLayout01));
EditText input = (EditText) layout
.findViewById(R.id.Oldpassword_Edit1);
EditText newPass_Edit = (EditText) layout
.findViewById(R.id.NewPassword_Edit2);
EditText confirm_Edit = (EditText) layout
.findViewById(R.id.Confirm_Edit3);
String str = input.getText().toString();
String edit_2 = newPass_Edit.getText()
.toString();
String edit_3 = newPass_Edit.getText()
.toString();
validate(str, edit_2, edit_3);
}
});
alertbox.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
System.out.println("Cancel clicked");
}
});
alertbox.show();
} else {
AlertDialog.Builder alertbox = new AlertDialog.Builder(
SettingsMod.this);
alertbox.setTitle("Contact info");
alertbox.setView(LayoutInflater.from(SettingsMod.this)
.inflate(R.layout.detailschange, null));
alertbox.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
}
});
alertbox.show();
}
}
});
}
void validate(String str, String edit_2, String edit_3) {
if (str == null || str.length() == 0) {
AlertDialog.Builder adb = new AlertDialog.Builder(SettingsMod.this);
adb.setTitle("enter old password");
adb.setPositiveButton("ok", null);
adb.show();
}
if (edit_2 == null || edit_2.length() == 0) {
AlertDialog.Builder adb = new AlertDialog.Builder(SettingsMod.this);
adb.setTitle("enter new password");
adb.setPositiveButton("ok", null);
adb.show();
}
if (!edit_2.equals(edit_3)) {
AlertDialog.Builder adb = new AlertDialog.Builder(SettingsMod.this);
adb.setTitle("matched");
adb.setPositiveButton("ok", null);
adb.show();
}
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
// get the position where the user clicked on the ListView
if (position == 0) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(
SettingsMod.this);
alertbox.setMessage("Password change!");
Context mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater
.inflate(
R.layout.passwordchange,
(ViewGroup) findViewById(R.id.LinearLayout01));
EditText input = (EditText) layout
.findViewById(R.id.Oldpassword_Edit1);
EditText newPass_Edit = (EditText) layout
.findViewById(R.id.NewPassword_Edit2);
EditText confirm_Edit = (EditText) layout
.findViewById(R.id.Confirm_Edit3);
alertbox.setView(LayoutInflater.from(SettingsMod.this)
.inflate(R.layout.passwordchange, null));
alertbox.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
System.out.println("Save clicked");
// getting the editText data from the Dailog
String str = input.getText().toString();
String edit_2 = newPass_Edit.getText()
.toString();
String edit_3 = newPass_Edit.getText()
.toString();
validate(str, edit_2, edit_3);
}
});
alertbox.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
System.out.println("Cancel clicked");
}
});
alertbox.show();
}

Spinner with checkbox items, is it possible?

Spinner with checkbox items, is it possible?
Try this
<selva.spinner.multispinner android:id="#+id/multi_spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
Spinner1Activity.java
package selva.spinner;
import java.util.ArrayList;
import java.util.List;
import selva.spinner.multispinner.multispinnerListener;
import android.app.Activity;
import android.os.Bundle;
public class Spinner1Activity extends Activity implements multispinnerListener
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
multispinner ms = (multispinner) findViewById(R.id.multi_spinner);
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
list.add("four");
list.add("five");
list.add("six");
list.add("seven");
list.add("eight");
list.add("nine");
list.add("ten");
ms.setItems(list, "select", this);
}
#Override
public void onItemschecked(boolean[] checked)
{
// TODO Auto-generated method stub
}
}
multispinner.java
package selva.spinner;
import java.util.List;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.util.AttributeSet;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class multispinner extends Spinner implements
OnMultiChoiceClickListener, OnCancelListener
{
private List<String> listitems;
private boolean[] checked;
public multispinner(Context context)
{
super(context);
}
public multispinner(Context arg0, AttributeSet arg1)
{
super(arg0, arg1);
}
public multispinner(Context arg0, AttributeSet arg1, int arg2)
{
super(arg0, arg1, arg2);
}
#Override
public void onClick(DialogInterface dialog, int ans, boolean isChecked)
{
if (isChecked)
checked[ans] = true;
else
checked[ans] = false;
}
#Override
public void onCancel(DialogInterface dialog)
{
String str="Selected values are: ";
for (int i = 0; i < listitems.size(); i++)
{
if (checked[i] == true)
{
str=str+" "+listitems.get(i);
}
}
AlertDialog.Builder alert1 = new AlertDialog.Builder(getContext());
alert1.setTitle("Items:");
alert1.setMessage(str);
alert1.setPositiveButton("Ok", null);
alert1.show();
}
#Override
public boolean performClick()
{
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMultiChoiceItems(
listitems.toArray(new CharSequence[listitems.size()]), checked, this);
builder.setPositiveButton("done",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
builder.setOnCancelListener(this);
builder.show();
return true;
}
public void setItems(List<String> items, String allText,
multispinnerListener listener)
{
this.listitems = items;
checked = new boolean[items.size()];
for (int i = 0; i < checked.length; i++)
checked[i] =false;
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),
android.R.layout.simple_spinner_item, new String[] { allText });
setAdapter(adapter);
}
public interface multispinnerListener
{
public void onItemschecked(boolean[] checked);
}
}
That depends on what you mean.
If you want a true multi-select Spinner, then there's nothing built into Android for that.
Note that you are in control over what goes in the Spinner rows of the drop-down list, except for the radio button. If you want to put checkboxes in your rows, be my guest. It'll look strange, may not work properly with respect to touch events, will not remove the radio buttons (AFAIK), and will be completely unrelated to the Spinner's contents in normal mode. Hence, I can't recommend this approach, but it is doable.
The source code to Spinner is available from the Android open source project, so you are welcome to clone it and develop a MultiSelectSpinner or something.
You can use the multiSpinner:
import java.util.List;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.util.AttributeSet;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class MultiSpinner extends Spinner implements OnMultiChoiceClickListener, OnCancelListener {
private List<String> items;
private boolean[] selected;
private String defaultText;
private MultiSpinnerListener listener;
public MultiSpinner(Context context) {
super(context);
}
public MultiSpinner(Context arg0, AttributeSet arg1) {
super(arg0, arg1);
}
public MultiSpinner(Context arg0, AttributeSet arg1, int arg2) {
super(arg0, arg1, arg2);
}
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked)
selected[which] = true;
else
selected[which] = false;
}
#Override
public void onCancel(DialogInterface dialog) {
// refresh text on spinner
StringBuffer spinnerBuffer = new StringBuffer();
boolean someUnselected = false;
for (int i = 0; i < items.size(); i++) {
if (selected[i] == true) {
spinnerBuffer.append(items.get(i));
spinnerBuffer.append(", ");
} else {
someUnselected = true;
}
}
String spinnerText;
if (someUnselected) {
spinnerText = spinnerBuffer.toString();
if (spinnerText.length() > 2)
spinnerText = spinnerText.substring(0, spinnerText.length() - 2);
} else {
spinnerText = defaultText;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),
android.R.layout.simple_spinner_item,
new String[] { spinnerText });
setAdapter(adapter);
listener.onItemsSelected(selected);
}
#Override
public boolean performClick() {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMultiChoiceItems(
items.toArray(new CharSequence[items.size()]), selected, this);
builder.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setOnCancelListener(this);
builder.show();
return true;
}
public void setItems(List<String> items, String allText,
MultiSpinnerListener listener) {
this.items = items;
this.defaultText = allText;
this.listener = listener;
// all selected by default
selected = new boolean[items.size()];
for (int i = 0; i < selected.length; i++)
selected[i] = true;
// all text on the spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),
android.R.layout.simple_spinner_item, new String[] { allText });
setAdapter(adapter);
}
public interface MultiSpinnerListener {
public void onItemsSelected(boolean[] selected);
}
}
And then in your layout .xml:
<xxx.xx.gui.MultiSpinner android:id="#+id/SpinnerCollegues"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="#string/university"/>
You could just create a ListView with check boxes. You could even add it to a dialog. That's essentially all a spinner is.
There is implemented a MultiSpinner, you can find it on AndroidArsenal
Can find it on Maven Repository
If you add a hint to it, looks nice:
android:hint="Choose ..."
I created a dynamic filled Spinner which gets its content over the Sqlite Database query over the content resolver, it's a Image instead of text when closed, it shows whats selected, and its awesome simple :-)
spinnerFavorites = (SpinnerMultiSameClick) v.findViewById(R.id.guide_btn_favorites);
spinnerFavorites.setOnItemSelectedListener(this);
ContentResolver resolver = activity.getContentResolver();
String[] projection = new String[] { DataContract.Favorites.FAVORITES_ID, DataContract.Favorites.NAME };
Cursor cursor = resolver.query(DataContract.Favorites.CONTENT_URI, projection, null, null, DataContract.Favorites.FAVORITES_ID +" ASC");
if (cursor.getCount() > 0) {
// create an array to specify which fields we want to display
String[] from = new String[] { DataContract.Favorites.NAME, DataContract.Favorites.FAVORITES_ID };
// create an array of the display item we want to bind our data
// to
int[] to = new int[] { android.R.id.text1, android.R.id.text2 };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(activity, R.layout.ghost_text, cursor, from, to,
SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
// get reference to our spinner
spinner.setAdapter(adapter);
adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
} else {
// TODO: Maybe button to make new favList
spinnerFavorites.setVisiblity(View.GONE);
}
Now, it looks like a simple Spinner, what makes it show its selection is this line, it will fill the values and put a radioCheckbox on the right side, the top/1st Element in your list will be preselected.
adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
there are several other predefined layouts wich work pretty well
simple_list_item_checked -> shows a checkMark instead of a RadioButton
simple_list_item_activated_1 or 2 -> Changes BackgroundColor
simple_list_item_multiple_choice -> CheckBoxes with checkMarks
to complete here is my layout, it shows an marked or unmarked Image (and not whats selected) therefore i specified R.layout.ghost_text in the spinnerAdapter.
<com.netstream.ch.tv.android.ui.program.guide.land.SpinnerMultiSameClick
android:id="#+id/guide_btn_favorites"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#drawable/icon_selector_guide_filter_favorites"
android:clickable="true" />
here my onItemSelecte which needs the OnItemSelectedListener Interfaces. What it does, it keeps track with a boolean if its the initialisation of the spinner or not. If there is a real click, we extract the information and update another UI Element over a Controller (could also be a callback) if the Clicked Element is the StandardSelected Element i set the SpinnerImage unselected, if its sth else then the standard element i set the spinnerImage selected.
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (parent.getId() == R.id.guide_btn_favorites) {
if (!AbsintheViewControllerFactory.getGuideController().isFavoriteListInitialisation()) {
Cursor c = (Cursor) parent.getItemAtPosition(pos);
String favid = c.getString(c.getColumnIndexOrThrow(DataContract.Favorites.FAVORITES_ID));
String name = c.getString(c.getColumnIndexOrThrow(DataContract.Favorites.NAME));
Log.d(TAG, "Set Filter to FavListId: " + favid + " by its name: " + name);
if (favid.equalsIgnoreCase(GuideViewController.allChannelsFavoritesIdentifier)) {
spinnerFavorites.setSelected(false);
} else {
spinnerFavorites.setSelected(true);
}
AbsintheViewControllerFactory.getGuideController().setFavourites(favid);
guideInfoSelectedFavoriteList.setText(name);
} else {
AbsintheViewControllerFactory.getGuideController().setFavoriteListInitialisation(false);
guideInfoSelectedFavoriteList.setText(getActivity().getResources().getString(R.string.FILTER_FAVORITE_ALL_CHANNELS));
}
}
}

Categories

Resources