I want to use custom dialog at list view - android

I'm making a list view using a custom adapter.
In that, I want show a dialog when each item is clicked (surely, a different dialog at each list).
Here is my code.
MainActivity:
public class MainActivity extends AppCompatActivity {
ListView listView;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<MyCustomList> list = new ArrayList<MyCustomList>();
list.add(new MyCustomList("a", R.string.jangho_string1, R.string.jangho_string2, R.drawable.jangho));
list.add(new MyCustomList("b", R.string.dae_string1, R.string.dae_string2, R.drawable.dae));
list.add(new MyCustomList("c", R.string.an_string1, R.string.an_string2, R.drawable.an));
listView = (ListView)findViewById(R.id.listviewone);
MyCustomAdapter adapter = new MyCustomAdapter(getApplicationContext(), R.layout.listviewone, list);
listView.setAdapter(adapter);
}
}
MyCustomAdapter
public class MyCustomAdapter extends BaseAdapter {
Context ctx;
int layout;
ArrayList<MyCustomList> list;
LayoutInflater inf;
public MyCustomAdapter(Context ctx, int layout, ArrayList<MyCustomList> list){
this.ctx = ctx;
this.layout = layout;
this.list = list;
inf = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(final int position, View convertView, ViewGroup parent){
if(convertView == null){
convertView = inf.inflate(layout, null);
}
final View.OnClickListener makeListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
((Activity)ctx).showDialog(position);
}
};
convertView.setOnClickListener(makeListener);
return convertView;
}
protected Dialog onCreateDialog(int position){
Dialog dialog = null;
switch (position){
case 0:
break;
}
return dialog;
}
}
I'm using Android Studio.

you can create a method to show dialog, and pass the values from the listItem which is clicked
public void showDialog(Context context, String something){
Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_layout);
//Initialize your widgets from layout here
dialog.show();
//You can dialog.dismiss() to close the dialog.
}

Firstly,use ViewHolder when using listview. And just use listview.setOnItemClickListener

try this to create Custom Dialog
final Dialog dialog = new Dialog(MainActivity.this);
// Include dialog.xml file
dialog.setContentView(R.layout.forgotpassword);
// Set dialog title
dialog.setTitle("ALERT!!");
// set values for custom dialog components - text, image and button
Button okbtn = (Button) dialog.findViewById(R.id.okbtn);
Button cancelbtn = (Button) dialog.findViewById(R.id.cancelbtn);
final EditText emailedittext = (EditText) dialog.findViewById(R.id.emailedittext);
dialog.show();
dialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
// if decline button is clicked, close the custom dialog
cancelbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Close dialog
dialog.dismiss();
}
});
okbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email=emailedittext.getText().toString();
//do something more here
}
});
Refer here:- http://coderzpassion.com/android-show-alertdialog/

Related

How to make dynamically add or remove edit text in listview

