Android - Confirmation Dialog for Delete button inside ListView row - java

I'm looking for a way to implement a dialog which asks for confirmation when clicking on the delete button of my ListView row. I tried to do it inside my custom ArrayAdapter, but as it is no Activity I don't know how to do it.
When I put the whole onClick-Listener inside the MainActivity, I have no clou how to find out which position the button was clicked so that I can remove it afterwards.
public class ServiceAdapter extends ArrayAdapter<Service> {
private final Singleton singleton = Singleton.getInstance();
private ArrayList<Service> services;
public ServiceAdapter(Context context, ArrayList<Service> services) {
super(context, 0, services);
this.services = services;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Service service = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.listview_row, parent, false);
}
// Lookup view for data population
TextView quantity = (TextView) convertView
.findViewById(R.id.QUANTITY_CELL);
TextView description = (TextView) convertView
.findViewById(R.id.DESCRIPTION_CELL);
Button delete = (Button) convertView.findViewById(R.id.BUTTON_DELETE);
// Populate the data into the template view using the data object
quantity.setText(String.valueOf(service.getQuantity()));
description.setText(service.getDescription());
// Set up the listener for the delete button.
final View view = convertView;
view.setTag(Integer.valueOf(position));
delete.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
Integer index = (Integer) view.getTag();
services.remove(index.intValue());
notifyDataSetChanged();
}
});
// Return the completed view to render on screen
return convertView;
}
}
public class MainActivity extends Activity {
private ListView serviceList;
private ArrayList<Service> services;
private ServiceAdapter adapter;
private final Singleton singleton = Singleton.getInstance();
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serviceList = (ListView) findViewById(R.id.service_list);
adapter = new ServiceAdapter(this, services);
serviceList.setAdapter(adapter);
serviceList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
Service temp = services.get(position);
singleton.setQuantity(temp.getQuantity());
singleton.setDescription(temp.getDescription());
setPosition(position);
openDetailedEntry();
}
});
}
public void openDetailedEntry() {
Intent i = new Intent(this, DetailedEntryActivity.class);
// Check if the meant Activity is actually resolvable
if (i.resolveActivity(getPackageManager()) != null)
startActivity(i);
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="16dp"
android:paddingRight="16dp" >
<TableLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.1"
android:paddingTop="8dp"
>
<ListView
android:id="#+id/service_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:dividerHeight="2dp" />
</TableLayout>
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/listview_row"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="4dip"
android:paddingBottom="4dip"
android:paddingLeft="4dip"
android:paddingRight="4dip"
android:orientation="horizontal">
<TextView android:id="#+id/QUANTITY_CELL"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textSize="20sp"
/>
<TextView android:id="#+id/DESCRIPTION_CELL"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_weight="6" />
<Button
android:id="#+id/BUTTON_DELETE"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:textSize="12sp"
android:focusable="false"
android:text="#string/delete" />
</LinearLayout>
Let me know if you need something.

Construct AlertDialog in ServiceAdapter Like this,
private AlertDialog mDialog;
private int mListRowPosition;
public ServiceAdapter(Context context, ArrayList<Service> services) {
super(context, 0, services);
this.services = services;
//Create AlertDialog here
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Your Message")
.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Use mListRowPosition for clicked list row...
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object
mDialog = builder.create();
}
Create method in ServiceAdapter Like,
private void showDialog(int position)
{
mListRowPosition = position;
if(mDialog != null)
mDialog.show();
}
Now in onClick() Just call
showDialog(position); // But make position of getView() as final...

Related

Listview Onclick Listener Not working after updating Cardview Layout

I have updated the layout, replaced the ImageViews with Buttons instaed, and the Listview OnCLick listener is not working now, when I used the old layout with ImageViews. Please let me know if this needs to be further formatted properly, any help will be approciated.
Listener in Activity:
lvItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, ItemDetailsActivity.class);
intent.putExtra("Position", position);
startActivity(intent);
}
});
list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="#+id/ItemNametv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item : "
android:textSize="20sp"
android:layout_marginBottom="8dp"/>
<TextView
android:id="#+id/qtytv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Qty : "
android:layout_marginBottom="8dp"/>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#c0c0c0"
android:layout_marginBottom="8dp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/EditItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Edit"
android:minWidth="0dp"
android:minHeight="0dp"
style="#style/Widget.AppCompat.Button.Borderless"/>
<Button
android:id="#+id/DeleteItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete"
android:textColor="#color/btn_logut_bg"
android:minWidth="0dp"
android:minHeight="0dp"
style="#style/Widget.AppCompat.Button.Borderless"/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
ItemDetailsAdapter.java:
public class ItemDetailsAdapter extends BaseAdapter {
private ArrayList<Item> arrayListItem;
private Context context;
private LayoutInflater inflater;
public ItemDetailsAdapter(Context context, ArrayList<Item> arrayListItem) {
this.context = context;
this.arrayListItem = arrayListItem;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return arrayListItem.size();
}
#Override
public Object getItem(int position) {
return arrayListItem.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
Holder holder;
if (v == null) {
v = inflater.inflate(R.layout.list_item, null);
holder = new Holder();
holder.ItemName = (TextView) v.findViewById(R.id.ItemNametv);
holder.qty = (TextView) v.findViewById(R.id.qtytv);
holder.EditItem = (Button) v.findViewById(R.id.EditItem);
holder.DeleteItem = (Button) v.findViewById(R.id.DeleteItem);
v.setTag(holder);
}
else {
holder = (Holder) v.getTag();
}
holder.ItemName.setText(arrayListItem.get(position).getItem());
holder.qty.setText(arrayListItem.get(position).getQty());
holder.EditItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,AddOrUpdateItem.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("Position", position);
context.getApplicationContext().startActivity(intent);
}
});
holder.DeleteItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ShowConfirmDialog(context, position);
}
});
return v;
}
class Holder {
TextView ItemName, qty;
Button DeleteItem, EditItem;
}
public static void ShowConfirmDialog(Context context, final int position) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder
.setMessage("Are you sure you want to delete this entry?")
.setCancelable(true)
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.getInstance().deleteItem(position);
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
There is issue of views getting in conflict i.e. views might be getting over lapped by others so add
android:descendantFocusability="blocksDescendants" on your parent layout and list item and for all views for which you want to handle click events, for them, android:focusable="false" add this as well like here in button...
TRY this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:descendantFocusability="blocksDescendants"
android:layout_width="match_parent"
android:layout_height="match_parent">
Step 1: In list_item.xml, add android:descendantFocusability="blocksDescendants" to your root Linearlayout.
Step 2: In list_item.xml, add android: focusable="false" to android.support.v7.widget.CardView
Note: If there is android:clickable="true" in android.support.v7.widget.CardView remove it.

