How to show the LayoutInflater in alert message? - java

This is my code for layoutInflater in alert message. When running on device, only OK and CANCEL buttons appear. The popup.xml (for layout) does not exist.
This is my code
public void onClick(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(reconfirm.this);
LayoutInflater layoutInflater
= (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null, false);
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intObj = new Intent(getApplicationContext(),
agree.class);
startActivity(intObj);
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intObj = new Intent(getApplicationContext(),
IntentExampleActivity.class);
startActivity(intObj);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
this is my popup.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="166dp"
android:orientation="vertical" >
</LinearLayout>
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.12"
android:text="By using any of the websites" />
<TextView
android:id="#+id/more"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.12"
android:linksClickable="true"
android:text="More" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="match_parent"
android:layout_height="92dp"
android:layout_weight="0.21"
android:text="I have read and agree to the Terms and Conditions." />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="114dp"
android:layout_margin="20dp"
android:orientation="vertical" >
</LinearLayout>

Possible duplicate: Using LayoutInflater and AlertDialog
It seems you are trying to load text from static TextView. May be it should be EditText?
TextView stax1=(TextView)dialogView.findViewById(R.id.xxx);
String sax1 = stax1.getText().toString();
EDITED:
Try this code:
lay1.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View v)
{
LayoutInflater myLayout = LayoutInflater.from(context);
final View dialogView = myLayout.inflate(R.layout.alerthelp, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setView(dialogView);
AlertDialog alertDialog = alertDialogBuilder.create();
Button button1 = (Button) alertDialog.findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
TextView stax1=(TextView)dialogView.findViewById(R.id.xxx);
String sax1 = stax1.getText().toString();
double sx1 = Double.parseDouble(sax1);
TextView textviewlay1 =(TextView)dialogView.findViewById(R.id.m1ab);
String stringl1 = textviewlay1.getText().toString();
Double doubl1 = Double.parseDouble(stringl1);
TextView textviewp1 = (TextView)dialogView.findViewById(R.id.inputPrice);
String stringp1 = textviewp1.getText().toString();
Double intp1 = Double.parseDouble(stringp1);
double resultl1 = intp1 - (doubl1*sx1);
int precision21t = 100; //keep 4 digits
resultl1= Math.floor(resultl1 * precision21t +.5)/precision21t;
textViewtotalproduct.setText(String.valueOf(resultl1));
}
});
return false;
}});

Try this
Dialog dialog = new Dialog(YourActivtyclass.this);
dialog.setContentView(R.layout.yourpopuplayout);
final TextView textView1= (TextView) dialog.findViewById(R.id.textView1);
dialog.show();
you can use this anywhere.And you can fully customize your alert dialog.

Related

Dialog with multiple textview

i need to add 5 text view in my code. For now there is only one and it is used to put a marker in google maps. I would like that in addition to this you could put another 4 data insertions like (description, age, work, hobbys).Below I also put the custom dialog I made can you check if it's okay? Feel free to ask for anything. How can I do?
add_address.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View viewcustom = getLayoutInflater().inflate(R.layout.custom_dialog, null);
EditText edt1 = view.findViewById(R.id.Description);
EditText edt2 = view.findViewById(R.id.Age);
EditText edt3 = view.findViewById(R.id.Hobby);
EditText edt4 = view.findViewById(R.id.City);
EditText edt5 = view.findViewById(R.id.address);
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(requireContext())
.setView(viewcustom)
.setPositiveButton("Ok", (dialogInterface, i) -> {
String description = edt1.getText().toString();
String age = edt2.getText().toString();
String Hobby = edt3.getText().toString();
String City = edt4.getText().toString();
String address = edt5.getText().toString();
Toast.makeText(requireContext(), description, Toast.LENGTH_SHORT).show();
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid()).child("address");
reference.setValue(address);
});
alertDialog.setNegativeButton("Cancel", null);
alertDialog.create().show();
//startAutoCompleteIntent();
}
});
Customdialog.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Text 1"
android:id="#+id/Description" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Text 2"
android:id="#+id/Age" />
<EditText
android:id="#+id/Hobby"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:hint="Text 3" />
<EditText
android:id="#+id/City"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Text 4" />
<EditText
android:id="#+id/Marker"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Text 5" />
</LinearLayout>
You have to provide your own custom view and then you have to retrieve your EditTexts with findViewByID()
View view = getLayoutInflater().inflate(R.layout.custom_dialog, null);
EditText edt1 = view.findViewById(R.id.Description);
// get other EditTexts here
final Dialog alertDialog = new Dialog(activity);
alertDialog.setView(view);
alertDialog.setPositiveButton("Ok", (dialogInterface, i) -> {
String description = edt1.getText().toString();
//other stuff
});
Entire sample inspired from your code
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(LayoutInflater.from(this));
setContentView(binding.getRoot());
binding.fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View viewcustom = getLayoutInflater().inflate(R.layout.custom_dialog, null);
EditText edt1 = viewcustom.findViewById(R.id.Description);
EditText edt2 = viewcustom.findViewById(R.id.Age);
EditText edt3 = viewcustom.findViewById(R.id.Hobby);
EditText edt4 = viewcustom.findViewById(R.id.City);
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this)
.setView(viewcustom)
.setPositiveButton("Ok", (dialogInterface, i) -> {
String description = edt1.getText().toString();
String age = edt2.getText().toString();
String Hobby = edt3.getText().toString();
String City = edt4.getText().toString();
Toast.makeText(MainActivity.this, description, Toast.LENGTH_SHORT).show();
});
alertDialog.setNegativeButton("Cancel", null);
alertDialog.create().show();
}
});
}
}

