How to make Items in ListView editable via interface - android

I have a ListView (shown below) that has a list of ingredients and how much of each ingredient each item has. How can I make it so there is some way to edit the number value when clicking on each ingredient?
Context menu and alert dialog so far, I also considered buttons to match the items but discovered it didn't work with the infinite listview. Thank you to anyone who helps me with this!

If you want to save the these values then you can create a child class and create list of this of child class.
you can use the onItemClickListner to update the value in the object and then do notifydatasetchange on the adapter this will do the trick.
or
Alternatively you can pass the two list in the adapter and update the list you want to update and do notifydatasetchange.
for e.g.:-
//MainActivity
public class MainActivity extends AppCompatActivity {
ListView recView;
ArrayList<Childclass> chobj=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recView= (ListView) findViewById(R.id.recView);
chobj.add(new Childclass("Tomato sauce","0.0"));
chobj.add(new Childclass("Chicken","0.0"));
chobj.add(new Childclass("Olives","0.0"));
ListAdapter lstadptr=new ListAdapter(MainActivity.this,chobj);
recView.setAdapter(lstadptr);
recView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = MainActivity.this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.custom_dialog, null);
dialogBuilder.setView(dialogView);
final EditText edt = (EditText) dialogView.findViewById(R.id.edit1);
dialogBuilder.setTitle("Custom dialog");
dialogBuilder.setMessage("Enter text below");
dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//do something with edt.getText().toString();
chobj.get(position).setQuantity(edt.getText().toString());
((ListAdapter) recView.getAdapter()).notifyDataSetChanged();
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//pass
}
});
AlertDialog b = dialogBuilder.create();
b.show();
}
});
}}
Child Class
public class Childclass {
String name;
String quantity;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public Childclass(String name, String quantity) {
this.name = name;
this.quantity = quantity;
}}
ListAdapter
public class ListAdapter extends ArrayAdapter {
ArrayList<Childclass> chobj;
Context context;
public ListAdapter(#NonNull Context context,ArrayList<Childclass> chobj) {
super(context, R.layout.recyclerow, chobj);
this.context = context;
this.chobj = chobj;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View v;
LayoutInflater inflater = LayoutInflater.from(getContext());
v = inflater.inflate(R.layout.recyclerow, parent, false);
TextView tv= (TextView) v.findViewById(R.id.txtrow);
TextView tv1= (TextView) v.findViewById(R.id.txtrow1);
tv.setText(chobj.get(position).getName());
tv1.setText(chobj.get(position).getQuantity());
return v;
}}
activity main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.abhishek.kotlinprojecttest.MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f2f2f2"
android:paddingTop="10dp"
android:id="#+id/recView">
</ListView>
custom alert
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:orientation="vertical">
<EditText
android:id="#+id/edit1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text" />
list row
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="3dp"
android:layout_marginTop="3dp"
android:id="#+id/rowcd">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="listTExt"
android:id="#+id/txtrow"
android:textColor="#000000"
android:textSize="16sp"
android:gravity="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="listTExt"
android:id="#+id/txtrow1"
android:textColor="#000000"
android:textSize="16sp"
android:gravity="center"/>
</android.support.v7.widget.CardView>
Hope this will help you

Related

in Android Studio the Button in ListView does not work