public class SoloPlayActivity extends BaseActivity implements View.OnClickListener{
private ListView case_list;
private RelativeLayout add_case;
private TextView num_case_textview;
private Button start_button;
ArrayList<ItemSoloplayCase> caseArrayList;
AdapterSoloplay adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_solo_play);
initView();
//처음에는 경우의 수가 아무것도 없음
num_case_textview.setText("0");
caseArrayList = new ArrayList<ItemSoloplayCase>();
adapter = new AdapterSoloplay(this, caseArrayList, num_case_textview);
case_list.setAdapter(adapter);
}
private void initView(){
add_case = (RelativeLayout)findViewById(R.id.add_case);
add_case.setOnClickListener(this);
num_case_textview = (TextView)findViewById(R.id.num_case);
start_button = (Button)findViewById(R.id.game_start);
start_button.setOnClickListener(this);
case_list = (ListView)findViewById(R.id.case_list);
//리스트뷰에서 포커스를 잃지 않도록 한다.
case_list.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
}
#Override
protected String getActionbarTitle() {
return getString(R.string.solo_play_name);
}
//뒤로가기가 눌렸을때 추가한 경우의 수가 있을경우에만 다이얼로그 띄우고 경우의수가 비었다면 그냥 종료
#Override
public void onBackPressed() {
if (!caseArrayList.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("입력한 경우의 수는 모두 사라집니다. 정말로 닫겠습니까?")
.setCancelable(false)
.setPositiveButton("확인", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SoloPlayActivity.this.finish();
}
})
.setNegativeButton("취소", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
else
SoloPlayActivity.this.finish();
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.game_start:
Toast.makeText(getApplicationContext(), "게임시작 버튼 누름", Toast.LENGTH_SHORT);
break;
case R.id.add_case:
//경우의수 추가
ItemSoloplayCase additem = new ItemSoloplayCase();
caseArrayList.add(additem);
num_case_textview.setText(Integer.toString(caseArrayList.size()));
adapter.notifyDataSetChanged();
break;
}
}}
activity file.
Adapter file.
public class AdapterSoloplay extends BaseAdapter {
private Context context;
private ArrayList<ItemSoloplayCase> caselist;
private TextView num_case;
//순서 갱신 오류, 해당 지운 에디트가 지워지지 않음
public AdapterSoloplay(Context context, ArrayList<ItemSoloplayCase> caselist, TextView num_case) {
this.context = context;
this.caselist = caselist;
this.num_case = num_case;
}
#Override
public int getCount() {
return caselist.size();
}
#Override
public Object getItem(int position) {
return caselist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Viewholder holder;
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_case_input, parent, false);
holder = new Viewholder();
holder.order = (TextView) convertView.findViewById(R.id.order_num);
holder.editText = (EditText)convertView.findViewById(R.id.input_case);
holder.button_clear = (ImageButton)convertView.findViewById(R.id.remove_case);
//순서는 현재 크기만큼
holder.order.setText(Integer.toString(getCount()));
convertView.setTag(holder);
}
else
holder = (Viewholder)convertView.getTag();
//클리어를 눌럿을때 제거하고 순서를 재정렬하고 갱신시킨다
holder.button_clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ItemSoloplayCase item = (ItemSoloplayCase)getItem(position);
item = null;
caselist.remove(position);
notifyDataSetChanged();
num_case.setText(Integer.toString(caselist.size()));
}
});
return convertView;
}
class Viewholder {
private EditText editText;
private TextView order;
private ImageButton button_clear;
}
}
i want to make dynamically add or remove edit text in list view. '
like image.
enter image description here
if i want remove second list(in this image, b) but it removed last data(in this image, d). and i click add button it makes last data..(in this image, makes edit text value d).
above is my code. help.
please help me.
Add a linearlayout to listview rows xml file :
For add dynamically EditText to this layout try this :
EditText editText = new EditText(context);
editText.setHint(hint);
editText.requestFocus();
editText.setSelection(editText.getText().length());
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
linearlayout.addview(editText);

How to get custom dialog activity while clicking on a button in listview in android?

here is my code for ArrayAdapter. When i click on LinearLayout "cat" it gives error on dialog.show(). I don't know how to create custom dialog within ArrayAdapter class.
Everything work fine when i remove creating dialog part.
Thanks in advance
CategoryAdapter.java
public class CategoryAdapter extends ArrayAdapter<String> {
private final Context context;
String[] menu = new String[25] ;
String[] menu2 = new String[25];
String[] menu3 = new String[25];
private LayoutInflater inflater;
viewholder vh;
public CategoryAdapter(Context context, String [] menu,String [] menu2,String [] menu3) {
super(context, R.layout.categoryadapter, menu);
this.context = context;
this.menu = menu;
this.menu2=menu2;
this.menu3=menu3;
}
public View getView(final int position, View convertView, ViewGroup parent) {
{
vh=new viewholder();
if (inflater == null)
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.categoryadapter, parent, false);
vh.cat=(LinearLayout) convertView.findViewById(R.id.category);
convertView.setTag(vh);
}
vh.cat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(getContext());
dialog.setContentView(R.layout.update_categore_dialog);
dialog.setTitle("Update Your Category");
dialog.show();
Toast.makeText(getContext(), "Clicked", Toast.LENGTH_LONG).show();
}
});
return convertView;
}
public class viewholder
{
LinearLayout cat;
}
}
Use context instead getContext()
final Dialog dialog = new Dialog(context);
Finally, Just pass context
vh.cat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.update_categore_dialog);
dialog.setTitle("Update Your Category");
dialog.show();
Toast.makeText(getContext(), "Clicked", Toast.LENGTH_LONG).show();
}
});
Try-
Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.update_categore_dialog);
dialog.setTitle("Update Your Category");
dialog.show();
try this below link, hope you like it.
OrderDetailListAdatper adapter = new OrderDetailListAdatper(Yourclass.this,Resource,
listorderlistInfo);
//set your adapter..
in your adapter getview, paste that code and it works fine for me.
holder.btnDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alert = new AlertDialog.Builder((Activity)_context);
alert.setMessage("Do you want to delete?");
alert.setNegativeButton("CANCEL",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int whichButton) {
dialog.cancel();
}
});
alert.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int whichButton) {
OrderDetailListAdatper.this._listOrderListInfoAdapter
.remove(position); OrderDetailListAdatper.thisnotifyDataSetChanged();
}
});
alert.create().show(); // btw show() creates and shows it..
}
});
In your getView() method, Replace getContext() with your context variable.
vh.cat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
//remaining code...
}
});
And in your initialization of CateogoryAdapter don't pass getApplicationContext(), instead pass in the context (Activity.this) like this.
CategoryAdapter adapter = CategoryAdapter(YourActivity.this, menu, menu2, menu3)