onClick not working in Fragment

Basically I have listview in my fragment layout. And another layout called item_todo.xml which contains my button.
The onClick() wasn't working while clicking the delete_task button in my layout.
It would be great if you could help me out !
Here is my Class ToDoFragment
public class ToDoFragment extends Fragment {
private static final String TAG = "MainActivity";
private TaskDbHelper mHelper;
private ListView mTaskListView;
private ArrayAdapter<String> mAdapter;
Button myButton;
FloatingActionButton btnadd;
//Overriden method onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_two, container, false);
mHelper = new TaskDbHelper(getActivity());
mTaskListView = (ListView) view.findViewById(R.id.list_todo);
//Floating action button
btnadd = (FloatingActionButton) view.findViewById(R.id.btnadd);
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText taskEditText = new EditText(getActivity());
AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setTitle("Add a new task")
.setMessage("What do you want to do next?")
.setView(taskEditText)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String task = String.valueOf(taskEditText.getText());
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
db.insertWithOnConflict(TaskContract.TaskEntry.TABLE,
null,
values,
SQLiteDatabase.CONFLICT_REPLACE);
db.close();
updateUI();
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
}
});
updateUI();
return view;
}
#Override
public void onActivityCreated(Bundle saved){
super.onActivityCreated(saved);
final LayoutInflater factory = getActivity().getLayoutInflater();
final View textEntryView = factory.inflate(R.layout.item_todo, null);
myButton = (Button) textEntryView.findViewById(R.id.task_delete);
myButton.setOnClickListener(new View.OnClickListener() {
// OnClick() Not Working !!
#Override
public void onClick(View view) {
deleteTask(view);
}
});
}
public void deleteTask(View view) {
View parent = (View) view.getParent();
TextView taskTextView = (TextView) parent.findViewById(R.id.task_title);
String task = String.valueOf(taskTextView.getText());
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(TaskContract.TaskEntry.TABLE,
TaskContract.TaskEntry.COL_TASK_TITLE + " = ?",
new String[]{task});
db.close();
updateUI();
}
private void updateUI() {
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase db = mHelper.getReadableDatabase();
Cursor cursor = db.query(TaskContract.TaskEntry.TABLE,
new String[]{TaskContract.TaskEntry._ID, TaskContract.TaskEntry.COL_TASK_TITLE},
null, null, null, null, null);
while (cursor.moveToNext()) {
int idx = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
taskList.add(cursor.getString(idx));
}
if (mAdapter == null) {
mAdapter = new ArrayAdapter<>(getActivity(),
R.layout.item_todo,
R.id.task_title,
taskList);
mTaskListView.setAdapter(mAdapter);
} else {
mAdapter.clear();
mAdapter.addAll(taskList);
mAdapter.notifyDataSetChanged();
}
cursor.close();
db.close();
}}
Fragment_two XML
<ListView
android:id="#+id/list_todo"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="16dp"
android:layout_marginRight="16dp"
android:orientation="horizontal" >
<android.support.design.widget.FloatingActionButton
android:layout_width="50dp"
android:id="#+id/btnadd"
android:layout_height="50dp"
app:fabSize="normal"
android:clickable="true"
android:src="#drawable/red"
android:scaleType="center"
/>
</LinearLayout>
</RelativeLayout>
item_todo XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical">
<TextView
android:id="#+id/task_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:text="Hello"
android:textSize="20sp" />
<Button
android:id="#+id/task_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:text="Done" />
</RelativeLayout>
You inflate a new View in your onActivityCreated But you never used that view !!! myButton refer to a button which its view has not been used !
Edit :
There are lots of ways you can reach your goal:
Interfaces
You can initialize an interface and pass it to fragment, so whenever something happen in your activity (button click for example), you will understand
BroadcastReceivers
You can register local broadcast receivers in your fragment and when user click on the button, you send that broadcast, so fragment will understand
i suggest the second one and using EVENTBUS library