I'm creating a shopping list similar to listonic app, but I'm stuck in listView, the button inside my listView does not read clicks but OnItemClickListener is working well. the objective is the user can save multiple shopping list for example grocery list, self-care list, etc. I have searched everywhere but did not find something that works.
here is the activity for the shopping list
private ArrayList<String> data = new ArrayList<String>();
private FloatingActionButton addList;
private ListView listView;
private TextView nList_name;
private DatabaseHelper dbHelper;
ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_lists);
dbHelper = new DatabaseHelper(this);
listView = findViewById(R.id.list_view);
addList = findViewById(R.id.add_list);
loadTaskList();
addList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
add_item();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(MyListsActivity.this, "list num "+position, Toast.LENGTH_SHORT).show();
}
});
}
private class MyListAdapter extends ArrayAdapter<String>
{
private final int layout;
public MyListAdapter(#NonNull Context context, int resource, #NonNull List<String> objects) {
super(context, resource, objects);
layout = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder viewHolder;
final int pos = position;
if (convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
viewHolder = new ViewHolder();
viewHolder.thumbnail = convertView.findViewById(R.id.list_item_thumbnail);
viewHolder.title = convertView.findViewById(R.id.list_item_text);
viewHolder.button = convertView.findViewById(R.id.list_item_btn);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.title.setText(getItem(position));
viewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MyListsActivity.this, "btn at row "+position, Toast.LENGTH_SHORT).show();
}
});
convertView.setTag(viewHolder);
return convertView;
}
}
public static class ViewHolder
{
ImageView thumbnail;
TextView title;
Button button;
}
private void add_item()
{
AlertDialog.Builder builder = new AlertDialog.Builder(MyListsActivity.this);
builder.setTitle("Add new list");
View v = LayoutInflater.from(MyListsActivity.this).inflate(R.layout.shop_list_dialog_item, null, false);
builder.setView(v);
TextInputEditText nList_name_edit_txt = v.findViewById(R.id.list_name_edit_txt);
TextInputLayout nList_name_layout = v.findViewById(R.id.list_name_layout);
builder.setPositiveButton("CREATE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i){}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {dialogInterface.cancel();}
});
AlertDialog dialog = builder.create();
dialog.show();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
String task = String.valueOf(nList_name_edit_txt.getText()).trim();
if (!TextUtils.isEmpty(nList_name_edit_txt.getText()))
{
dbHelper.insertNewTask(task);
loadTaskList();
dialog.cancel();
}
else{nList_name_layout.setError("Name your list");}
}
});
}
private void loadTaskList() {
ArrayList<String> taskList = dbHelper.getTaskList();
if(mAdapter==null){
mAdapter = new ArrayAdapter<String>(this, R.layout.list_wrapper_item, R.id.list_item_text, taskList);
listView.setAdapter(mAdapter);
}
else{
mAdapter.clear();
mAdapter.addAll(taskList);
mAdapter.notifyDataSetChanged();
}
}
}
this is the xml for the shopping list activity
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MyListsActivity">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/add_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="30dp"
android:layout_marginBottom="30dp"
android:clickable="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:srcCompat="#drawable/ic_baseline_add_24" />
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" >
</ListView>
</androidx.constraintlayout.widget.ConstraintLayout>
and this is the layout for the adapter
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants">
<ImageView
android:id="#+id/list_item_thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginTop="30dp"
android:layout_marginBottom="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_baseline_image_24" />
<TextView
android:id="#+id/list_item_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginTop="30dp"
android:layout_marginBottom="30dp"
android:textColor="#color/youtube"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/list_item_thumbnail"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/list_item_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_marginEnd="30dp"
android:layout_marginBottom="30dp"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Your MyListAdapter works as it should except int position should be final int position because button calls it from inner class.
The problem is that you are not using MyListAdapter. So change
mAdapter = new ArrayAdapter<String>(this, R.layout.list_wrapper_item, R.id.list_item_text, taskList);
To
mAdapter = new MyListAdapter(this, R.layout.list_wrapper_item, taskList);

Android RecyclerView doesn't show cardview on the screen