showDialog in button Listview adapter

i have a listView like THIS
i want when i press the delete. it show a dialog like this image
so when i press YES. it will remove from list.
here's my code..
public class customadapter extends BaseAdapter{
ArrayList<HashMap<String, String>> oslist;
Context context;
private Button btnDelete;
private Button btnEdit;
AlertDialog.Builder alertDialogBuilder;
public customadapter(ArrayList<HashMap<String, String>> oslist,Context context) {
System.out.println("skdjfhksdfjskfjhsdkjfh");
this.context = context;
this.oslist = oslist;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return oslist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return oslist.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
System.out.println("oslist oslist = "+oslist);
System.out.println("oslist 1 = "+oslist);
System.out.println("oslist size = "+oslist.size());
System.out.println("oslist oslist = "+oslist.getClass());
System.out.println("position = "+position);
System.out.println("convertView = "+convertView);
System.out.println("parent = "+parent);
System.out.println("position = "+position);
LayoutInflater lif = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = lif.inflate(R.layout.listitem, null);
TextView id = (TextView) convertView.findViewById(R.id.varId);
TextView noNota = (TextView) convertView.findViewById(R.id.varNoNota);
TextView senderName = (TextView) convertView.findViewById(R.id.varSenderName);
TextView totalAmount = (TextView) convertView.findViewById(R.id.varTotalAmount);
id.setText(oslist.get(position).get("id"));
noNota.setText(oslist.get(position).get("noNota"));
senderName.setText(oslist.get(position).get("senderName"));
totalAmount.setText(oslist.get(position).get("totalAmount"));
Button btnEdit = (Button) convertView.findViewById(R.id.btnEdit);
Button btnDelete = (Button) convertView.findViewById(R.id.btnDelete);
btnEdit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Edit ditekan!", Toast.LENGTH_LONG).show();
//I want show YES NO dialog here.
}
});
btnDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//I want show YES NO dialog here
}
});
return convertView;
}
}
how can i do to create a dialog like that..i tried this code
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
dialog.setTitle("Title...");
// set the custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Android custom dialog example!");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.ic_launcher); //line 115
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
but itsnt success.
i got this error
Create an interface:
public interface OnDeleteListener {
public void onDelete(String message);
}
When you are initializing customadapter send OnDeleteListener as a parameter:
private OnDeleteListener mListener;
public customadapter(ArrayList<HashMap<String, String>> oslist,Context context, OnDeleteListener mListener) {
this.context = context;
this.oslist = oslist;
this.mListener = mListener;
}
then on delete button click check for listener to whether activate it or not:
btnDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//I want show YES NO dialog here
if(mListener != null)
mListener.onDelete("The message you want to show");
}
});
and finally initialize adapter in your activity/fragment and on listener invoke show Dialog:
customadaper mAdapter = new customadapter(ArrayList<HashMap<String, String>> oslist,Context context, new OnDeleteListener(){
#Override
public void onDelete(String msg){
//Show your dialog here
//msg - you can send any parameter or none of them through interface just as an example i send a message to show
showDialog(msg);
}
});
You can create a seperate function for code clearance and call it whenever you want to use
(also notice that, to create a custom dialog you have to inflate it {probably thats why you are getting an error}):
private void showDialog(String message){
// set the custom dialog components - text, image and button
inflater = mInflater.inflate(R.layout.your_custom_dialog, null, false);
TextView text = (TextView) inflater.findViewById(R.id.text);
text.setText(message);
ImageView image = (ImageView) inflater.findViewById(R.id.image);
image.setImageResource(R.drawable.ic_launcher); //line 115
AlertDialog.Builder mDialogBuilder = new AlertDialog.Builder(context);
mDialogBuilder.setView(viewFilterDialog);
mDialogBuilder.setCancelable(true);
mDialogBuilder.setTitle(mRes.getString(R.string.dialog_title_filter));
...
final AlertDialog mAlertDialog = mDialogBuilder.create();
mAlertDialog.show();
note: I have hardcoded this answer so any syntax error can occur
try this code.For a Dialog you have to use Activity's instance not application context.
final Dialog dialog = new Dialog(youractivity.this);
dialog.setContentView(R.layout.custom);
first pass the activity like this.
list.setAdapter(new customadapter(oslist,getApplicationContext(),registerItem.this));
then get the parent activity like this..
private Activity parentActivity;
private Button btnDelete;
private Button btnEdit;
AlertDialog.Builder alertDialogBuilder;
public customadapter(ArrayList<HashMap<String, String>> oslist,Context context, Activity parentactivity) {
System.out.println("skdjfhksdfjskfjhsdkjfh");
this.context = context;
this.oslist = oslist;
this.parentActivity = parentactivity;
}
and set dialog builder like this..
final Dialog dialog = new Dialog(parentActivity);
You can also do this in activity. For Adapter code, add some tags to your button to identify which button is pressed. You can also set position as a tag.
Button btnEdit = (Button) convertView.findViewById(R.id.btnEdit);
Button btnDelete = (Button) convertView.findViewById(R.id.btnDelete);
btnEdit.setTag(oslist.get(position).get("id"),R.id.varId);
btnDelete .setTag(oslist.get(position).get("id"),R.id.varId);
You can add this in xml for your custom dialog.
android:onclick="deleteMethod"
Write your method in activity like this :
public void deleteMethod(View v)
{
// Get your id or position for which delete button was pressed
String id=v.getTag().toString();
new AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("Do you really want to delete ?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(MainActivity.this, "Deleting...", Toast.LENGTH_SHORT).show();
// You know which item to delete from id / position. delete here.
}})
.setNegativeButton(android.R.string.no, null).show();
}
I think there is a easy way to do this, in my case i have followed this code.
write a method alertMessage() and call this inside your button listener code
btnDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//I want show YES NO dialog here
alertMessage();
}
});
public void alertMessage() {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE: // Yes button clicked
Toast.makeText(AlertDialogActivity.this, "Yes Clicked",
Toast.LENGTH_LONG).show();
// set your own logic for removal item from listview
break;
case DialogInterface.BUTTON_NEGATIVE: // No button clicked // do nothing
Toast.makeText(AlertDialogActivity.this, "No Clicked",
Toast.LENGTH_LONG).show();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
dialog will dismiss itself after user click "YES" or "NO" button. There is nothing you need to do

Android "Dialog" instace is "null" when tried to "dismiss"

I have a custom dialog created inside an Adapter, which has two buttons ((+)ve and (-)ve), (+)ve vl call another service and (-)ve will simply dismiss the dialog.
public class BookingAdapter extends ArrayAdapter<BookingItem> {
private Dialog aDialog;
private Context context;
private Activity activity;
public BookingAdapter (Context context, int resource, List<BookingItem> objects) {
super(context, resource, objects);
this.context = context;
this.activity = (Activity) context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// some other tasks being done
onButtonClick(position, holder);
return convertView;
}
public void onButtonClick(final int position, ViewHolder viewHolder){
// some other tasks being done
makeDialog(name, id, date, cost);
}
public void makeDialog(final String name, final String Id, final String date, String cost){
Button confirmButton;
Button cancelAndReturnButton;
TextView confirmDialogBody;
aDialog = new Dialog(activity, R.style.Dialog_No_Border);
aDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
LayoutInflater m_inflater = LayoutInflater.from(activity);
View m_view = m_inflater.inflate(R.layout.casual_day_booking_confirm_dialog, null);
// set Buttons and Texts
View.OnClickListener m_clickListener = new View.OnClickListener(){
#Override
public void onClick(View p_v) {
switch (p_v.getId()) {
case R.id.confirm_and_proceed:
PlaceBookingTask bookingTask = new PlaceBookingTask(date,Id,context);
bookingTask.execute();
break;
case R.id.cancel_and_return:
aDialog.dismiss();
break;
default:
break;
}
}
};
aDialog.setContentView(m_view);
if(!activity.isFinishing()) {
aDialog.show();
}
}
#Subscribe
public void onSuccess(PlaceBookingEvent event){
PlaceBookingResponse response = event.getPlaceBookingResponse();
aDialog.dismiss();
secondConfirmationDialog(response.getName, response.getDate, response.getId);
}
public void secondConfirmationDialog(String name,String date,String id) {
// this will create another dialog
}
}
When onSuccess, aDialog.dismiss(), aDialog is null and cannot be dismissed.
i checked some similar questions in SO like this and this, i'm doubt that only AlertDialog.Builder is the solution for my problem.
Try removing the "private" in your variable.
I think your dialog implementation is wrong. Try with the following.
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
dialog.setTitle("Title...");
// set the custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Android custom dialog example!");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.ic_launcher);
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();

How to Show Dialog while user do Tap on List Item Row

whenever user do tap on list item row i am trying to show dialog, but getting nothing whenever i do click on list item row, why?
Here I just want to update value of total by accepting new qty from user in dialog via show that value in place of quantity in a List row ....
CartActivity.java:
public class CartActivity extends Activity {
ListView mLstView1;
CartAdapter mViewCartAdpt;
final private static int DIALOG_QUANTITY = 1;
EditText update_quantity ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
mLstView1 = (ListView) findViewById(R.id.listView1);
mViewCartAdpt = new CartAdapter(CartActivity.this);
mLstView1.setAdapter(mViewCartAdpt);
mLstView1.setOnItemClickListener(new OnItemClickListener() {
#SuppressWarnings("deprecation")
public void onItemClick(AdapterView<?> parent, View v,
final int position, long id)
{
showDialog(DIALOG_QUANTITY);
}
});
}
protected Dialog onCreateDialog(int id) {
AlertDialog dialogDetails = null;
switch (id) {
case DIALOG_QUANTITY:
LayoutInflater inflater = LayoutInflater.from(this);
View dialogview = inflater.inflate(R.layout.dialog_layout, null);
AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
dialogbuilder.setTitle("Image Information");
dialogbuilder.setView(dialogview);
dialogDetails = dialogbuilder.create();
break;
}
return dialogDetails;
}
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DIALOG_QUANTITY:
final AlertDialog alertDialog = (AlertDialog) dialog;
Button updateQuantityButton = (Button) alertDialog
.findViewById(R.id.btn_login);
Button cancelbutton = (Button) alertDialog
.findViewById(R.id.btn_cancel);
update_quantity = (EditText) alertDialog
.findViewById(R.id.edit_new_qty);
updateQuantityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
cancelbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
break;
}
}
// Called when the activity begins interacting with the user
#Override
protected void onResume(){
super.onResume();
mViewCartAdpt.notifyDataSetChanged();
}
}
CartAdapter.java:
public class CartAdapter extends BaseAdapter {
public static final String LOG_TAG = "CartAdapter";
public static final String KEY_TITLE = "title";
public static final String KEY_COST = "cost";
public static final String KEY_QTY = "qty";
public static final String KEY_TOTAL = "total";
Activity activity;
LayoutInflater inflater;
ImageButton mImgBtnDelete;
ListView listView;
private double itemamount = 0;
private int itemquantity = 0;
public CartAdapter(Activity a) {
// TODO Auto-generated constructor stub
activity = a;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
// TODO Auto-generated method stub
return Constants.sItem_Detail.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.listrow_cart, null); // listrow_cart
vi.setClickable(true);
vi.setFocusable(true);
vi.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
}
});
final TextView title = (TextView) vi.findViewById(R.id.title);
final TextView qty = (TextView) vi.findViewById(R.id.qty);
final TextView cost = (TextView) vi.findViewById(R.id.cost);
final TextView total = (TextView) vi.findViewById(R.id.total);
HashMap<String, String> item = new HashMap<String, String>();
item = Constants.sItem_Detail.get(position);
// Setting all values in listview
title.setText(item.get(com.example.sample.ItemsActivity.KEY_TITLE));
cost.setText(item.get(com.example.sample.ItemsActivity.KEY_COST));
qty.setText("1");
itemquantity = Integer.parseInt(qty.getText().toString());
itemamount = Double.parseDouble(cost.getText().toString());
total.setText(new DecimalFormat("##.#").format(itemamount*itemquantity));
return vi;
}
}
Take your Dialog inside your activity, where you have to do code for listiview click, inside click show your dialog,
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
//show dialog.
}
});
I can see, your dialog having two buttons and one editbox, and whatever values is to be input in editbox, you updating your list value with editbox value.
Grab editbox value and update your list array, which you are setting on adapter to fill your listview.
updateQuantityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// here you have to fetch editbox value and update your arraylist and then notify your adapter.
}
});
I believe this is because onCreateDialog() and onPrepareDialog() should be overriden in an activity, not in the adapter.
Since you declared activity to be of type Activity, calling activity.showDialog() won't have any effect.
What you have to do, is to move those methods in the activity you want the dialogs to be displayed, then pass to the CardAdapter and instance of your activity and use it in the adapter.
new CardAdapter(MyActivity.this);
//...
public class CardAdapter .... {
public MyActivity activity;
//.......
activity.showDialog
}
Though, I would suggest to use DialogFragment instead.
you can use this way when click on item of the list view then open the dialog box and whatever changes or update in list then use setNotifyDataChanged() before set the adapter on list view
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
yourActivty.this.showDialog(DIALOG_QUANTITY);
}
});

Categories

Resources