Everything shows inside the dialog except the listview - android

I'm trying to have an edittext with a list view to choose contacts from a custom listview here is the code but everything appears except the listview:
InstantDialogBox:
public class InstantTextBoxDialog extends DialogFragment {
private EditText message;
private Button sendToAll;
private Button sendToLimited;
private ListView listContacts;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
LayoutInflater inflater=getActivity().getLayoutInflater();
View view=inflater.inflate(R.layout.intant_message,null,false);
message=(EditText)view.findViewById(R.id.instant_message);
sendToAll=(Button) view.findViewById(R.id.btn_sent_to_all);
listContacts=(ListView)view.findViewById(R.id.list_checkable);
ChackableListAdapter adapter=new ChackableListAdapter(getActivity(),R.layout.list_chackable_item,new ArrayList<Contact>());
sendToAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!TextUtils.isEmpty(message.getText())){
ChatService.bind.getService().sendMessageToAll(message.getText().toString());
message.setText("");
dismiss();
}
}
});
sendToLimited=(Button) view.findViewById(R.id.btn_send_to_limited);
sendToLimited.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!TextUtils.isEmpty(message.getText())){
}
}
});
listContacts.setAdapter(adapter);
builder.setView(view);
return builder.create();
}
CheckableListAdapter:
public class ChackableListAdapter extends ArrayAdapter<Contact> {
private ArrayList<Contact> contacts;
private int resource;
private Context context;
private ArrayList<Contact> choosen;
public ChackableListAdapter(#NonNull Context context, int resource,ArrayList<Contact> arrayList) {
super(context, resource,arrayList);
this.context=context;
this.resource=resource;
this.contacts=arrayList;
contacts= DatabaseHandler.getDataBaseHandler(context).getAllRegisteredContacts();
choosen=new ArrayList<>();
}
#Nullable
#Override
public Contact getItem(int position) {
return contacts.get(position);
}
#NonNull
#Override
public View getView(final int position, #Nullable View view, #NonNull ViewGroup parent) {
Holder holder=null;
if (view == null || view.getTag() == null) {
holder=new Holder();
view= LayoutInflater.from(context).inflate(resource,null);
holder.phone=(TextView)view.findViewById(R.id.text_number);
holder.name=(CheckBox)view.findViewById(R.id.checkbox_number);
view.setTag(holder);
}
else {
holder = (Holder) view.getTag();
}
holder.phone.setText(getItem(position).phone_number);
holder.name.setText(getItem(position).name);
holder.name.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
choosen.add(getItem(position));
}else {
int i=0;
for (Contact contact:choosen){
if(contact.phone_number.equalsIgnoreCase(getItem(position).phone_number)){
choosen.remove(i);
notifyDataSetChanged();
}
i++;
}
}
}
});
Log.wtf("generating rows"," yes");
return view;
}
private class Holder{
public CheckBox name;
public TextView phone;
}
public ArrayList<Contact> getChoosenContacts(){
return choosen;
}
}
intant_message.xml:
<?xml version="1.0" encoding="utf-8"?>
<EditText
android:id="#+id/instant_message"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_weight="5"
android:gravity="top"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/btn_send_to_limited"
android:text="send to limited"
android:layout_width="95dp"
android:textSize="10sp"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
/>
<Button
android:id="#+id/btn_sent_to_all"
android:layout_width="95dp"
android:layout_height="wrap_content"
android:text="send to all"
android:textSize="10sp"
android:layout_below="#+id/btn_send_to_limited"
android:layout_marginTop="5dp"
/>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools">
<ListView
android:id="#+id/list_checkable"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:listitem="#layout/list_chackable_item">
</ListView>
</LinearLayout>
list_chacakble_item:
<?xml version="1.0" encoding="utf-8"?>
<CheckBox
android:id="#+id/checkbox_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Abdallah"
android:textStyle="bold"/>
<TextView
android:id="#+id/text_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="7656156165156651"
android:layout_marginLeft="30dp"/>
The dialog box is trigered from an adapter of a listview and that's the adapter's code:
holder.replay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
InstantTextBoxDialog exampleDialog=new InstantTextBoxDialog();
exampleDialog.show(((Activity) activity).getFragmentManager(),"sadsdadsaadassd");
}
});
But till now nothing shows except the buttons and no listview