I have a database, and I am trying to show the columns on cardview on my app.
Nothing wrong database side I guess. I have checked it, for example I can add items to the database. I can login-register. But when I add my items, I should be seeing them on the cardview after addition process.
When I add item on the database, it goes back to the recyclerview layout but shows nothing. Only an empty page.
No errors on the debug process until now.
Here is my cardview layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:padding="15dp"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="#+id/itemName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stock Name"
android:textColor="#color/colorPrimary" />
<TextView
android:id="#+id/barcode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stock Code" />
<TextView
android:id="#+id/tvQuantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Quantity" />
<TextView
android:id="#+id/tvPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Price" />
<TextView
android:id="#+id/tvCost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cost" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
recyclerlayout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
RECYCLER.JAVA
public class recycler extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private DatabaseHelper myDb;
private itemAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler);
myDb = new DatabaseHelper(this);
Intent intent =getIntent();
mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.home_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.addMenu:
goToAddActivity();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void goToAddActivity(){
Intent intent = new Intent(recycler.this, add.class);
startActivity(intent);
}
}
itemAdapter.java
public class itemAdapter extends RecyclerView.Adapter<itemAdapter.ViewHolder> {
private List<list> mItemsList;
private Context mContext; //to inflate list layout
private RecyclerView mRecyclerV;
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView nameTxt;
public TextView quantityTxt;
public TextView priceTxt;
public TextView costTxt;
public TextView barcodeTxt;
public View layout;
public ViewHolder( View v) {
super(v);
layout = v;
nameTxt = (TextView) v.findViewById(R.id.itemName);
quantityTxt = (TextView) v.findViewById(R.id.tvQuantity);
priceTxt = (TextView) v.findViewById(R.id.tvPrice);
costTxt = (TextView) v.findViewById(R.id.tvCost);
barcodeTxt = (TextView) v.findViewById(R.id.barcode);
}
}
public void add(int position, list list) {
mItemsList.add(position, list);
notifyItemInserted(position);
}
public void remove(int position) {
mItemsList.remove(position);
notifyItemRemoved(position);
}
// Provide a suitable constructor (depends on the kind of dataset)
public itemAdapter(List<list> myDataset, Context context, RecyclerView recyclerView) {
mItemsList = myDataset;
mContext = context;
mRecyclerV = recyclerView;
}
// Create new views (invoked by the layout manager)
#Override
public itemAdapter.ViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
//create a new view
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v =inflater.inflate(R.layout.activity_list, parent, false);
// set the view's size, margins, paddings and layout parameters
return new ViewHolder(v);
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
final list list = mItemsList.get(position);
holder.nameTxt.setText("Stock Name: " + list.getName());
holder.barcodeTxt.setText("Barcode: " + list.getBarcode());
holder.quantityTxt.setText("Quantity: " + list.getQuantity());
holder.priceTxt.setText("Price: " + list.getPrice());
holder.costTxt.setText("Cost: " + list.getCost());
holder.layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("Choose option");
builder.setMessage("Update or delete stock?");
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//go to update activity
goToUpdateActivity(list.getId());
}
});
builder.setNeutralButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DatabaseHelper dbHelper = new DatabaseHelper(mContext);
dbHelper.deleteRecord(list.getId(), mContext);
mItemsList.remove(position);
mRecyclerV.removeViewAt(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mItemsList.size());
notifyDataSetChanged();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
});
}
private void goToUpdateActivity(long listID){
Intent goToUpdate = new Intent(mContext, update.class);
goToUpdate.putExtra("listID", listID);
mContext.startActivity(goToUpdate);
}
#Override
public int getItemCount() {
return mItemsList.size();
}
}

setOnItemClickListener() not working on ListView (select always first row)