Listview and button hidden

Well, I try to explain.
I made an application where I have a listview where each row have also two buttons (I have made it with other question posted in this site).
The problem is this:
The two buttons is "start" and "stop". When I click start, a service starts and when I click on stop this service has to stop (I haven't implemented the service for now).
So, when I click start, I would like to hide the start button, in this way I know that the service is started.
How can I do it? Besides, it can be the right choice implements the service in this way?
I have choosen this idea because I need to stop the service when I decide to stop it.
Code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//generate list
ArrayList<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
//instantiate custom adapter
android.widget.ListAdapter adapter = new ListAdapter(this,0,list);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.list_item);
lView.setAdapter(adapter);
}
}
activity_main.xml:
<?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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.sara.myapplication.MainActivity">
<ListView
android:id="#+id/list_item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
row_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="Text"
android:id="#+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5pt"
android:layout_marginTop="2pt"
android:textSize="10pt"
android:layout_weight="0.49"/>
<Button
android:text="Start"
android:id="#+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:text="Stop"
android:id="#+id/stop_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/start_button"/>
</LinearLayout>
ListAdapter.java
public class ListAdapter extends ArrayAdapter<String> {
private ArrayList<String> list;
private int layout;
private Context context;
public ListAdapter(Context context, int resource, ArrayList<String> objects) {
super(context, resource, objects);
context = context;
layout = resource;
list = objects;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
view = inflater.inflate(R.layout.row_item, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.stop_button);
Button addBtn = (Button)view.findViewById(R.id.start_button);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "delete - Button was clicked for list item " + position, Toast.LENGTH_SHORT).show();
//do something
notifyDataSetChanged();
}
});
addBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "start - Button was clicked for list item " + position, Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
}
});
return view;
}
}
you can use some boolean flag value to change the visibility of button on click.
addBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "start - Button was clicked for list item " + position, Toast.LENGTH_SHORT).show();
//do something
addBtn.setVisibility(View.GONE);
notifyDataSetChanged();
}
});
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "delete - Button was clicked for list item " + position, Toast.LENGTH_SHORT).show();
//do something
addBtn.setVisibility(View.VISIBLE);
notifyDataSetChanged();
}
});
In this way seems working
If on your list you have more than one element, then you have to implement a custom adapter and create an ad hoc listner for each element. Use setTag and getTag.
CHange row_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="Text"
android:id="#+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5pt"
android:layout_marginTop="2pt"
android:textSize="10pt"
android:layout_weight="0.49"/>
<Button
android:text="Start"
android:id="#+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="start"/>
<Button
android:text="Stop"
android:id="#+id/stop_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/start_button"
android:onClick="stop"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/start_button" />
</LinearLayout>
And in MainAcitivty
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//generate list
ArrayList<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
//instantiate custom adapter
ListAdapter adapter = new ListAdapter(this, 0, list);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.list_item);
lView.setAdapter(adapter);
}
public void start(View v){
Button b = (Button) v;
v.setVisibility(View.INVISIBLE);
}
public void stop(View v){
}
}
ListAdapter
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
view = inflater.inflate(R.layout.row_item, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.stop_button);
Button addBtn = (Button)view.findViewById(R.id.start_button);
return view;
}
You need to use the setVisible(false) method
Example:
addBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "start - Button was clicked for list item " + position, Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
addBtn.setVisible(false); // ← Hide the "Start button"
}
});
To Hide start Button after clicking,
addBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "start - Button was clicked for list item " + position, Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
addBtn.setVisibility(View.GONE);
}
});