Related

How to add items to recyclerview programmatically? [duplicate]

I have a button(save contact) to save contacts ,the button when pressed get name and email from edit text and should dynamically add 1 list item in recycle view
The save button is in fragment
This is the name which i am extracting
company_name=(EditText)view.findViewById(R.id.edittext_companyname_createMeeting);
When i click on lead it should add in the existing recycleview
leads.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
newValueAdapter.newAddeddata(company_name.getText().toString());*/
}
});
The recycle view already have a arraylist,how do i add new value to the arraylist and again call oncreate
I tried to extract company name and send it to the adapter of that recycler view but it dint work
Adapter of RecyclerView
public class NewleadsAdapter extends RecyclerView.Adapter<NewleadsAdapter.MyViewHolder> {
Context context;
LayoutInflater inflater;
int positionbundle;
ArrayList<NewleadsPOJO> datalist;
public NewleadsAdapter(Context context, ArrayList<NewleadsPOJO> datalist,int positionbundle){
this.context=context;
this.datalist=datalist;
this.positionbundle=positionbundle;
}
/* public NewleadsAdapter(){}*/
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=LayoutInflater.from(context).inflate(R.layout.custom_new_leads,parent,false);
MyViewHolder myViewHolder=new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.leads_company.setText(datalist.get(position).getLeads_company());
holder.leads_date.setText(datalist.get(position).getLeads_date());
holder.leads_time.setText(datalist.get(position).getLeads_time());
if (positionbundle == 1){
/* holder.icon1.setVisibility(View.GONE);*/
holder.icon1.setImageResource(R.drawable.taskcompletednewblue);
}else{}
Log.e("Create_meetingdate_ArrayList:", datalist.get(0).getLeads_company()); /* Arrays.deepToString(data.toArray())*/
System.out.println(datalist.get(0).getLeads_company());
}
#Override
public int getItemCount() {
return datalist.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView leads_company,leads_date,leads_time;
ImageView icon1;
public MyViewHolder(View itemView) {
super(itemView);
leads_company=(TextView)itemView.findViewById(R.id.leads_company);
leads_date=(TextView)itemView.findViewById(R.id.leads_date);
leads_time=(TextView)itemView.findViewById(R.id.leads_time);
icon1=(ImageView)itemView.findViewById(R.id.leads_info);
}
}
/*public void newAddeddata(String company_name){
NewleadsPOJO newValue=new NewleadsPOJO();
newValue.setLeads_company(company_name);
datalist.add(datalist.size(),newValue);
}*/
}
Createmeetingfrag.java
public class CreateMeetingFrag extends Fragment {
TextView leads,cold,warm,hot,closed;
EditText company_name,email,date,time;
public CreateMeetingFrag() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_create_meeting, container, false);
company_name=(EditText)view.findViewById(R.id.edittext_companyname_createMeeting);
leads=(TextView)view.findViewById(R.id.meeting_leads);
cold=(TextView)view.findViewById(R.id.meeting_cold);
warm=(TextView)view.findViewById(R.id.meeting_warm);
hot=(TextView)view.findViewById(R.id.meeting_hot);
closed=(TextView)view.findViewById(R.id.meeting_closed);
leads.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getSavedValues();
/* NewleadsAdapter newValueAdapter=new NewleadsAdapter();
newValueAdapter.newAddeddata(company_name.getText().toString());*/
NewleadsAdapter newValue=new NewleadsAdapter();
newValue.newAddeddata(company_name.getText().toString());
setDefaultValues();
leads.setBackgroundColor(getResources().getColor(R.color.blue));
Toast.makeText(getActivity(),"leads clicked and saved",Toast.LENGTH_SHORT).show();
leads.setTextColor(getResources().getColor(R.color.white));
}
});
cold.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setDefaultValues();
cold.setBackgroundColor(getResources().getColor(R.color.blue));
Toast.makeText(getActivity(),"leads clicked",Toast.LENGTH_SHORT).show();
cold.setTextColor(getResources().getColor(R.color.white));
}
});
warm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setDefaultValues();
warm.setBackgroundColor(getResources().getColor(R.color.blue));
Toast.makeText(getActivity(),"leads clicked",Toast.LENGTH_SHORT).show();
warm.setTextColor(getResources().getColor(R.color.white));
}
});
hot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setDefaultValues();
hot.setBackgroundColor(getResources().getColor(R.color.blue));
Toast.makeText(getActivity(),"leads clicked",Toast.LENGTH_SHORT).show();
hot.setTextColor(getResources().getColor(R.color.white));
}
});
closed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setDefaultValues();
closed.setBackgroundColor(getResources().getColor(R.color.blue));
Toast.makeText(getActivity(),"leads clicked",Toast.LENGTH_SHORT).show();
closed.setTextColor(getResources().getColor(R.color.white));
}
});
return view;
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void setDefaultValues(){
leads.setBackgroundColor(getResources().getColor(R.color.white));
cold.setBackgroundColor(getResources().getColor(R.color.white));
warm.setBackgroundColor(getResources().getColor(R.color.white));
hot.setBackgroundColor(getResources().getColor(R.color.white));
closed.setBackgroundColor(getResources().getColor(R.color.white));
closed.setTextColor(getResources().getColor(R.color.black_semi_transparent));
hot.setTextColor(getResources().getColor(R.color.black_semi_transparent));
warm.setTextColor(getResources().getColor(R.color.black_semi_transparent));
cold.setTextColor(getResources().getColor(R.color.black_semi_transparent));
leads.setTextColor(getResources().getColor(R.color.black_semi_transparent));
leads.setBackground(getResources().getDrawable(R.drawable.bordder_button));
closed.setBackground(getResources().getDrawable(R.drawable.bordder_button));
hot.setBackground(getResources().getDrawable(R.drawable.bordder_button));
warm.setBackground(getResources().getDrawable(R.drawable.bordder_button));
cold.setBackground(getResources().getDrawable(R.drawable.bordder_button));
}
}
Add this method to your adapter and call on button click.
public void newAddeddata(String company_name){
NewleadsPOJO newValue=new NewleadsPOJO();
newValue.setLeads_company(company_name);
datalist.add(newValue);
notifyDataSetChanged();
}
Add following method to NewLeadFrag
public NewleadsAdapter getAdapter(){
return adapter;
}
now in Createmeetingfrag
leads.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NewLeadFrag fragment = getFragmentManager().findFragmentByTag("NewLeadFrag_TAG"); //set tag of fragment when you add with fragment manager. and if you are using support library use getSupportFragmentManager()
if(fragment!= null){
fragment.getAdapter().newAddeddata(company_name.getText().toString());
}
}
});
You don't need to go through the entire life cycle of your Activity or Fragment just because you've made changes to the list. Instead try adding the item in the list you currently have associated with the Adapter. And then call adapter.notifyDataSetChange(). This should automatically add the new Item to the RecyclerView.
How to add items and delete items in recycler view using floating button in java(android).
Add this dependency.
implementation 'com.google.android.material:material:1.4.0-alpha02'
implementation 'com.google.code.gson:gson:2.8.6'
MainActivity.java
fab = (FloatingActionButton) view.findViewById(R.id.fab_id);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater li = LayoutInflater.from(getContext());
View v = li.inflate(R.layout.layout_dialog, null);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
alertDialog.setTitle("Add Data");
EditText title = v.findViewById(R.id.edittext_title);
EditText description = v.findViewById(R.id.editview_description);
alertDialog.setView(v);
alertDialog.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Gson gson = new Gson();
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("title", title.getText().toString());
jsonObject.put("description", description.getText().toString());
item item = gson.fromJson(String.valueOf(jsonObject), item.class);
items.add(item);
Adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
alertDialog.setNegativeButton("cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
dialog.cancel();
}
});
alertDialog.show();
}
});
layout_dialog.xml
<?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="300dp"
android:orientation="vertical"
android:padding="60dp">
<EditText
android:id="#+id/edittext_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/enter_title"
app:layout_constraintBottom_toTopOf="#+id/editview_description"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="MissingConstraints"
android:inputType="text"
android:autofillHints="" />
<EditText
android:id="#+id/editview_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:hint="#string/enter_description"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/edittext_title"
tools:ignore="MissingConstraints"
android:autofillHints=""
android:inputType="text" />
Adapter.java
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
List<item> mdata;
public Adapter(List<item> mdata) {
this.mdata = mdata;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_item, parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.tilte.setText(mdata.get(position).getTitle());
holder.Description.setText(mdata.get(position).getDescription());
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mdata.remove(position);
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return mdata.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
TextView tilte,Description;
ImageView imageView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tilte=itemView.findViewById(R.id.title);
Description=itemView.findViewById(R.id.description);
imageView = itemView.findViewById(R.id.remove_image);
}
}
}
layout_item.xml
<?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"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="55dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="12dp"
android:layout_height="12dp"
android:layout_marginStart="4dp"
android:layout_marginTop="4dp"
android:contentDescription="#string/mark"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/circle_img" />
<View
android:id="#+id/view"
android:layout_width="1dp"
android:layout_height="0dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:background="#800080"
app:layout_constraintBottom_toBottomOf="#+id/description"
app:layout_constraintEnd_toEndOf="#id/imageView"
app:layout_constraintStart_toStartOf="#id/imageView"
app:layout_constraintTop_toBottomOf="#id/imageView" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="60dp"
android:layout_marginTop="16dp"
android:textStyle="bold"
android:textSize="16sp"
android:inputType="text"
app:layout_constraintStart_toEndOf="#+id/imageView"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/description"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:lineSpacingExtra="1sp"
android:padding="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/imageView"
app:layout_constraintTop_toBottomOf="#+id/title" />
<ImageView
android:id="#+id/remove_image"
android:layout_width="20dp"
android:layout_height="24dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="24dp"
android:contentDescription="#string/remove_item"
app:layout_constraintEnd_toStartOf="#+id/title"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#android:drawable/ic_menu_close_clear_cancel" />
</androidx.constraintlayout.widget.ConstraintLayout>
item.java
public class item {
private String title;
private String description;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public item(String title, String description) {
this.title = title;
this.description = description;
}
}
layout
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvContactNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:nestedScrollingEnabled="false"
android:overScrollMode="never"
tools:itemCount="2"
tools:listitem="#layout/row_add_contact_number" />
java
private ArrayList<ContactNumberModel> arrayList;
private ContactNumberAdapter adapter;
onCreate
arrayList = new ArrayList<>();
arrayList.add(new ContactNumberModel());
adapter = new ContactNumberAdapter(context);
binding.rvContactNumber.setLayoutManager(new LinearLayoutManager(context));
binding.rvContactNumber.setHasFixedSize(true);
binding.rvContactNumber.setAdapter(adapter);
ContactNumberModel.java
public class ContactNumberModel {
private String contactNo;
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
}
ContactNumberAdapter.java
public class ContactNumberAdapter extends RecyclerView.Adapter<ContactNumberAdapter.ViewHolder> {
private Context context;
private ArrayList<ContactNumberModel> arrayList;
public ContactNumberAdapter(Context context) {
this.context = context;
this.arrayList = new ArrayList<>();
this.arrayList.add(new ContactNumberModel());
}
#NonNull
#Override
public ContactNumberAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
RowAddContactNumberBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.row_add_contact_number, parent, false);
return new ViewHolder(binding);
}
#Override
public void onBindViewHolder(#NonNull final ContactNumberAdapter.ViewHolder holder, int position) {
ContactNumberModel model = arrayList.get(position);
//holder.bind(model);
holder.binding.etContactNumber.setText("");
holder.binding.etContactNumber.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
arrayList.get(holder.getAdapterPosition()).setContactNo(editable.toString());
}
});
if (arrayList.size() - 1 == holder.getAdapterPosition()) {
holder.binding.tvAddMore.setVisibility(View.VISIBLE);
holder.binding.ivRemove.setVisibility(View.GONE);
} else {
holder.binding.tvAddMore.setVisibility(View.GONE);
holder.binding.ivRemove.setVisibility(View.VISIBLE);
}
holder.binding.ivRemove.setOnClickListener(null);
holder.binding.tvAddMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addNewRow();
}
});
}
public void addNewRow() {
this.arrayList.add(new ContactNumberModel());
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
RowAddContactNumberBinding binding;
public ViewHolder(RowAddContactNumberBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
public void bind(ContactNumberModel model) {
binding.setContact(model);
binding.executePendingBindings();
}
}
}
row_add_contact_number.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="contact"
type="com.appname.model.ContactNumberModel" />
</data>
<androidx.appcompat.widget.LinearLayoutCompat
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/_10sdp"
android:orientation="vertical">
<androidx.appcompat.widget.LinearLayoutCompat
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/_15sdp"
android:layout_marginRight="#dimen/_15sdp"
android:gravity="center"
android:orientation="horizontal">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:theme="#style/TextInputLayoutHint">
<androidx.appcompat.widget.AppCompatEditText
android:id="#+id/etContactNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="false"
android:focusableInTouchMode="true"
android:hint="Enter Contact Number"
android:inputType="number"
android:maxLines="1" />
</com.google.android.material.textfield.TextInputLayout>
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/tvAddMore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/_3sdp"
android:layout_marginLeft="#dimen/_3sdp"
android:fontFamily="#font/font_barlow"
android:gravity="center"
android:text="#string/add_more"
android:textColor="#color/colorOrange"
android:textSize="#dimen/_12ssp"
android:textStyle="bold" />
<androidx.appcompat.widget.AppCompatImageView
android:id="#+id/ivRemove"
android:layout_width="#dimen/_15sdp"
android:layout_height="#dimen/_15sdp"
android:layout_marginLeft="#dimen/_5sdp"
android:adjustViewBounds="true"
android:src="#drawable/ic_logo"
android:visibility="gone" />
</androidx.appcompat.widget.LinearLayoutCompat>
<View style="#style/Divider" />
</androidx.appcompat.widget.LinearLayoutCompat>
</layout>

