I am trying to create a Custom dialog via DialogFragment.
i want to have a Title and a Checkbox.
I am doing this by using a Custom Title as follows
<?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:paddingTop="5dp" >
<TextView
android:id="#+id/textView1"
style="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingLeft="15dp"
android:text="Categories"
android:textColor="#ffffff"
android:textSize="22sp" />
<TextView
android:id="#+id/all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="All"
android:textColor="#ffffff" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:paddingRight="10dp"/>
</LinearLayout>
Now i want to reference this this Check box and add a listener to the Checkbox.
I want to achieve something like this
What i have tried ?
public class CategoriesDialogFragment extends SherlockDialogFragment {
ListView dialog_ListView;
static CheckBox chk_all;
static SelectViewHolder viewHolder;
private static ArrayAdapter<mItems> listAdapter;
static ArrayList<String> checked = new ArrayList<String>();
protected static CharSequence[] _categories = { "Amusement Park",
"Bird Sanctuary", "Wild Life", "River", "Hill Station", "Temple",
"Rafting", "Fishing", "Hiking", "Museums" };
protected static boolean[] _selections = new boolean[_categories.length];
PlacesListAdapter adapter;
ListView listView;
Button dialog_ok;
static int TAG = 0;
static mItems categories;
static mItems orig;
public static CategoriesDialogFragment newInstance(int title) {
CategoriesDialogFragment frag = new CategoriesDialogFragment();
Bundle args = new Bundle();
args.putInt("title", title);
frag.setArguments(args);
return frag;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Dialog dialog = new Dialog(MainActivity.context);
//dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setTitle("Categories");
dialog.setContentView(R.layout.dialog);
dialog_ok = (Button) dialog.findViewById(R.id.button_category_ok);
dialog_ok.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
dialog_ListView = (ListView) dialog.findViewById(R.id.listViewDialog);
dialog_ListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View item,
int position, long id) {
categories = listAdapter.getItem(position);
orig = listAdapter.getItem(position);
categories.toggleChecked();
viewHolder = (SelectViewHolder) item.getTag();
viewHolder.getCheckBox().setChecked(
categories.isChecked());
if (!viewHolder.getCheckBox().isChecked()) {
TAG = 1;
chk_all.setChecked(false);
}
TAG = 0;
/*
* if (viewHolder.getCheckBox().isChecked()) {
*
* TAG = 0; }
*/
for (int i = 0; i < _categories.length; i++) {
categories = listAdapter.getItem(i);
if (!categories.isChecked()) {
break;
}
if (i == _categories.length - 1) {
TAG = 1;
chk_all.setChecked(true);
TAG = 0;
}
}
}
});
chk_all = (CheckBox) dialog.findViewById(R.id.checkBoxAll);
chk_all.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (TAG != 1) {
if (isChecked) {
for (int i = 0; i < listAdapter.getCount(); i++) {
categories = listAdapter.getItem(i);
categories.setChecked(true);
}
listAdapter.notifyDataSetChanged();
} else {
for (int i = 0; i < listAdapter.getCount(); i++) {
categories = listAdapter.getItem(i);
categories.setChecked(false);
}
listAdapter.notifyDataSetChanged();
}
}
if (TAG == 1) {
TAG = 0;
}
}
});
// itemss = (mItems[]) onRetainNonConfigurationInstance();
ArrayList<mItems> CategoryList = new ArrayList<mItems>();
CategoryList.add(new mItems("Amusement Park"));
CategoryList.add(new mItems("Bird Sanctuary"));
CategoryList.add(new mItems("Wild Life"));
CategoryList.add(new mItems("River"));
CategoryList.add(new mItems("Hill Station"));
CategoryList.add(new mItems("Temple"));
CategoryList.add(new mItems("Rafting"));
CategoryList.add(new mItems("Fishing"));
CategoryList.add(new mItems("Hiking"));
CategoryList.add(new mItems("Museums"));
// Set our custom array adapter as the ListView's adapter.
listAdapter = new SelectArralAdapter(MainActivity.context, CategoryList);
dialog_ListView.setAdapter(listAdapter);
return dialog;
}
private static class SelectArralAdapter extends ArrayAdapter<mItems> {
private LayoutInflater inflater;
public SelectArralAdapter(Context context, List<mItems> planetList) {
super(context, R.layout.dialog_row, R.id.rowTextView, planetList);
// Cache the LayoutInflate to avoid asking for a new one each
// time.
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Planet to display
mItems planet = (mItems) this.getItem(position);
// The child views in each row.
CheckBox checkBox;
TextView textView;
// Create a new row view
if (convertView == null) {
convertView = inflater.inflate(R.layout.dialog_row, null);
// Find the child views.
textView = (TextView) convertView
.findViewById(R.id.rowTextView);
checkBox = (CheckBox) convertView.findViewById(R.id.CheckBox01);
// Optimization: Tag the row with it's child views, so we
// don't
// have to
// call findViewById() later when we reuse the row.
convertView.setTag(new SelectViewHolder(textView, checkBox));
// If CheckBox is toggled, update the planet it is tagged
// with.
checkBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("uffff");
CheckBox cb = (CheckBox) v;
mItems row_view = (mItems) cb.getTag();
row_view.setChecked(cb.isChecked());
TAG = 1;
chk_all.setChecked(false);
TAG = 0;
for (int i = 0; i < _categories.length; i++) {
row_view = listAdapter.getItem(i);
if (!row_view.isChecked()) {
break;
}
if (i == _categories.length - 1) {
TAG = 1;
chk_all.setChecked(true);
TAG = 0;
}
}
}
});
}
// Reuse existing row view
else {
// Because we use a ViewHolder, we avoid having to call
// findViewById().
SelectViewHolder viewHolder = (SelectViewHolder) convertView
.getTag();
checkBox = viewHolder.getCheckBox();
textView = viewHolder.getTextView();
}
// Tag the CheckBox with the Planet it is displaying, so that we
// can
// access the planet in onClick() when the CheckBox is toggled.
checkBox.setTag(planet);
// Display planet data
checkBox.setChecked(planet.isChecked());
textView.setText(planet.getName());
return convertView;
}
}
}
I am not sure how we can include a setCustomTitle layout for the Custom Dialog
Now i want to reference this this Check box and add a listener to the
Checkbox.
I'm assuming that you show the dialog using the DialogFragment's onCreateDialog method, so in the onCreateDialog method you would do:
// inflate the layout title
View customTitle = inflater.inflate(R.layout.custom_title, null);
// find the CheckBox and set the listener
CheckBox ckb = (CheckBox) customTitle.findViewById(R.id.checkBox1);
ckb.setOnCheckedChangeListener(new ...);
// set the title view on the dialog etc
Related
For my Android project, I have a listview which has a checkbox for every item. The data is loaded from an SQLite database by using a CursorAdapter class. However, whenever I scroll, the checkbox positions will get moved and get carried down to the next part of the listview. How can I fix this problem?
GIF of my CheckBox Problem
Here's my Cursor Adapter Class:
public class VocabCursorAdapter extends CursorAdapter {
private static final int DIFFICULT = 0;
private static final int FAMILIAR = 1;
private static final int EASY = 2;
private static final int PERFECT = 3;
public VocabCursorAdapter(Context context, Cursor c, int flags) {
super(context, c, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.item_vocab, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// Find fields to populate in inflated template
TextView tvVocabName = (TextView) view.findViewById(R.id.vocabName);
TextView tvVocabDefinition = (TextView) view.findViewById(R.id.vocabDefinition);
ImageView tvVocabLevel = (ImageView) view.findViewById(R.id.vocabLevel);
// Extract properties from cursor
String vocab = cursor.getString(cursor.getColumnIndexOrThrow(VocabDbContract.COLUMN_NAME_VOCAB));
String definition = cursor.getString(cursor.getColumnIndexOrThrow(VocabDbContract.COLUMN_NAME_DEFINITION));
int level = cursor.getInt(cursor.getColumnIndexOrThrow(VocabDbContract.COLUMN_NAME_LEVEL));
// Populate fields with extracted properties
tvVocabName.setText(vocab);
tvVocabDefinition.setText(definition);
if (level == DIFFICULT) {
tvVocabLevel.setImageResource(R.drawable.level_bars_difficult);
tvVocabLevel.setTag(DIFFICULT);
}
else if (level == FAMILIAR) {
tvVocabLevel.setImageResource(R.drawable.level_bars_familiar);
tvVocabLevel.setTag(FAMILIAR);
}
else if (level == EASY) {
tvVocabLevel.setImageResource(R.drawable.level_bars_easy);
tvVocabLevel.setTag(EASY);
}
else if (level == PERFECT) {
tvVocabLevel.setImageResource(R.drawable.level_bars_perfect);
tvVocabLevel.setTag(PERFECT);
}
}
And here's my list item xml, item_vocab.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:longClickable="true">
<ImageView
android:layout_width="36sp"
android:layout_height="36sp"
android:id="#+id/vocabLevel"
android:layout_gravity="right"
android:src="#drawable/level_bars"
android:scaleType="fitXY"
android:contentDescription="#string/vocab_level"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/editCheckbox"
android:layout_toStartOf="#+id/editCheckbox"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/vocabName"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/vocabLevel"
android:layout_toStartOf="#+id/vocabLevel"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/vocabDefinition"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/vocabLevel"
android:layout_toStartOf="#+id/vocabLevel"
android:layout_below="#id/vocabName"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editCheckbox"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
And here's my xml which contains a 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"
tools:context=".controller.MyVocab"
android:paddingLeft="5dp">
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/mVocabList"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/empty_text_view"
android:id="#android:id/empty"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
</RelativeLayout>
I have looked at a lot of different solutions on StackOverflow, but I wasn't able to successfully do it in my own app. For an example, this post has a similar problem, but its solution used getView and I had trouble understanding how to implement it with newView and bindView instead.
And some other solutions might be examples where a cursoradapter is not involved. Any help is much appreciated, thanks a lot!
Edit #1: After incorporating Phan's changes, the checkbox states get resets to false rather than keeping its states when I scroll the listview (See ).
Reason : ListView re-uses the views.
Solution :
class VocabCursorAdapter extends CursorAdapter {
List<Integer> selectedItemsPositions;//to store all selected items position
public VocabCursorAdapter(Context context, Cursor c,int flags) {
super(context, c,0);
selectedItemsPositions = new ArrayList<>();
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
View view = LayoutInflater.from(context).inflate(R.layout.item_vocab, viewGroup, false);
CheckBox box = (CheckBox) view.findViewById(R.id.editCheckbox);
box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
int position = (int) compoundButton.getTag();
if (b) {
//check whether its already selected or not
if (!selectedItemsPositions.contains(position))
selectedItemsPositions.add(position);
} else {
//remove position if unchecked checked item
selectedItemsPositions.remove((Object) position);
}
}
});
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
//your other stuff
CheckBox box = (CheckBox) view.findViewById(R.id.editCheckbox);
box.setTag(cursor.getPosition());
if (selectedItemsPositions.contains(cursor.getPosition()))
box.setChecked(true);
else
box.setChecked(false);
}
}
Try this
public class VocabCursorAdapter extends CursorAdapter {
private ArrayList<Boolean> itemChecked = new ArrayList<Boolean>(); // array list for store state of each checkbox
public VocabCursorAdapter(Context context, Cursor c, int flags) {
for (int i = 0; i < c.getCount(); i++) { // c.getCount() return total number of your Cursor
itemChecked.add(i, false); // initializes all items value with false
}
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
...
final int position = cursor.getPosition(); // get position by cursor
CheckBox checkBox = (CheckBox) view.findViewById(R.id.editCheckbox);
checkBox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (itemChecked.get(position) == true) { // if current checkbox is checked, when you click -> change it to false
itemChecked.set(position, false);
} else {
itemChecked.set(position, true);
}
}
});
checkBox.setChecked(itemChecked.get(position)); // set the checkbox state base on arraylist object state
Log.i("In VocabCursorAdapter","position: "+position+" - checkbox state: "+itemChecked.get(position));
}
}
public class ObservationselectattributeFragment extends Fragment {
DatabaseHandler mDBHandler;
ListView mListView;
SimpleCursorAdapter mSCA;
Cursor mCsr;
ArrayList<String> attributeItems = new ArrayList<>();
public ObservationselectattributeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate the layout for this fragment
View view1=inflater.inflate(R.layout.fragment_observationselectattribute, container, false);
//Bundle bundle2 = getArguments();
Bundle bundle1 = getArguments();
final int firsttext= bundle1.getInt("TotalCount");
final String selectedtreatment= bundle1.getString("SelectedTreatment");
Toast.makeText(getActivity(),"value \n"+firsttext+"\n"+"treatment \n"+selectedtreatment, Toast.LENGTH_SHORT).show();
// Toast.makeText(getActivity(),"SelectedTreatment \n"+selectedtreatment, Toast.LENGTH_SHORT).show();
mListView = (ListView)view1.findViewById(R.id.lv001);
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button addattribute = (Button)view1.findViewById(R.id.addattribute);
addattribute.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String items1="";
Integer tcount1=0;
for(String item1:attributeItems){
items1+="-"+item1+"\n";
tcount1++;
}
Toast.makeText(getActivity(),"you have selected \n"+items1,Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(),"you have selected \n"+tcount1,Toast.LENGTH_LONG).show();
/*FragmentTransaction fr= getFragmentManager().beginTransaction();
fr.replace(R.id.main_container, new ShowObservationDataRecordingFragment()).addToBackStack("ObservationselectattributeFragment");
fr.commit();*/
Bundle bundle = new Bundle();
bundle.putInt("TotalCount2",firsttext);
bundle.putInt("TotalCount1", tcount1);
bundle.putString("SelectedTreatment", selectedtreatment);
Fragment showobservationdatarecordingfragment = new ShowObservationDataRecordingFragment();
showobservationdatarecordingfragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.main_container, showobservationdatarecordingfragment).addToBackStack("ObservationselectattributeFragment").commit();
}
});
mDBHandler = new DatabaseHandler(this.getActivity());
mCsr = mDBHandler.getAllRecords();
// Prepare a list of the columns to get the data from, for the ListViewt
String[] columns_to_get_data_from = new String[]{
DatabaseHandler.KEY_IDS,
DatabaseHandler.KEY_NAMES,
DatabaseHandler.KEY_FNAME,
DatabaseHandler.KEY_MONAME,
DatabaseHandler.KEY_SNAME
};
// Prepare a list of the Views into which to place the data
int[] itemviews_to_place_data_in = new int[]{
R.id.euserid,
R.id.eusername,
R.id.efname,
R.id.emoname,
R.id.esname
};
// get and instance of SimpleCursorAdapter
mSCA = new SimpleCursorAdapter(getActivity(),
R.layout.listviewitem_record,
mCsr,
columns_to_get_data_from,
itemviews_to_place_data_in,
0);
// Save the ListView state (= includes scroll position) as a Parceble
Parcelable state = mListView.onSaveInstanceState();
// get and instance of SimpleCursorAdapter the listviewitem_record layout
mListView.setAdapter(mSCA);
// Restore previous state (including selected item index and scroll position)
mListView.onRestoreInstanceState(state);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String attributeItem1 = ((TextView)view.findViewById(R.id.euserid)).getText().toString();
String attributeItem2 = ((TextView)view.findViewById(R.id.eusername)).getText().toString();
String attributeItem3 = ((TextView)view.findViewById(R.id.efname)).getText().toString();
String attributeItem4 = ((TextView)view.findViewById(R.id.emoname)).getText().toString();
String attributeItem5 = ((TextView)view.findViewById(R.id.esname)).getText().toString();
String attributeItem = attributeItem1 + attributeItem2 + attributeItem3 + attributeItem4 + attributeItem5;
// CheckedTextView box = (CheckedTextView) view.findViewById(R.id.record_checkbox);
// box.setChecked(true);
CheckedTextView checkedTextView = (CheckedTextView) view.findViewById(R.id.record_checkbox);
if(checkedTextView.isChecked()) {
checkedTextView.setChecked(false);
} else {
checkedTextView.setChecked(true);
}
if(attributeItems.contains(attributeItem)){
attributeItems.remove(attributeItem);//uncheck item
}
else
{
attributeItems.add(attributeItem);
}
Toast.makeText(getActivity(), "Item1 = " + attributeItem1 +"\n"+ "Item2 ="+attributeItem2 +"\n"+"Item3 ="+attributeItem3+"\n"+"Item4 ="+attributeItem4+"\n"+"Item5 ="+attributeItem5, Toast.LENGTH_SHORT).show();
}
});
((HomeActivity) getActivity())
.setActionBarTitle("Select Attribute");
return view1;
}
}
From this Activity i get text from textField and display it in a ListView.
Now i want to to add check box on every entry in a listView Cell and also like to know how to display more than one text in a single ListView Cell.
Help with code will be appreciated.
Here is my code ....
public class AfterRegister extends AppCompatActivity
{
ListView listView;
EditText editText;
Button insertItemButton;
ArrayList<String> arrayList = new ArrayList<String>();
ArrayAdapter<String> adapter;
CheckBox checkBox;
StoreRegistrationDataBase storeRegistrationDataBase;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_register);
storeRegistrationDataBase = new StoreRegistrationDataBase(this);
storeRegistrationDataBase = storeRegistrationDataBase.open();
checkBox = (CheckBox) findViewById(R.id.checkbox);
insertItemButton = (Button) findViewById(R.id.button4);
insertItemButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
editText = (EditText) findViewById(R.id.editText2);
listView = (ListView) findViewById(R.id.listView);
String getEditTextString = editText.getText().toString();
if(isAlphaNumeric(getEditTextString))
{
if(!getEditTextString.equals(""))
{
arrayList.add(getEditTextString);
adapter = new ArrayAdapter<String>(getBaseContext(), R.layout.text_view_layout, R.id.achView1, arrayList);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
editText.setText("");
}
else
{
Toast.makeText(AfterRegister.this, "You can not insert empty field", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(AfterRegister.this, "Remove Space", Toast.LENGTH_SHORT).show();
}
}
});
listView.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
return false;
}
});
}
public boolean isAlphaNumeric(String s)
{
String pattern= "^[a-zA-Z0-9]*$";
if(s.matches(pattern))
{
return true;
}
return false;
}
}
You have to use a BaseAdapter and some Getter/Setter methods to add multiple texts/images/other UI elements in each item of your list view.
You have to implement multiple things to get this result. Here they are --
Create a Custom Layout for each item of your ListView.
listview_item_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/layout_textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:layout_marginRight="5dip"
android:textStyle="bold"/>
<TextView
android:id="#+id/layout_textview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:layout_marginLeft="5dip"
android:textStyle="bold"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkbox"
android:text="Test"/>
</LinearLayout>
Create a custom class and add some Getter/Setter methods.
ListRowItem.java
public class ListRowItem implements Serializable{
String carrier,number;
public String getCarrier(){
return carrier;
}
public String getNumber(){
return number;
}
public void setCarrier(String ba_carrier){
carrier = ba_carrier;
}
public void setNumber(String ba_number){
number = ba_number;
}
}
Create a custom class and extend the BaseAdapter class.
public class MyBaseAdapter extends BaseAdapter {
public Context ba_context;
public ArrayList<ListRowItem> listitem = new ArrayList<>();
public LayoutInflater inflater;
ListRowItem currentlistitem;
public MyBaseAdapter(Context ma_context, ArrayList<ListRowItem> ma_listitem) {
super();
this.ba_context = ma_context;
this.listitem = ma_listitem;
inflater = (LayoutInflater) ba_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return this.listitem.size();
}
#Override
public Object getItem(int position) {
return this.listitem.get(position);
}
#Override
public long getItemId(int position) {
return (long) position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.listview_item_layout, parent, false);
TextView carrier = (TextView) vi.findViewById(R.id.layout_textview1);
TextView number = (TextView) vi.findViewById(R.id.layout_textview2);
currentlistitem = listitem.get(position);
String str_carrier = currentlistitem.getCarrier();
String str_number = currentlistitem.getNumber();
carrier.setText(str_carrier);
number.setText(str_number);
return vi;
}
}
Finally, populate your ArrayList and set the Adapter in your MainActivity.
ArrayList<ListRowItem> listitem = new ArrayList<>();
Context context = TestActivity.this;
MyBaseAdapter baseAdapter;
ListRowItem lr = new ListRowItem();
lr.setNumber(number);
lr.setCarrier(carrier);
listitem.add(lr);
baseAdapter = new MyBaseAdapter(context,listitem);
setContentView(R.layout.activity_test);
listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(baseAdapter);
Hope this helps!!
I am trying to create a custom listview with a checkbox and a string list of "observations" retrieved from my sqlite database. The idea is that when I click on the "retrieve" button, all checked items are shown in a toast message.
I can populate the listview through my customadapter just fine, but it doesnt seem to recognise the status of each checkbox, as no toast messages are shown, regardless of whether they are checked.
Please can someone show me where I am going wrong?
Here is my custom listview xm that I have called list_o:
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
android:id="#+id/obsgrid">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/chkbx"
android:layout_row="0"
android:layout_column="0" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/obs"
android:layout_row="0"
android:layout_column="1" />
Here is my custom adapter:
class CustomAdObs extends ArrayAdapter<String> {
private String [] observation;
private Boolean [] checked;
private Context context;
public CustomAdObs(Context context, String[] observation) {
super(context, R.layout.list_o, observation);
this.observation = observation;
this.checked = checked;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater siteInflater = LayoutInflater.from(getContext());
View customView = siteInflater.inflate(R.layout.list_o, parent, false);
TextView observationTV = (TextView) customView.findViewById(R.id.obs);
CheckBox checkCB = (CheckBox) customView.findViewById(R.id.chkbx);
checkCB.setTag(Integer.valueOf(position));
observationTV.setText(observation[position]);
checkCB.setChecked(checked[position]);
return customView;
}
}
Finally here is my activity:
public class selobs extends Activity {
List< List<String> > listArray = new ArrayList< List<String> >();
List<String> array1 = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode. setThreadPolicy(policy);
setContentView(R.layout.activity_selobs);
final Button retrieve= (Button) findViewById(R.id.btnret);
final EditText txtob = (EditText) findViewById(R.id.editText23);
filladapter();
retrieve.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
ListView obsListView = (ListView) findViewById(R.id.obsList);
View v;
for (int i = 0; i < obsListView.getCount(); i++) {
v = obsListView.getAdapter().getView(i, null, null);
CheckBox check = (CheckBox) v.findViewById(R.id.chkbx);
TextView obsItem = (TextView) v.findViewById(R.id.obs);
if (check.isChecked()) {
String p = obsItem.getText().toString();
Toast.makeText(selobs.this, p, Toast.LENGTH_LONG).show();
}
}
}
}
);
}
public void filladapter(){
myDBhandler1 dbHandler;
dbHandler = new myDBhandler1(selobs.this, null, null, 1);
listArray = dbHandler.databaseToStringObs();
List array1 = listArray.get(0);
String[] observ = (String[]) array1.toArray(new String[0]);
Boolean[] checked = new Boolean[0];
Arrays.fill(checked, Boolean.FALSE);
final ListAdapter ObsAdapter = new CustomAdObs(this, observ, checked);
final ListView obsListView = (ListView) findViewById(R.id.obsList);
obsListView.setAdapter(ObsAdapter);
obsListView.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(selobs.this, item, Toast.LENGTH_LONG).show();
TextView txtobs = (TextView) findViewById(R.id.editText23);
txtobs.setText(item);
}
}
);
}
}
your constructor
public CustomAdObs(Context context, String[] observation) {//here the Boolean[] checked ->is messing
super(context, R.layout.list_o, observation);
this.observation = observation;
this.checked = checked;
}
so you replace it with this
public CustomAdObs(Context context, String[] observation, Boolean[] checked) {
super(context, R.layout.list_o, observation);
this.observation = observation;
this.checked = checked;
}
why ?
because you call it like this
new CustomAdObs(this, observ, checked);
while you have just the 2 params in your constructor(Context context,String[] observation)
list_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="5dp">
<TextView
android:id="#+id/mytitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="5dip"
android:layout_marginTop="5dp"
android:layout_toRightOf="#+id/icon"
android:background="#drawable/textbox1"
android:paddingBottom="10dp"
android:text="Title"
android:textColor="#CC0033"
android:textSize="20dp" />
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="75dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/mytitle"
android:layout_marginLeft="20dp"
android:scaleType="fitXY"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="#+id/descri"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/mytitle"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/icon"
android:layout_marginTop="16dp"
android:background="#drawable/textbox1"
android:text="Description"
android:textColor="#3399FF"
android:textSize="14dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/mytitle"
android:layout_toLeftOf="#+id/mytitle"
android:layout_marginLeft="5dp"
android:background="#drawable/buttontextview"
android:text=" Click To Share"
android:textColor="#android:color/white"
android:textSize="13sp" />
This is my RowItem class
public class RowItem {
private String imagepath;
private String title;
private String desc;
public boolean isclicked;
public RowItem(String imagepath,String title,String desc) {
System.out.println("ImagePath is:---"+imagepath);
this.imagepath = imagepath;
System.out.println("Title is:---"+title);
this.title = title;
System.out.println("Description is:---"+desc);
this.desc = desc;
isclicked = false;
}
public String getImagepath() {
return imagepath;
}
public boolean isIsclicked() {
return isclicked;
}
public void setIsclicked(boolean isclicked) {
this.isclicked = isclicked;
}
public void setImagepath(String imagepath) {
this.imagepath = imagepath;
}
public String getTitle() {
return title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return title + "\n" + desc;
}
}
This is my onCreate() Method from the Activity
{ int k = 0;
if(i>0){
rowItems = new ArrayList<RowItem>();
for (int j = 0;j<i ; j++) {
System.out.println("Loop Value:--"+j);
System.out.println("Location Details:-----"+location.get(j));
System.out.println("Description Details:------"+description.get(j));
System.out.println("Image Details:------"+images.get(j));
RowItem item = new RowItem(images.get(j),location.get(j),description.get(j));
rowItems.add(item);
}
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListViewAdapter(PicActivity.this, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
This is my listitem onClicklistner method
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println("My List Item Clicked");
mylistid = position;
Button deleteBtn = (Button) findViewById(R.id.delete);
deleteBtn.setOnClickListener(this);
File myimagefile = new File(images.get(position));
lastlistid = mydb.getlastlistid();
int list = Integer.valueOf(lastlistid.get(0));
listno=0 ;
listno = list-position;
SharedPreferences mylistpref = getSharedPreferences(Constants.listiddetails, 0);
Editor edit= mylistpref.edit();
edit.putInt("listid", listno);
edit.commit();
System.out.println("First Position Value:-"+position);
Toast toast = Toast.makeText(getApplicationContext(),
"Title " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
Intent intermediate = new Intent (PicActivity.this,InterMediateActivity.class);
intermediate.putExtra("savenshare", "notshare");
intermediate.putExtra("flag", "false");
startActivity(intermediate);
finish();
}
The Checkbox is coming in the listview but onItemclicklistner is not working.
My deleteButton onClicklistner is like this
case R.id.delete:
System.out.println("My List item:-"+mylistid);
((CustomListViewAdapter)listView.getAdapter()).notifyDataSetChanged();
break;
Here mylistid is a global integer which i am setting while on listitemonclick.
Why my list item onclicklistner not working if i add checkbox in my list and also how can i delete the row and update the listitem.I have followed many tutorials but unable to implement.
Please help !!!!
UPDATE
This is my customListViewAdapter Class
public class CustomListViewAdapter extends BaseAdapter {
private List<RowItem> arr = new ArrayList<RowItem>();
ArrayList<Integer> checks=new ArrayList<Integer>();
private Context context;
Bitmap mybitmap;
private Activity activity;
ViewHolder holder = null;
int mypos=0;
File f;
RowItem rowItem;
public CustomListViewAdapter(Context context,List<RowItem> items) {
//super();
this.arr = items;
this.context=context;
}
private class ViewHolder {
//ImageView imageView;
TextView txtTitle;
TextView txtDesc;
ImageView image;
// CheckBox mychk;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arr.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
//mypos=arg0;
return arr.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
rowItem = (RowItem) getItem(position);
f = new File(rowItem.getImagepath());
System.out.println("My list item Position from GetView:--"+position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.descri);
holder.txtTitle = (TextView) convertView.findViewById(R.id.mytitle);
// holder.mychk = (CheckBox) convertView.findViewById(R.id.checkBox1);
holder.image = (ImageView) convertView.findViewById(R.id.icon);
// holder.mychk.setOnCheckedChangeListener(this);
// holder.mychk.setTag(arr.get(position));
// holder.mychk.setChecked(false);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
// holder.mychk.setOnCheckedChangeListener(this);
System.out.println("My Description is:--"+holder.txtDesc.getText());
System.out.println("My Title is:--"+holder.txtTitle.getText());
holder.txtDesc.setText(" "+rowItem.getDesc());
holder.txtTitle.setText(" "+rowItem.getTitle());
if(f.exists())
{
mybitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
Bitmap myeditedbitmap = Bitmap.createScaledBitmap(mybitmap, 180, 150, false);
holder.image.setImageBitmap(myeditedbitmap);
//holder.mychk.setChecked(true);
//setImageResource(rowItem.getImagepath());
}
//holder.txtTitle.setText(rowItem.getTitle());
/* for(int i=0;i<ArrayId.size();i++)
{
rowItem.remove(ArrayId[i]);
}
*/
return convertView;
}
}
}
UPDATE 2
I have updated my ListItem xml to some code and now onItemClick is working..
android:descendantFocusability="blocksDescendants"
Now The other part is..delete row item..which is still not working.and also if i select one checkbox then others are also getting selected.like if i select 1..then 3..5..7 is getting selected..How to avoid this ??
My deleteItem row code..
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SparseBooleanArray checkedItemPositions = listView.getCheckedItemPositions();
int itemCount = listView.getCount();
for(int i=itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
// adapter.remove(rowItems.get(i)); This line is giving me error.first i want to delete row temp and give a toast message.then i will update the database later.but as i am using customarrayadapter class.so i dont have the method remove.Can someone help me regarding the remove method ?
}
}
checkedItemPositions.clear();
adapter.notifyDataSetChanged();
}
});
UPDATE 3
case R.id.delete:
SharedPreferences del = getSharedPreferences(Constants.checkedid,0);
int checkmyid = 0;
checkmyid = del.getInt("check", 0);
int mycount = listView.getCount();
System.out.println("My List item COUNT FROM DELETE METHOD:-"+mycount);
System.out.println("My List item FROM DELETE METHOD:-"+checkmyid);
rowItems.remove(checkmyid);
mydb.delete(checkmyid);
((CustomListViewAdapter)listView.getAdapter()).notifyDataSetChanged();
break;
and my Delete method from database is
public void delete(int id){
String sql = "delete from picdetails where id="+id;
Cursor mych;
mych = myDataBase.rawQuery(sql, null);
}
But when i am reopening the database the data is showing once again.How to avoid ? Also When i am selecting one checkbox to delete that particular checkbox is not getting deleted.the bottom row is getting deleted.
UPDATE 4
i have updated the delete button code..now the row item is getting deleted..but for the first selection its not deleted.its getting deleted from bottom.but the checkitemid is perfect
SharedPreferences del = getSharedPreferences(Constants.checkedid,0);
int checkmyid = 0;
checkmyid = del.getInt("check", 0);
int mycount = listView.getCount();
System.out.println("My List item COUNT FROM DELETE METHOD:-"+mycount);
SparseBooleanArray checked = listView.getCheckedItemPositions();
System.out.println("*****My SELECTED List item FROM DELETE METHOD:-*****"+checkmyid);
rowItems.remove(checkmyid);
For ListView onClickListner not working
It happens due to focusability of CheckBoxin listitem layout.
Add below line to root layout of your ListView's Item layout.
android:descendantFocusability="blocksDescendants"
in list_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="5dp"
android:descendantFocusability="blocksDescendants">
To delete row (not sure but will work if make some changes)
for(int i=0; i < itemCount; i++){
if(checkedItem.contains(i)){
View rowView=listView.getChildAt(i) OR listView.removeViewAt(i);
listView.removeView(rowView);
//Also Remove data from **rowItems**
}
}
Here checkedItem is arraylist(or something else) where you supposed store position of checked listrow.
onClick...{
rowItems.remove(position);
notifyDataSetChanged();
}
this should work...
I'm new to programming and having problem with using getCheckedItemPositions() for check boxes and getting edit values from edit text in custom list view. Can anyone help me with an example to create custom list view which has above functionality. Thanks.
*this is custom listview xml code
<CheckBox android:id="#+id/checkBox" android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:text="CheckBox"
android:onClick="clickHandler"
></CheckBox>
<TextView android:layout_height="wrap_content"
android:layout_width="fill_parent" android:text="TextView"
android:id="#+id/textView1"
android:layout_alignParentLeft="true"
android:layout_centerHorizontal="true" android:layout_marginBottom="14dp"
android:layout_toLeftOf="#+id/checkBox">
*This is code for set up listview
lv1 = (ListView)dialog.findViewById(R.id.l1);
adapter2 = new SimpleCursorAdapter(
this,
R.layout.custom,
cursor2,
new String[] {"ItemName"},
new int[] {R.id.textView1});
lv1.setItemsCanFocus(false);
lv1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv1.setAdapter(adapter2);
*this what I tried to do when checked
public void onClick(View v) {
int len = lv1.getCount();
SparseBooleanArray checked = lv1.getCheckedItemPositions();
for (int i = 0 ; i < len; i++)
if (checked.get(i)) {
String item = mArrayList.get(i);
mItems.add(mArrayList.get(i));
System.out.println(item);
/* do whatever you want with the checked item */
}
But this is not working. And also I want to use edit text in this manner for getting values.when I checked and click the button app terminate.
The following code will solve your problem.
public class SimpleCursorAdapter extends ArrayAdapter {
private Context mcontext;
private View rowview;
LayoutInflater inflater;
public static ArrayList<Boolean > itemchecked=new ArrayList<Boolean>();
public SimpleCursorAdapter(Context context,ArrayList<String> mylist)
{
super(context,your layout id);
mcontext=context;
//this is the important step
for (int i = 0; i < this.getCount(); i++)
{
itemchecked.add(i,false); // initializes all items value with false
}
}
public View getView(final int position, View convertView, ViewGroup parent) {
rowview=convertView;
if(convertView==null)
{
rowview = inflater.inflate(R.yourlayout, parent, false);
}
TextView textView_heading = (TextView) rowview.findViewById(R.id.textView1);
CheckBox checkbox_detail=(CheckBox) rowview.findViewById(R.id.checkBox1);
checkbox_detail.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) v.findViewById(R.id.checkBox1);
if (cb.isChecked()) {
itemchecked.set(position, true);
// do some operations here
} else if (!cb.isChecked()) {
itemchecked.set(position, false);
// do some operations here
}
}
});
checkbox_detail.setChecked(itemchecked.get(position));
textView_heading.setText(userheading_list.get(position));
return rowview;
}
}
//now the custom list part finish
Now, to get all the information from list and also watch which checkbox is checked:
for(int i=0;i<yourlistadapterobject.getCount();i++)
{
View content_view=msg_adapter.getView(i,null , user_detail_list);
System.out.println("the list count"+user_detail_list.getCount());
if(MyContactAdapter.itemchecked.get(i))
{
System.out.println("is checked true");
TextView tv_heading= (TextView) content_view.findViewById(R.id.textView1);
String text=tv_heading.getText();
}
}
By doing this, you can get all the information against checkbox which is checked.