How get a value from AlertDialog in Preference

I have Settings class. And I use preference inside. In the preference I use AlertDialog which has EditText and radioButton in it.
I want to get the values of the edit text and the radio button from my settings activity, but everything I see online is just about preference OR AlertDialog and I don't understand what to do if they are combined.
my Settings.java:
public class Settings extends AppCompatActivity {
private RadioGroup radioGroup;
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_setting, new MySettingsFragment())
.commit();
}
public static class MySettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preference, rootKey);
}
#Override
public boolean onPreferenceTreeClick(Preference p){
final EditText input = new EditText(this.getContext());
if(p.getKey().equals("appointment type")){
return true;
}
if(p.getKey().equals("time frame")){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = requireActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.set_time, null)).
setPositiveButton(R.string.save_settings, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
**Here i dont know how to take the value**
}
})
.setNegativeButton(R.string.cancel_settings, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
my Prefernce.xml :
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference
android:key="appointment type"
android:title="Set appointment types"
android:icon="#drawable/appoitment_type"
/>
<Preference
android:id="#+id/timeFrame"
android:key="time frame"
android:title="Allow change meeting"
android:summary="Time frame where clients can't change a meeting"
android:onClick = "popUpWindow"
android:icon="#drawable/no_meetings_changes"
/>
<Preference
android:id="#+id/remindTime"
android:key="remind time"
android:title="Meetings reminder"
android:summary="How much time to remind client before a meeting"
android:icon="#drawable/send_reminder" />
</PreferenceScreen>
my setTime.xml (the dialog):
<?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:background="#color/colorPrimaryLight">
<EditText
android:id="#+id/num_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/default_num"
android:inputType="text" />
<RadioGroup
android:id="#+id/radio_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/minutes_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/minutes" />
<RadioButton
android:id="#+id/hours_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text = "#string/hours"/>
<RadioButton
android:id="#+id/days_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text = "#string/days"/>
<RadioButton
android:id="#+id/weeks_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text = "#string/weeks"/>
</RadioGroup>
</LinearLayout>
In your OnPreferenceTreeClick function in MySettingsFragment:
#Override
public boolean onPreferenceTreeClick(Preference p){
final EditText input = new EditText(this.getContext());
if(p.getKey().equals("appointment type")){
return true;
}
if(p.getKey().equals("time frame")){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = requireActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.set_time, null) // add this line
builder.setView(dialogView).
setPositiveButton(R.string.save_settings, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// take the value from selected radio button
RadioGroup radioGroup = (RadioGroup) dialogView.findViewById(R.id.radio_group);
int selectedId = radioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
RadioButton radioButton = (RadioButton) findViewById(selectedId);
// get edittext value
EditText edittext = (EditText) dialogView.findViewById(R.id.num_input);
String edittextValue = edittext.getText().toString();
}
})
.setNegativeButton(R.string.cancel_settings, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}

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

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();

Categories