Android recyclerView Adapter Popup menu not working

I'm trying to make a notes app and I already got the items (notes) to be listed in the recycler. There is an ImageButton on each of the items and I want a popUpMenu to appear once it is clicked.
It is possible to click the imageButton for individual items but I cant get the popUpMenu to appear for each individual item.
If there is a better or alternative way that would be great too.
Item XML (row_notes.xml):
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="2dp"
card_view:cardElevation="0dp"
android:clickable="true"
android:layout_margin="5dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_weight="1"
android:background="#drawable/note_shape"
android:padding="3dp">
<TextView
android:textColor="#color/primaryText"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Note"
android:id="#+id/rowNoteTitle"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:paddingLeft="10dp"
android:textSize="20dp"
android:layout_gravity="top|left|center_vertical"
android:layout_marginTop="2dp" />
<ImageButton
android:layout_width="20dp"
android:layout_height="match_parent"
android:id="#+id/rowNoteBtn"
android:layout_gravity="right|center_vertical"
android:background="#drawable/img_btn_shape"
android:src="#drawable/ic_dots_vertical_white_24dp" />
<TextView
android:textColor="#color/secondaryText"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Note amount"
android:id="#+id/rowNoteAmount"
android:layout_alignParentTop="true"
android:textSize="12dp"
android:layout_gravity="left|bottom"
android:layout_marginLeft="20dp"
android:layout_marginTop="7dp" />
</FrameLayout>
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="5dp"
android:id="#+id/progressBar"
android:max="100"
android:progressDrawable="#drawable/progress_color"
android:background="#ffffff" />
</LinearLayout>
Recycler Adapter (nRecyclerAdapter.java) POPUPMENU CODE IS HERE:
public class nRecyclerAdapter extends RecyclerView.Adapter<nViewHolder> {
private Context context;
private ArrayList<Note> notes;
public nRecyclerAdapter(Context context, ArrayList<Note> notes) {
this.context = context;
this.notes = notes;
}
#Override
public nViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_notes, parent, false);
nViewHolder holder = new nViewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(final nViewHolder holder, final int position) {
holder.noteTitle.setText(notes.get(position).getNoteTitle());
holder.noteAmount.setText(notes.get(position).getNoteAmount());
holder.optionBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(context, notes.get(position).getNoteTitle()+" click button works",Toast.LENGTH_SHORT).show();
PopupMenu popupMenu = new PopupMenu(context,holder.optionBtn);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
String option = menuItem.getTitle().toString();
Toast.makeText(context, notes.get(position).getNoteTitle(),Toast.LENGTH_SHORT).show();
if(option.matches("Edit")){
Toast.makeText(context, notes.get(position).getNoteTitle()+" Edit",Toast.LENGTH_SHORT).show();
}else if(option.matches("Delete")){
Toast.makeText(context, notes.get(position).getNoteTitle()+" Delete",Toast.LENGTH_SHORT).show();
}
return true;
}
});
popupMenu.show();
}
});
//listener
holder.setItemClickListener(new noteClickListener() {
#Override
public void onNoteItemClick(View v, int position) {
Toast.makeText(context, notes.get(position).getNoteTitle(),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return notes.size();
}
public void updateData(ArrayList<Note> mNotes){
notes.clear();
notes.addAll(mNotes);
notifyDataSetChanged();
}
public void addItem(String title, String amount){
notes.add(new Note(title,amount));
notifyDataSetChanged();
}
public void removeItem(int position){
notes.remove(position);
notifyDataSetChanged();
}
}
ViewHolder (nViewHolder.java):
public class nViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView noteTitle;
TextView noteAmount;
noteClickListener noteClickListener;
ImageButton optionBtn;
public nViewHolder(View itemView) {
super(itemView);
optionBtn = (ImageButton) itemView.findViewById(R.id.rowNoteBtn);
noteTitle = (TextView) itemView.findViewById(R.id.rowNoteTitle);
noteAmount = (TextView) itemView.findViewById(R.id.rowNoteAmount);
optionBtn.setOnClickListener(this);
itemView.setOnClickListener(this);
}
public void setItemClickListener(noteClickListener nc){
this.noteClickListener = nc;
}
#Override
public void onClick(View view) {
this.noteClickListener.onNoteItemClick(view,getLayoutPosition());
}
}
onClickListener Class (noteClickListener.java):
import android.view.View;
public interface noteClickListener {
void onNoteItemClick(View v, int position);
}
You need to create some /res/menu/popupmenu.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="Menu Item" />
</menu>
Then, below your line PopupMenu popupMenu = new PopupMenu(context,holder.optionBtn); you need to inflate the menu with popupMenu.inflate(R.menu.popupmenu);
You must replace only the
holder.optionBtn with view
PopupMenu popupMenu = new PopupMenu(context,view);
And your code is start working.

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
}