I can not perform Button click in custom listview with my custom arrayadapter

I have search a lot of questions here and already implemented every answer i get from here, but no one has solved this problem. I have 2 buttons in a row of my custom listview and i want to perform on click on them. Here is my custom adapter and xml code.
EDIT
CartAadpter.java
public class CartAdapter extends ArrayAdapter<CartItemListData> {
Context context;
int layoutResourceId;
ArrayList<CartItemListData> data = new ArrayList<CartItemListData>();
LayoutInflater mInflater;
CartItemListData listData;
CartDatabaseHelper db;
int i;
public CartAdapter(Context context, ArrayList<CartItemListData> data) {
super(context, R.layout.cart_listitems, data);
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
this.data = data;
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
mInflater = LayoutInflater.from(context);
convertView = mInflater.inflate(R.layout.cart_listitems, parent,
false);
holder = new ViewHolder();
holder.text = (TextView) convertView
.findViewById(R.id.cart_item_id);
holder.text1 = (TextView) convertView
.findViewById(R.id.cart_item_boxes);
holder.edit = (Button) convertView.findViewById(R.id.editdata);
holder.delete = (Button) convertView.findViewById(R.id.deletedata);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
listData = data.get(position);
// Button's Tag
holder.edit.setTag(data.get(position).getId());
holder.delete.setTag(data.get(position).getId());
// SetText to Textview
holder.text.setText(data.get(position).getTilesId());
holder.text1.setText(String.valueOf(listData.getNumberOfBox()));
Log.e("Database Data ID: ", listData.getId() + " " + position);
holder.edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
i = data.get(position).getId();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Edit Box");
builder.setMessage("Please Enter Number of Box.");
final EditText editText = new EditText(context);
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
editText.setLayoutParams(lp);
builder.setView(editText);
builder.setNegativeButton("Cancel", null);
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
if (editText.getText().toString() == null
&& editText.getText().length() == 0) {
Toast.makeText(
context,
"To delete Data use \"delete button\"",
Toast.LENGTH_LONG).show();
} else {
int data = Integer.parseInt(editText
.getText().toString());
if (data <= 0) {
Toast.makeText(
context,
"To delete Item Please use delete button",
Toast.LENGTH_LONG).show();
} else {
Log.e("Edited", "Yes");
CartDatabaseHelper cartDatabaseHelper = new CartDatabaseHelper(
context);
cartDatabaseHelper
.updateCart(new CartItemListData(
i, holder.text
.getText()
.toString(),
data));
CartAdapter.this.data.clear();
CartAdapter.this.data.add(listData);
notifyDataSetChanged();
}
}
}
});
builder.create().show();
}
});
holder.delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("Deleted", "Yes");
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Delete!!");
builder.setMessage("Deleting Item from List!!!");
builder.setIcon(R.drawable.ic_alerts_and_states_warning);
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
db = new CartDatabaseHelper(context);
db.delete_cartitem(data.get(position).getId());
data.remove(position);
notifyDataSetChanged();
}
});
builder.setNegativeButton("No", null);
builder.create().show();
}
});
return convertView;
}
static class ViewHolder {
TextView text, text1;
Button edit, delete;
}
}
cartlist_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/cart_item_id"
android:layout_width="0sp"
android:layout_height="fill_parent"
android:layout_marginLeft="2dp"
android:layout_weight="2"
android:background="#drawable/cart_list_text_background"
android:gravity="center_vertical|center_horizontal"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textSize="22sp" />
<TextView
android:id="#+id/cart_item_boxes"
android:layout_width="0sp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/cart_list_text_background"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textSize="22sp" />
<Button
android:id="#+id/editdata"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:background="#drawable/edit"
android:focusable="false" // Here I have checked it with true value too
android:focusableInTouchMode="false" />
<Button
android:id="#+id/deletedata"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:background="#drawable/ic_delete"
android:focusable="false"
android:focusableInTouchMode="false" />
MylistView:
<ListView
android:id="#+id/lvExp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:cacheColorHint="#FFFFFF"
android:childDivider="#f8dfdb"
android:choiceMode="singleChoice"
android:clipChildren="true"
android:clipToPadding="true"
android:divider="#ff2200"
android:dividerHeight="3dp"
android:drawSelectorOnTop="true"
android:fastScrollEnabled="true"
android:focusable="false"
android:footerDividersEnabled="true"
android:hapticFeedbackEnabled="true"
android:headerDividersEnabled="true"
android:scrollingCache="true"
android:soundEffectsEnabled="true"
android:textFilterEnabled="false"
android:transcriptMode="normal"
android:translationX="10dp" />
Can anyone tell me where did i make mistake? My work is about to finish and app is almost ready but i am stuck in this problem. I will be thankfull to any type of suggestion or help.
I am not sure,but Try holder.edit.setOnClickListener(new View.OnClickListener())
instead of holder.edit.setOnClickListener(new OnClickListener()).
try this
add this cartlist_row.xml in parent Linearlayout
android:clickable="false"
android:descendantFocusability="blocksDescendants"
android:focusable="false"
android:focusableInTouchMode="false"
for Button add this
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
and AlertDialog.Builder builder is not working , you never used show().. Please Cross check .. Use
AlertDialog alert = builder.create(); alert.show();