I have created a custom ListView by extending LinearLayout for every row (Contact) and i need to select the item, but the method "setOnItemClickListener()" not working. I have just put a onItemSelectedListener under and now the method "setOnItemClickListener" select always the first item though i select other row
MainActivity:
public class MainActivity extends AppCompatActivity {
private ListView lvPhone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvPhone = (ListView)findViewById(R.id.listPhone);
final List<PhoneBook> listPhoneBook = new ArrayList<PhoneBook>();
listPhoneBook.add(new PhoneBook(BitmapFactory.decodeResource(getResources(),R.drawable.image),"Contact_1","123456789","av1#gmail.com","1"));
listPhoneBook.add(new PhoneBook(BitmapFactory.decodeResource(getResources(),R.drawable.image),"Contact_2","123456789","av2#gmail.com","2"));
listPhoneBook.add(new PhoneBook(BitmapFactory.decodeResource(getResources(),R.drawable.image),"Contact_3","123456789","av3#gmail.com","3"));
final PhoneBookAdapter adapter = new PhoneBookAdapter(this, listPhoneBook);
lvPhone.setAdapter(adapter);
lvPhone.setItemsCanFocus(false);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Dialog d = new Dialog(MainActivity.this);
d.setTitle("Login");
d.setCancelable(true);
d.setContentView(R.layout.account);
d.show();
Button button_close = (Button) d.findViewById(R.id.DCancel);
button_close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
d.dismiss();
}
});
Button button_login = (Button) d.findViewById(R.id.DLogin);
button_login.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String mName = new String("Ciao");
String mPhone;
String mEmail;
String mID;
TextView TextName = (TextView) d.findViewById(R.id.DName);
TextView TextPhone = (TextView)d.findViewById(R.id.DPhone);
TextView TextEmail = (TextView)d.findViewById(R.id.DEmail);
TextView TextID = (TextView)d.findViewById(R.id.DID);
mName=TextName.getText().toString();
mPhone=TextPhone.getText().toString();
mEmail=TextEmail.getText().toString();
mID=TextID.getText().toString();
listPhoneBook.add(new PhoneBook(BitmapFactory.decodeResource(getResources(),R.drawable.image),mName,mPhone,mEmail,mID));
lvPhone.setAdapter(adapter);
d.dismiss();
}
});
}
});
lvPhone.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView TextName = (TextView) view.findViewById(R.id.tvName);
TextView TextPhone = (TextView)view.findViewById(R.id.tvPhone);
TextView TextEmail = (TextView)view.findViewById(R.id.tvEmail);
TextView TextID = (TextView)view.findViewById(R.id.tvID);
String tvName = new String(TextName.getText().toString());
String tvPhone = new String(TextPhone.getText().toString());
String tvEmail = new String(TextEmail.getText().toString());
String tvID = new String(TextID.getText().toString());
Toast.makeText(MainActivity.this, tvName, Toast.LENGTH_SHORT).show();
}
});
lvPhone.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
PhoneBookAdapter:
public class PhoneBookAdapter extends BaseAdapter{
private Context mContext;
private List<PhoneBook> mListPhoneBook;
public PhoneBookAdapter (Context context, List<PhoneBook> list) {
mContext = context;
mListPhoneBook = list;
}
#Override
public int getCount() {
return mListPhoneBook.size();
}
#Override
public Object getItem(int position) {
return mListPhoneBook.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
PhoneBook entry = mListPhoneBook.get(position);
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.phonebook_row,null);
}
ImageView ivAvatar = (ImageView)convertView.findViewById(R.id.imgAvatar);
ivAvatar.setImageBitmap(entry.getmAvatar());
TextView tvName = (TextView)convertView.findViewById(R.id.tvName);
tvName.setText(entry.getmName());
TextView tvPhone = (TextView)convertView.findViewById(R.id.tvPhone);
tvPhone.setText(entry.getmPhone());
TextView tvEmail = (TextView)convertView.findViewById(R.id.tvEmail);
tvEmail.setText(entry.getmEmail());
TextView tvID = (TextView)convertView.findViewById(R.id.tvID);
tvID.setText(entry.getmID());
return convertView;
}
}
`
PhoneBook_row:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true">
<ImageView
android:id="#+id/imgAvatar"
android:layout_width="70dp"
android:layout_height="70dp"
android:scaleType="fitCenter"
android:src="#drawable/image"
android:clickable="true"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:clickable="true">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvName"
android:textStyle="bold"
android:clickable="true"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvPhone"
android:textStyle="bold"
android:clickable="true"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvEmail"
android:textStyle="bold"
android:clickable="true"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvID"
android:textStyle="bold"
android:clickable="true"/>
</LinearLayout>
</LinearLayout>
Replace your PhoneBook_row.xml with the one I am putting up here, I have tried this and it worked for me. I have changed all your android:clickable="true" to android:clickable="false". The reason for doing this is, all of your child views consume click and the result is your parent view i.e ListView not getting the click event. Hope this helps.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="false">
<ImageView
android:id="#+id/imgAvatar"
android:layout_width="70dp"
android:layout_height="70dp"
android:scaleType="fitCenter"
android:src="#drawable/image"
android:clickable="false"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:clickable="false">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvName"
android:textStyle="bold"
android:clickable="false"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvPhone"
android:textStyle="bold"
android:clickable="false"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvEmail"
android:textStyle="bold"
android:clickable="false"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvID"
android:textStyle="bold"
android:clickable="false"/>
</LinearLayout>
</LinearLayout>
Looks like you are missing the override.
Add an #Override before the function as shown below.
lvPhone.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
Also adding android:clickable = true in the layout file wouldn't be necessary.
You have changed your question , anyway i believe you can now get the item selected listener working. To get the item which is selected you can use the position as below
lvPhone.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
PhoneBook phoneBook = listPhoneBook.get(position);
Toast.makeText(MainActivity.this, phoneBook.getName() , Toast.LENGTH_SHORT).show();
//where getName is a function to get the name in the phonebook class
}
});

Android - SetOnItemClickListener doesn't work

I know here we have a lot of questions like mine, but I don't know why none works for me.
My objective: I have an AlertDialog with a ListView with a check box in each row, I can select some of the items, and I wish to make an ArrayList with the elements selected.
For that reason, I'm calling the SetOnclickListener, I put a Log inside the method, but does nothing.
I tried with focusable and clickable almost everywhere, but my Log doesn't appear.
Here My alert Dialog
private void callAdditionalDialog() {
LayoutInflater layoutInflater = LayoutInflater.from(ConfigProductActivity.this);
final View additionalView = layoutInflater.inflate(R.layout.dialog_additional, null);
additionalView.setFocusable(true);
// set the custom dialog components - text, buttons, accountants
TextView titleDialog = (TextView) additionalView.findViewById(R.id.title_additional);
titleDialog.setTypeface(boldFont);
Button buttonAccept = (Button) additionalView.findViewById(R.id.button_accept);
buttonAccept.setTypeface(boldFont);
Button buttonCancel = (Button) additionalView.findViewById(R.id.button_cancel);
buttonCancel.setTypeface(boldFont);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ConfigProductActivity.this);
alertDialogBuilder.setView(additionalView);
final AlertDialog alertD = alertDialogBuilder.create();
alertD.setCanceledOnTouchOutside(false);
//Fill object of additional
final ListView additionalListView = (ListView) additionalView.findViewById(R.id.list_additional);
TextView additionalNotFound = (TextView) additionalView.findViewById(R.id.additional_not_found);
if (!withoutModifiers){
additionalAdapter = new AdditionalAdapter(ConfigProductActivity.this, additionalList);
additionalListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
additionalListView.setAdapter(additionalAdapter);
final ArrayList<ModifierEntity> modifierList = new ArrayList<ModifierEntity>();
additionalListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
Object modifier = additionalListView.getAdapter().getItem(position).toString();
Log.d(TAG, "SOMETHIIIIING");
}
});
}
else{
additionalListView.setVisibility(View.GONE);
additionalNotFound.setVisibility(View.VISIBLE);
additionalNotFound.setTypeface(font);
buttonCancel.setVisibility(View.GONE);
}
//End of fill object of additional
buttonCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
additionalBox.setEnabled(true);
alertD.dismiss();
}
});
buttonAccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//additional.setText(additionalAdapter.getCount());
additionalBox.setEnabled(true);
alertD.dismiss();
}
});
alertD.show();
}
Here my adapter:
public class AdditionalAdapter extends ArrayAdapter {
private static String TAG = AdditionalAdapter.class.getName();
private List<ModifierEntity> originalData = null;
private ConfigProductActivity activity;
private Typeface font;
private Typeface boldFont;
private static ModifierEntity modifier;
public AdditionalAdapter (ConfigProductActivity activity, List<ModifierEntity> listArray){
super(activity, R.layout.additional_item);
this.activity = activity;
this.originalData = listArray ;
font = Typeface.createFromAsset(activity.getAssets(),"HelveticaNeueThn.ttf");
boldFont = Typeface.createFromAsset(activity.getAssets(), "avgardm.ttf");
}
public static class Row
{
public TextView labelName;
public TextView labelPrice;
public CheckBox check;
}
#Override
public int getCount() {
return originalData.size();
}
#Override
public ModifierEntity getItem(int position) {
return originalData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int colorFont = activity.getResources().getColor(R.color.brown_tataki);
final Row holder;
View rowView = convertView;
// reuse views
if (convertView == null) {
holder = new Row();
LayoutInflater inflater = LayoutInflater.from(activity);
rowView = inflater.inflate(R.layout.additional_item, null);
rowView.setClickable(true);
//rowView.setFocusable(false);
// configure view holder
holder.labelName = (TextView) rowView.findViewById(R.id.additional_name);
holder.labelPrice = (TextView) rowView.findViewById(R.id.additional_price);
holder.check = (CheckBox) rowView.findViewById(R.id.additional_check);
rowView.setTag(holder);
}
else {
holder = (Row) convertView.getTag();
// rowView.setClickable(true);
}
final ModifierEntity itm = originalData.get(position);
holder.labelName.setText(itm.getModifier_name());
holder.labelName.setTypeface(font);
holder.labelName.setTextColor(colorFont);
holder.labelPrice.setText(GlobalParameters.CURRENCY.concat(String.valueOf(itm.getModifier_cost())));
holder.labelPrice.setTypeface(boldFont);
holder.labelPrice.setTextColor(colorFont);
return rowView;
}
}
Here My Dialog
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:background="#color/white">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/orange_tataki"
android:text="#string/additional_title"
android:textColor="#color/white"
android:textSize="20sp"
android:gravity="center"
android:id="#+id/title_additional"
android:padding="5dp"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/title_additional"
android:gravity="center"
android:background="#color/white"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/list_additional"
android:divider="#color/brown_tataki"
android:dividerHeight="0.5dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/list_additional"
android:gravity="center"
android:padding="10dp"
android:visibility="gone"
android:textColor="#color/brown_tataki"
android:id="#+id/additional_not_found"
android:text="#string/additional_not_found"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/buttons"
android:layout_marginBottom="10dp"
android:layout_below="#+id/additional_not_found"
android:gravity="center"
android:layout_marginTop="20dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:id="#+id/button_cancel"
android:background="#color/green_tataki"
android:text="#string/button_cancel"
android:textSize="15sp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button_accept"
android:padding="10dp"
android:background="#color/green_tataki"
android:text="#string/button_accept"
android:textSize="15sp"
android:layout_marginLeft="15dp"
/>
</LinearLayout>
</RelativeLayout>
And Here my item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
>
<TextView
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="QUESO"
android:singleLine="true"
android:padding="10dp"
android:textColor="#color/brown_tataki"
android:id="#+id/additional_name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/additional_price"
android:padding="10dp"
android:text="Bs. 500"
android:textColor="#color/brown_tataki"
android:layout_toRightOf="#id/additional_name"
android:layout_marginLeft="10dp"
/>
<CheckBox
android:id="#+id/additional_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginLeft="8dp" />
Using interfaces I can solve my problem, this link provided me the solution, and bassically consist in create an interface and implement in my activity.
Like this:
1.- Interface
public interface MyListener {
void folderClicked();
}
2.- Implements the interface in the activity
public class ActivityA extends Activity implements MyListener
3.- You will have to auto override the method folderClicked it will look like this:
#Override
protected void folderClicked() {
// Do your stuff here.
}
4.- Send the activity listener to the adapter with constructor like this:
MyAdpater adapter = new MyAdpater(ActivityA.this);
5.- Your adapter class your code should be like this:
public class TimeLineAdapter extends BaseAdapter {
private MyListener mListener;
public TimeLineAdapter(MyListener listener) {
super();
mListener = listener;
}
holder.iconImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.onFolderClicked()
//code to do stuff when the image is clicked
}

multi select checkable dropdown check boxes in alert dailog in android

I am trying to alert multi selection dropdown check box in alert dialog like spinner but with check boxes in my android application ,can any one help here?
It may not work properly with respect to touch events. I guess that you will have to clone it and develop something like MultiSelectSpinner. You might wanna consult this answer for further detail.
Use customlayout in AlertDialog class using api, dialog.setconteView() method. You can add whatever widgets you wish in your custom layout
Use below code:-
AlertDialog.Builder builder = new AlertDialog.Builder(
context);
builder.setTitle("Title");
builder.setMultiChoiceItems(list, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog,
int indexSelected, boolean isChecked)
{
}
})
.setPositiveButton("OK",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog,
int id)
{
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id)
{
}
});
dialog = builder.create();
dialog.show();
As your view, Cant get the click events in AlertDialog.
Best solution for your Question. Just include the custom layout and get the Alertdialog Click events in your activity.
create a XML layout which you want to design
Include that XML layout in your activity through SetContentView()
Get the click events through your activity.
Please check this link for reference http://www.mkyong.com/android/android-custom-dialog-example/
Happy Coding :)
for Custom checkbox dropdown Dialogbox first we need to create MultiCheckAdaptar
public class MultiCheckAdaptar extends RecyclerView.Adapter<MultiCheckAdaptar.MyViewHolder> {
protected Context context;
private LayoutInflater inflater;
private ArrayList<ModelSpacialization> joblist ;
private String TYPE = "";
private int count = 0 ;
MultiCheckAdaptar.OnItemClickListener listener;
public interface OnItemClickListener {
void onClick(ModelSpacialization jobs, int pos , boolean type);
}
public MultiCheckAdaptar(Context context, ArrayList<ModelSpacialization> list, MultiCheckAdaptar.OnItemClickListener listener) {
this.context = context;
this.listener = listener;
if (context != null) {
inflater = LayoutInflater.from(context);
this.joblist= new ArrayList<>();
this.joblist.addAll(list);
}
}
public MultiCheckAdaptar.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.layout_ckeck_item , parent, false);
MultiCheckAdaptar.MyViewHolder holder = new MultiCheckAdaptar.MyViewHolder(view);
return holder;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public void onBindViewHolder(#NonNull final MultiCheckAdaptar.MyViewHolder holder, final int position) {
ModelSpacialization item = joblist.get(position);
holder.txt_item.setText(item.getName());
if(item.isCheck())
holder.txt_item.setChecked(true) ;
else
holder.txt_item.setChecked(false) ;
holder.txt_item.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
listener.onClick(item, position, false);
}
});
}
#Override
public int getItemCount() {
return joblist.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
CheckBox txt_item ;
public MyViewHolder(View itemView) {
super(itemView);
txt_item = itemView.findViewById(R.id.txt_item);
}
}
}
layout_check_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="#+id/txt_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="#dimen/size_10"
android:text="text"
android:textSize="#dimen/size_16" />
</RelativeLayout>
dialog_dropdwon_recyle.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:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:text="TItle"
android:id="#+id/tv_dialogTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textColor="#color/primary"
android:fontFamily="#font/poppins_medium"
android:textSize="#dimen/size_16"
tools:ignore="SpUsage" />
<ImageButton
android:id="#+id/btn_dialog_close"
android:layout_width="#dimen/size_25"
android:layout_height="#dimen/size_25"
android:layout_alignParentEnd="true"
android:layout_gravity="right"
android:background="#drawable/btn_grey_transparent"
android:elevation="1dp"
android:padding="#dimen/size_5"
android:src="#drawable/ic_close" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/btn_dialog_close"
android:paddingHorizontal="#dimen/size_5"
android:orientation="vertical">
<EditText
android:id="#+id/edit_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search..."
android:visibility="gone" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/dialog_list"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/size_10"
android:scrollbars="none" />
<Button
android:id="#+id/btn_save"
android:layout_width="match_parent"
android:layout_height="#dimen/size_40"
android:layout_marginHorizontal="#dimen/size_10"
android:layout_marginTop="#dimen/size_10"
android:layout_marginBottom="#dimen/size_10"
android:background="#drawable/button_primary"
android:fontFamily="#font/poppins_medium"
android:text="Save"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="#dimen/size_15" />
</LinearLayout>
</RelativeLayout>
in Activity
Dialog dg_industries = new Dialog(context);
selected_spaci = new HashSet<>();
industresList.addAll(industries2);
selected_spaci = new HashSet<>();
dg_industries.setContentView(R.layout.dailogbox_dwondwon_recycle);
final RecyclerView indview = (RecyclerView) dg_industries.findViewById(R.id.dialog_list);
final TextView title = (TextView) dg_industries.findViewById(R.id.tv_dialogTitle);
title.setVisibility(View.VISIBLE);
title.setText("Select Specialization");
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
indview.setLayoutManager(linearLayoutManager);
adaptor = new MultiCheckAdaptar(context, industresList, new MultiCheckAdaptar.OnItemClickListener() {
#Override
public void onClick(ModelSpacialization jobs, int pos, boolean type) {
jobs.setCheck(type);
selected_spaci.add(jobs);
Log.e("industries2", new Gson().toJson(industresList));
}
});
dg_industries.setCancelable(false);
dg_industries.show();

Categories

Resources