Check all checkboxes in custom list view

I currently have ListFragment with a ArrayAdapter class
The codes are below.
1)I want to implement a checkbox from listview main xml to check all the checkboxes that are present in custom list row xml which is inflated using Array adapter.
2)how to refresh view in this code by clearing all checkboxes when a button is clicked.
listview_main.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:orientation="vertical"
android:weightSum="10"
android:background="#fff2fff2" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="10"
android:choiceMode="multipleChoice" >
</ListView>
<TextView
android:id="#android:id/empty"
android:layout_width="wrap_content"
/>
<LinearLayout
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<Button
android:id="#+id/btnin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="In" />
<Button
android:id="#+id/btndelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/checkAll"
android:checked="false" />
</LinearLayout>
</RelativeLayout>
custom_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="wrap_content" >
<ImageView
android:id="#+id/icon"
android:layout_width="50dp"
android:layout_height="50dp" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/paackage"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent">
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
Adapter class
public class FileAdapter extends ArrayAdapter<String>{
private List<String> filelist = null;
private Context context;
CheckBox checkAll;
public FileAdapter(Context _context, int _resource,List<String> _filelist) {
super(_context,_resource,_filelist);
this.context = _context;
this.filelist = _filelist;
this.itemChecked = new boolean[_filelist.size()];
}
private class ViewHolder {
TextView Name;
TextView pName;
CheckBox ck1;
ImageView iconview;
}
#Override
public int getCount() {
return ((null != filelist) ? filelist.size() : 0);
}
#Override
public String getItem(int position) {
return ((null != filelist) ? filelist.get(position) : null);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
View view = convertView;
if (null == view) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.custom_row, null);
holder = new ViewHolder();
holder.Name = (TextView) view.findViewById(R.id.name);
holder.pName = (TextView) view
.findViewById(R.id.paackage);
holder.ck1 = (CheckBox) view.findViewById(R.id.checkBox1);
holder.iconview = (ImageView) view.findViewById(R.id.app_icon);
view.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.appName.setText();
holder.packageName.setText();
holder.iconview.setImageDrawable();
holder.ck1.setChecked(false);
if (itemChecked[position])
holder.ck1.setChecked(true);
else
holder.ck1.setChecked(false);
holder.ck1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (holder.ck1.isChecked()) {
itemChecked[position] = true;
} else {
itemChecked[position] = false;
}
}
});
return view;
}
}
ListFragment class
public class FragmentA extends ListFragment implements View.OnClickListener {
public ArrayList<String> filelist;
Button in, delete;
ListView lv;
CheckBox cb;
private FileAdapter listadaptor = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
filelist = new ArrayList<String>();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View inflatedView = inflater.inflate(R.layout.fragment_app_restore, container, false);
in = (Button) inflatedView.findViewById(R.id.btnin);
delete= (Button) inflatedView.findViewById(R.id.btndelete);
lv = (ListView) inflatedView.findViewById(android.R.id.list);
empty = inflatedView.findViewById(android.R.id.empty);
//calling asynctask to load files here
delete.setOnClickListener(this);
in.setOnClickListener(this);
return inflatedView;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
cb = (CheckBox) v.findViewById(R.id.checkBox1);//this is the checkbox in row only
cb.performClick();
if (cb.isChecked()) {
} else {
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btndelete:
break;
case R.id.btnin:
break;
}
}
private class LoadFiles extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
filelist = GetFiles(root_path);
if (filelist != null) {
listadaptor = new AppRestoreFileAdapter(getActivity(),
R.layout.custom_row, filelist);
} else {
// lv.setEmptyView(empty);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
lv.setAdapter(listadaptor);
progress.dismiss();
super.onPostExecute(result);
}
}
}