customised listview using arrayadapter class in android

how to select row item using Tick mark like iphone in android?iam using imageview in list_row.xml.when i click the list row item then i show image in row imageview.
if(getItem(position)!=null){
img.setvisibilty(View.Visible);}
else{System.out.println("imagenull");}
iam using this but image display in last row only.please help me how to select item using tickmark image.
public class DistanceArrayAdapter extends ArrayAdapter<Constant>{
public static String category,state,miles;
public ImageView img;
private Context context;
private int current = -1;
ArrayList<Constant> dataObject;
public DistanceArrayAdapter(Context context, int textViewResourceId,
ArrayList<Constant> dataObject) {
super(context, textViewResourceId, dataObject);
this.context=context;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView=convertView;
if(rowView==null){
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.category_row, parent, false);
}
//TextView textView = (TextView) rowView.findViewById(R.id.text1);
TextView textView1 = (TextView) rowView.findViewById(R.id.text2);
//textView.setText(""+getItem(position).id);
textView1.setText(""+getItem(position).caption);
img=(ImageView)rowView.findViewById(R.id.img);
img.setVisibility(View.GONE);
if(position%2==1)
{
rowView.setBackgroundResource(R.color.even_list);
}
else
{
rowView.setBackgroundResource(R.color.odd_list);
}
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(img.getVisibility()==View.GONE)
{
img.setVisibility(View.VISIBLE);
System.out.println("1");
}
if(img.getVisibility()==View.VISIBLE){
img.setVisibility(View.GONE);
System.out.println("12");
}
miles=getItem(position).caption;
System.out.println("miles"+miles);
}
});
return rowView;
}
}
Drawing from https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
String[] GENRES = new String[] {"Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama", "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"};
private CheckBoxAdapter mCheckBoxAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listView = (ListView) findViewById(R.id.lv);
listView.setItemsCanFocus(false);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(this);
mCheckBoxAdapter = new CheckBoxAdapter(this, GENRES);
listView.setAdapter(mCheckBoxAdapter);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
StringBuilder result = new StringBuilder();
for (int i = 0; i < GENRES.length; i++) {
if (mCheckBoxAdapter.mCheckStates.get(i) == true) {
result.append(GENRES[i]);
result.append("\n");
}
}
Toast.makeText(MainActivity.this, result, 1000).show();
}
});
}
public void onItemClick(AdapterView parent, View view, int position, long id) {
mCheckBoxAdapter.toggle(position);
}
class CheckBoxAdapter extends ArrayAdapter implements CompoundButton.OnCheckedChangeListener {
LayoutInflater mInflater;
TextView tv1, tv;
CheckBox cb;
String[] gen;
private SparseBooleanArray mCheckStates;
private SparseBooleanArray mCheckStates;
CheckBoxAdapter(MainActivity context, String[] genres) {
super(context, 0, genres);
mCheckStates = new SparseBooleanArray(genres.length);
mInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gen = genres;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return gen.length;
}
}
}
activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
And the XML file for the checkboxes:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="34dp"
android:text="TextView" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView1"
android:layout_marginRight="22dp"
android:layout_marginTop="23dp" />
</RelativeLayout>
When you click the button a toast message with list of item choosen is displayed. You can modify the above according to your requirements.
Set selection mode on your ListView
//if using ListActivity or ListFragment
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//or
myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//myListView is reference to your ListView
1.Make visibility gone to you tick mark image
2.Implement view.setOnClickListener in arrayadapter.
3.In that check image.getVisibility()==View.GONE then make image.setVisibity(View.Visible)
4.if image.getVisiblity()==View.VISIBLE then make your image.setVisibity(View.GONE)
Try this.

Categories