ListFragment with checkbox onListItemClick never gets called

I've read some SO questions like this and this but still couldn't figure out whats wrong with my code.
I have a ListFragment, and each row has a TextView and a CheckBox.
Clicking the CheckBox is working, but clicking on the TextView does nothing, and OnListItemClick doesn't get called. I've also tried to dynamically add an OnClickListener, which make it work, but it's not the correct way to do it, and it also lacks the GUI feedback of the click (item being "highlighted" for a sec).
This is my textview_with_checkbox.XML I'm using for each item:
<?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="wrap_content"
android:clickable="true"
android:focusable="true"
android:gravity="left"
android:descendantFocusability="blocksDescendants"
android:orientation="horizontal" >
<TextView
android:id="#+id/textview_event_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingLeft="3dp"
android:paddingTop="5dp"
android:focusable="true"
android:singleLine="false" />
<CheckBox
android:id="#+id/checkbox_for_event_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.05"
android:focusable="false"
android:clickable="false" />
</LinearLayout>
now the code:
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
displayEventsLogFiles();
}
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
String chosenItem = (String) getListAdapter().getItem(position);
mCallBack.onEventItemSelected(chosenItem);
}
static class myCustomAdapterViewHolder
{
public TextView eventName;
public CheckBox eventCheckBox;
}
private class myCustomAdapter extends ArrayAdapter<String>
{
private ArrayList<String> sortedList;
private Context m_oContext;
List<String> m_oValues = null;
public myCustomAdapter(Context cont, int viewResId, List<String> objects)
{
super(cont, viewResId, objects);
m_oContext = cont;
m_oValues = objects;
sortedList = new ArrayList<String>();
for (String str : objects)
sortedList.add(str);
java.util.Collections.sort(sortedList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View l_oRowView = convertView;
myCustomAdapterViewHolder l_oInitializedViewHolder = null;
final int l_nPosition = position;
// Use convertView if possible, otherwise inflate a view:
if (l_oRowView == null)
{
LayoutInflater inflater = (LayoutInflater) m_oContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
l_oRowView = inflater.inflate(R.layout.textview_with_checkbox, parent, false);
// PlaceHolder pattern:
final myCustomAdapterViewHolder l_oViewHolder = new myCustomAdapterViewHolder();
l_oViewHolder.eventName = (TextView) l_oRowView.findViewById(R.id.textview_event_name);
l_oViewHolder.eventCheckBox = (CheckBox) l_oRowView.findViewById(R.id.checkbox_for_event_name);
l_oViewHolder.eventCheckBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox)v;
//cb.setChecked(!cb.isChecked());
String l_sFilename = l_oViewHolder.eventName.getText().toString();
if (cb.isChecked())
{
if (!m_lstSelectedFilenames.contains(l_sFilename))
m_lstSelectedFilenames.add(l_sFilename);
}
else
{
if (m_lstSelectedFilenames.contains(l_sFilename))
m_lstSelectedFilenames.remove(l_sFilename);
}
}
});
l_oViewHolder.eventCheckBox.setFocusable(false);
//l_oViewHolder.eventCheckBox.setClickable(false);
// "Add" the viewHolder as a tag:
l_oRowView.setTag(l_oViewHolder);
l_oInitializedViewHolder = l_oViewHolder;
}
else
l_oInitializedViewHolder = (myCustomAdapterViewHolder) l_oRowView.getTag();
// By now, the rowView is initialized, just get the viewHolder and then get the views from it, to update:
//myCustomAdapterViewHolder l_oViewHolder = (myCustomAdapterViewHolder) l_oRowView.getTag();
/*l_oInitializedViewHolder.eventName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallBack.onEventItemSelected((String)getListAdapter().getItem(l_nPosition));
}
});*/
l_oInitializedViewHolder.eventName.setText(m_oValues.get(position));
return l_oRowView;
//return super.getView();
}
public myCustomAdapter(Context cont, int viewResId, String[] strings)
{
this(cont, viewResId, Arrays.asList(strings));
}
#Override
public String getItem(int position)
{
return sortedList.get(position);
}
#Override
public int getPosition(String item)
{
return sortedList.indexOf(item);
}
}
What am I doing wrong here?
All I want is to be able to select "files" for deletion, using the CheckBoxes
Try only using only onclick for textview and checkbox, not onListItemClick -which you can remove- as well, so you should change some properties for the linear layout as well.
<?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="wrap_content"
android:clickable="false"
android:focusable="false"
android:gravity="left"
android:orientation="horizontal" >
<TextView
android:id="#+id/textview_event_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingLeft="3dp"
android:paddingTop="5dp"
android:focusable="true"
android:singleLine="false" />
<CheckBox
android:id="#+id/checkbox_for_event_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.05"
android:focusable="false"
android:clickable="false" />
</LinearLayout>
Implement in the adapter
// PlaceHolder pattern:
final myCustomAdapterViewHolder l_oViewHolder = new myCustomAdapterViewHolder();
l_oViewHolder.eventName = (TextView) l_oRowView.findViewById(R.id.textview_event_name);
l_oViewHolder.eventCheckBox = (CheckBox) l_oRowView.findViewById(R.id.checkbox_for_event_name);
l_oViewHolder.eventName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// your code for textview click
}
}
l_oViewHolder.eventCheckBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox)v;
//cb.setChecked(!cb.isChecked());
String l_sFilename = l_oViewHolder.eventName.getText().toString();
if (cb.isChecked())
{
if (!m_lstSelectedFilenames.contains(l_sFilename))
m_lstSelectedFilenames.add(l_sFilename);
}
else
{
if (m_lstSelectedFilenames.contains(l_sFilename))
m_lstSelectedFilenames.remove(l_sFilename);
}
}
});
l_oViewHolder.eventCheckBox.setFocusable(false);
add following attribute:
android:focusable="false"
android:clickable="false"
for example in my xml file:
<CheckBox xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeightSmall"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="center_vertical"
android:button="?android:attr/listChoiceIndicatorSingle"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:buttonTint="#color/gray"
android:focusable="false"
android:clickable="false"
/>
and in my code:
public class MyTestFragment extends ListFragment {
.....
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
}
}

Categories

Resources