How to Add and Remove Recycler listview items inside element - android

This is my Adapter class
public class NewFeePlanAdapter extends RecyclerView.Adapter<NewFeePlanAdapter.MyViewHolder> {
Context context;
ArrayList<FeeTypeModel> feeTypeModelArrayList;
public NewFeePlanAdapter(Context context, ArrayList<FeeTypeModel> feeTypeModelArrayList){
this.context = context;
this.feeTypeModelArrayList = feeTypeModelArrayList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.new_fee_list_row, parent,false);
MyViewHolder myViewHolder = new MyViewHolder(itemView,new MyCustomEditTextListener());
return myViewHolder;
}
FeeTypeModel feeTypeModel;
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
feeTypeModel = feeTypeModelArrayList.get(position);
holder.fee_type_name_tv.setText(feeTypeModel.getFeeType().toString());
if (feeTypeModel.getLinearLayout()!=null) {
holder.new_plan_main_ll.addView(feeTypeModel.getLinearLayout());
}
holder.myCustomEditTextListener.updatePosition(position);
holder.fee_amount_et.setText( feeTypeModelArrayList.get(position).getAmount());
holder.fee_type_cb.setOnCheckedChangeListener(null);
holder.fee_type_cb.setChecked(feeTypeModel.isSelectPlan());
holder.fee_type_cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
feeTypeModelArrayList.get(position).setSelectPlan(isChecked);
}
});
holder.add_installments_iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.fee_amount_et.getText().length() == 0){
Toast.makeText(context,"Please Enter Amount",Toast.LENGTH_LONG).show();
}else {
showDialogForNumberOfInstallments(v,position,Long.parseLong(holder.fee_amount_et.getText().toString()));
}
}
});
}
#Override
public int getItemCount() {
return feeTypeModelArrayList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView fee_type_name_tv;
EditText fee_amount_et;
ImageView add_installments_iv;
CheckBox fee_type_cb;
public MyCustomEditTextListener myCustomEditTextListener;
LinearLayout new_plan_main_ll;
public MyViewHolder(View view, MyCustomEditTextListener myCustomEditTextListener) {
super(view);
new_plan_main_ll = (LinearLayout)view.findViewById(R.id.new_plan_main_ll);
fee_type_cb = (CheckBox) view.findViewById(R.id.fee_type_cb);
fee_type_name_tv = (TextView) view.findViewById(R.id.fee_type_name_tv);
fee_amount_et = (EditText) view.findViewById(R.id.fee_amount_et);
add_installments_iv = (ImageView)view.findViewById(R.id.add_installments_iv);
this.myCustomEditTextListener = myCustomEditTextListener;
this.fee_amount_et.addTextChangedListener(myCustomEditTextListener);
}
}
private class MyCustomEditTextListener implements TextWatcher {
private int position;
public void updatePosition(int position) {
this.position = position;
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
// no op
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
feeTypeModelArrayList.get(position).setAmount( charSequence.toString());
}
#Override
public void afterTextChanged(Editable editable) {
// no op
}
}
AutoCompleteTextView new_fee_plan_name_act;
EditText numberOfInstallments_et;
int selectedPosition;
private void showDialogForNumberOfInstallments(View v,int position, final long amount){
selectedPosition = position;
// Create custom dialog object
final Dialog dialog = new Dialog(context);
// Include dialog.xml file
dialog.setContentView(R.layout.new_plan_name_dialog);
dialog.setTitle("Installments");
new_fee_plan_name_act = (AutoCompleteTextView) dialog.findViewById(R.id.new_fee_plan_name_act);
new_fee_plan_name_act.setVisibility(View.GONE);
numberOfInstallments_et = (EditText)dialog.findViewById(R.id.numberOfInstallments_et);
numberOfInstallments_et.setVisibility(View.VISIBLE);
new_fee_plan_name_act.setHint("Enter Number Of Installments");
dialog.setCancelable(false);
dialog.show();
Button feePlan_cancel_bt = (Button) dialog.findViewById(R.id.feePlan_cancel_bt);
// if decline button is clicked, close the custom dialog
feePlan_cancel_bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Close dialog
dialog.dismiss();
}
});
Button FeePlan_create_bt = (Button) dialog.findViewById(R.id.FeePlan_create_bt);
FeePlan_create_bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (numberOfInstallments_et.getText().toString().length()==0){
Toast.makeText(context,"Please Enter New number 0f Installments",Toast.LENGTH_LONG).show();
}else {
FeeTypeModel feeTypeModel11 = feeTypeModelArrayList.get(selectedPosition);
if (feeTypeModel11.getLinearLayout()!=null) {
feeTypeModel11.getLinearLayout().removeView(v);
}
LinearLayout layout = new LinearLayout(context);
layout.setLayoutParams(new LinearLayout.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));
layout.setOrientation(LinearLayout.VERTICAL);
// Toast.makeText(context,"Entered Installments "+numberOfInstallments_et.getText().toString(),Toast.LENGTH_LONG).show();
int WrapWidth = LinearLayout.LayoutParams.WRAP_CONTENT;
int WrapHeight = LinearLayout.LayoutParams.WRAP_CONTENT;
int length = Integer.parseInt(numberOfInstallments_et.getText().toString());
long instAmount = amount/length;
for (int i=0;i<length;i++){
TextView t = new TextView(context);
t.setText("Installment"+i+" "+instAmount);
layout.addView(t,WrapWidth,WrapHeight);
}
feeTypeModel11.setLinearLayout(layout);
dialog.dismiss();
notifyDataSetChanged();
}
}
});
}
}
this is my new_fee_list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:elevation="6dp"
android:layout_marginTop="#dimen/activity_horizontal_margin"
android:layout_marginRight="#dimen/activity_horizontal_margin"
android:layout_marginBottom="#dimen/activity_horizontal_margin"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/new_plan_main_ll"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="wrap_content">
<CheckBox
android:id="#+id/fee_type_cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/fee_type_name_tv"
android:text="fsdfdsf"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_marginTop="#dimen/activity_horizontal_margin"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_toLeftOf="#+id/add_installments_iv"
android:layout_height="wrap_content">
<EditText
android:id="#+id/fee_amount_et"
android:layout_width="130dp"
android:layout_height="wrap_content"
android:imeActionId="#+id/login"
android:imeActionLabel="#string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:maxLines="1"
android:hint="Enter Amount"
android:inputType="number"
android:singleLine="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</android.support.design.widget.TextInputLayout>
<ImageView
android:id="#+id/add_installments_iv"
android:layout_width="wrap_content"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="#dimen/activity_horizontal_margin"
android:src="#android:drawable/ic_input_add"
android:layout_height="wrap_content" />
</RelativeLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
//This is my main Activity class
public class NewFeePlanActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_fee_plan);
RecyclerView fee_plans_rv = (RecyclerView)findViewById(R.id.fee_plans_rv);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
fee_plans_rv.setLayoutManager(mLayoutManager);
NewFeePlanAdapter newFeePlanAdapter = new NewFeePlanAdapter(NewFeePlanActivity.this, feeTypeModelArrayList);
fee_plans_rv.setAdapter(newFeePlanAdapter);
}}
I am using above code,but my problem is adding specific position on list
** As showed above image how i need to dynamically add and remove the views each item positionin recycler view,can any one guide me with code,
your response will be appreciated..... **

Related

Listview custom adapter cant select an item

I tried all the solution that i found here in the stackoverflow but it seems like none of them work.
Here is my main activity:
public class MerchantLocatorActivity extends AppCompatActivity implements OnMapReadyCallback {
public void init(){
merchantLocatorResponseObject = new MerchantLocatorResponse();
merchantLocatorResponseObject.setTitle("Spherical");
merchantLocatorResponseObject.setAddress("8007 Pioneer St, Kapitolyo, Mandaluyong, 1550 Metro Manila");
merchantLocatorResponseObject.setLatitude( 14.573249);
merchantLocatorResponseObject.setLongitude(121.057022);
merchantLocatorObjectArray.add(merchantLocatorResponseObject);
merchantLocatorResponseObject = new MerchantLocatorResponse();
merchantLocatorResponseObject.setTitle("Globe");
merchantLocatorResponseObject.setAddress("SCT, 584 Shaw Blvd, Mandaluyong, 1552 Metro Manila");
merchantLocatorResponseObject.setLatitude(14.585095);
merchantLocatorResponseObject.setLongitude(121.048893);
merchantLocatorObjectArray.add(merchantLocatorResponseObject);
merchantLocatorResponseObject = new MerchantLocatorResponse();
merchantLocatorResponseObject.setTitle("Sparndium");
merchantLocatorResponseObject.setAddress("Xavier, San Juan, 1502 Metro Manila");
merchantLocatorResponseObject.setLatitude(14.601918);
merchantLocatorResponseObject.setLongitude(121.042169);
merchantLocatorObjectArray.add(merchantLocatorResponseObject);
addMarker();
}
#OnClick(R.id.fab)
public void showAccToDialog() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
View alertView = LayoutInflater.from(this).inflate(R.layout.dialog_biller, null);
alertDialogBuilder.setView(alertView);
final AlertDialog dialog = alertDialogBuilder.create();
dialog.show();
final ListView listViewBillers = (ListView) dialog.findViewById(R.id.biller_institutions_listview);
if (listViewBillers != null) {
MerchantLocatorAdapter adapter = new MerchantLocatorAdapter(
this, R.layout.merchant_locator_adapter, merchantLocatorObjectArray);
listViewBillers.setAdapter(adapter);
listViewBillers.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
geoLocate(merchantLocatorObjectArray,position);
DebugUtils.log("TESTTESTACTIVITYZXC");
DebugUtils.showToast(MerchantLocatorActivity.this,"HAHAHAH");
dialog.dismiss();
}
});
final EditText mSearchedittext = (EditText) dialog.findViewById(R.id.search_edittext);
mSearchedittext.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) {
final ArrayList<MerchantLocatorResponse> searchResultObject = new ArrayList<>();
searchResultObject.clear();
for (int hay = 0; hay <= merchantLocatorObjectArray.size() - 1; hay++) {
if ( merchantLocatorObjectArray.get(hay).getTitle().toLowerCase().contains(charSequence)) {
searchResultObject.add( merchantLocatorObjectArray.get(hay));
}
}
MerchantLocatorAdapter adapter = new MerchantLocatorAdapter(
MerchantLocatorActivity.this, R.layout.merchant_locator_adapter, searchResultObject);
listViewBillers.setAdapter(adapter);
listViewBillers.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
geoLocate(searchResultObject,position);
dialog.dismiss();
}
});
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
}
}
i remove some part of the code because i think it's un necessary to include but let me know if there's some part that i need some clarification.
currently in my main activity, i'm calling a dialog that contains a listview and in my listview i have items.
My problem is i can't select any of my items even thought i have my setOnitemclick listener.
here is my adapter:
public class MerchantLocatorAdapter extends BaseAdapter {
private int resourceLayout;
private Context mContext;
ArrayList<MerchantLocatorResponse> merchantLocatorarray = new ArrayList<>();
public MerchantLocatorAdapter(Context context, int resource, ArrayList<MerchantLocatorResponse> merchantLocatorResponsesobjectArray) {
this.resourceLayout = resource;
this.mContext = context;
this.merchantLocatorarray = merchantLocatorResponsesobjectArray;
}
#Override
public int getCount() {
return merchantLocatorarray.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(resourceLayout, parent, false);
}
TextView tt1 = (TextView) convertView.findViewById(R.id.field_name_textview);
TextView tt2 = (TextView) convertView.findViewById(R.id.field_value_textview);
ImageButton direction = (ImageButton) convertView.findViewById(R.id.direction);
tt1.setText(merchantLocatorarray.get(position).getTitle());
tt2.setText(merchantLocatorarray.get(position).getAddress());
return convertView;
}
}
here is my layout for my adapter:
<LinearLayout 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">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_margin="8dp"
android:elevation="3dp">
<LinearLayout
android:id="#+id/card_overflow"
android:focusable="true"
android:clickable="true"
android:background="#fff"
android:paddingLeft="16dp"
android:paddingRight="0dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1">
<TextView
android:id="#+id/field_name_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_toLeftOf="#+id/branch_btns"
android:layout_alignParentLeft="true"
android:textSize="17sp"
android:textStyle="bold"
android:textColor="#color/edittext_text"
android:text="test"/>
<LinearLayout
android:id="#+id/branch_btns"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:orientation="horizontal"
>
<ImageButton
android:id="#+id/direction"
android:layout_width="50sp"
android:layout_height="wrap_content"
android:src="#drawable/ic_direction"
android:scaleType="fitCenter"
android:background="#color/translucent_clear_bg"
/>
<ImageButton
android:id="#+id/btn_branch_phone"
android:layout_width="50sp"
android:layout_height="wrap_content"
android:src="#drawable/ic_call_phone"
android:scaleType="fitCenter"
android:background="#color/translucent_clear_bg"
/>
</LinearLayout>
</RelativeLayout>
<View
android:id="#+id/seperator"
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginBottom="5dp"
android:background="#android:color/darker_gray"
android:visibility="gone"
android:layout_marginTop="2dp"/>
<TextView
android:id="#+id/field_value_textview"
android:textSize="14sp"
android:textColor="#color/edittext_tint"
android:layout_marginTop="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="test"/>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
i tried every solution that i found here in stackoverflow, and yet i can't still click my item. so please don't mark this as a duplicate.
if there's any part of the code that need clarification, please leave a comment and i'll answer as soon as possible. thanks.
Try to use Observable in you custom adapter:
// Define
private final PublishSubject<MerchantLocatorResponse> onItemClick = PublishSubject.create();
// Create the observable method
public Observable<ConversationMessage> getObservable(){
return onItemClick;
}
// Set the onClickListener into getView()
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemClick.onNext(merchantLocatorarray.get(position));
}
});
Then, in your main activity listen to it and handle the click:
#OnClick(R.id.fab)
public void showAccToDialog() {
// bla bla bla
listViewBillers.setAdapter(adapter);
listViewBillers.getObservable().subscribe(geoLocate);
// bla bla bla
}
Consumer<MerchantLocatorResponse> geoLocate = new Consumer<MerchantLocatorResponse>() {
#Override
public void accept(MerchantLocatorResponse mlr) {
// Code after click event
}
};
Add those library in your gradle:
implementation "io.reactivex.rxjava2:rxjava:2.1.5"
implementation "io.reactivex.rxjava2:rxandroid:2.0.1"
Add convertView.setOnclickListener() in your code. Try below code in your adapter
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(resourceLayout, parent, false);
}
TextView tt1 = (TextView) convertView.findViewById(R.id.field_name_textview);
TextView tt2 = (TextView) convertView.findViewById(R.id.field_value_textview);
ImageButton direction = (ImageButton) convertView.findViewById(R.id.direction);
tt1.setText(merchantLocatorarray.get(position).getTitle());
tt2.setText(merchantLocatorarray.get(position).getAddress());
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});
return convertView;
} }

Call contacts from a list in Android Studio

I have an Android application where I used Linear Layout that shows a list of contacts. Now what I want is that when selecting the contacts, call the indicated number.
For now, all it do is show the contacts, but when I click on call, it does not take any action. I do not know how to make to mark
I tried with setOnClickListener().But Unsuccessful
My code:
public class ContactsAdapter extends RecyclerView.Adapter<ContactsAdapter.ContactViewHolder>{
Dialog myDialog;
private List<ContactModel> contactModelList;
private Context mContext;
public ContactsAdapter(List<ContactModel> contactModelList, Context mContext){
this.contactModelList = contactModelList;
this.mContext = mContext;
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.single_contact_view, null);
ContactViewHolder contactViewHolder = new ContactViewHolder(view);
return contactViewHolder;
}
#Override
public void onBindViewHolder(ContactViewHolder holder, int position) {
final ContactModel contactModel = contactModelList.get(position);
holder.tvContactName.setText(contactModel.getContactName());
holder.tvPhoneNumber.setText(contactModel.getContactNumber());
holder.contactsRowLV.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View view) {
Toast.makeText(mContext,""+ contactModel.getContactNumber(),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return contactModelList.size();
}
public static class ContactViewHolder extends RecyclerView.ViewHolder{
ImageView ivContactImage;
TextView tvContactName;
TextView tvPhoneNumber;
LinearLayout contactsRowLV;
public ContactViewHolder(View itemView) {
super(itemView);
ivContactImage = (ImageView) itemView.findViewById(R.id.ivContactImage);
tvContactName = (TextView) itemView.findViewById(R.id.tvContactName);
tvPhoneNumber = (TextView) itemView.findViewById(R.id.tvPhoneNumber);
contactsRowLV = itemView.findViewById(R.id.contactsRowLV);
}
}
}
Here I show my XML of how I have. Help me please
<LinearLayout
android:id="#+id/contactsRowLV"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/ivContactImage"
android:layout_width="55dp"
android:layout_height="55dp"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_gravity="center"
android:src="#drawable/ic_person"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center_vertical">
<TextView
android:id="#+id/tvContactName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:textSize="30dp"
android:textStyle="bold"
android:textColor="#android:color/primary_text_light"
android:text="Name"/>
<TextView
android:id="#+id/tvPhoneNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:textSize="25dp"
android:textColor="#android:color/primary_text_light"
android:text="Phone"/>
</LinearLayout>
</LinearLayout>
You just need to add following code in setOnClickListener(). This code is used to call particular number.
#Override
public void onBindViewHolder(ContactViewHolder holder, int position) {
final ContactModel contactModel = contactModelList.get(position);
holder.tvContactName.setText(contactModel.getContactName());
holder.tvPhoneNumber.setText(contactModel.getContactNumber());
holder.contactsRowLV.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View view) {
Toast.makeText(mContext,""+ contactModel.getContactNumber(),Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" +contactModel.getContactNumber()));
mContext.startActivity(intent);
}
});
}

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>

How to box each word after user presses space/comma in android studio?

I'm currently trying to make an android application and I've run into a problem. How would you allow for user to type a word and once they press space/comma, it boxes the word, preferably with an exit option.
https://i.stack.imgur.com/BwpZ9.png
https://i.stack.imgur.com/zqOLo.png
Anything along the lines of these pictures would be perfect.
What you are wanting is called chips in Android, it's one of the native designs you can read about it's specification here.
Here are a few example to get you started, last time I checked there was no proper documentation or support for this feature so I ended up using one the libraries that has built it, you can do something yourself by implementing a custom view as explained here
Here is how I would implement it. This is a working example. When the user hits space it adds and item. When you click an item it will remove it.
Here is a gif of it in action.
https://giphy.com/gifs/l4EpayEaAuGV58tgY
add to gradle:
compile 'com.android.support:design:26.0.0-alpha1'
compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
compile 'com.xiaofeng.android:flowlayoutmanager:1.2.3.2'
classes
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler);
recyclerView.setLayoutManager(new FlowLayoutManager());
recyclerView.setAdapter(new CustomRecyclerAdapter());
}
}
public class CustomRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int HOLDER_ERROR = 0;
private static final int HOLDER_BOX = 1;
private static final int HOLDER_EDIT = 2;
private List<Object> objectList = new ArrayList<>();
public CustomRecyclerAdapter() {
objectList.add(0);
}
public void addItem(String item) {
objectList.add(getItemCount() - 1, item);
notifyItemInserted(getItemCount() - 1);
}
public void removeItem(int position) {
objectList.remove(position);
notifyItemRemoved(position);
}
#Override
public int getItemCount() {
return objectList.size();
}
#Override
public int getItemViewType(int position) {
if (objectList.get(position) instanceof String) {
return HOLDER_BOX;
} else if (objectList.get(position) instanceof Integer) {
return HOLDER_EDIT;
} else {
return HOLDER_ERROR;
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case HOLDER_ERROR:
return null;
case HOLDER_BOX:
return new ViewHolderBox(LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_box, parent, false));
case HOLDER_EDIT:
return new ViewHolderEdit(LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_edit_text, parent, false));
default:
return null;
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof ViewHolderBox) {
ViewHolderBox mHolder = (ViewHolderBox) holder;
mHolder.bindItems();
} else if (holder instanceof ViewHolderEdit) {
ViewHolderEdit mHolder = (ViewHolderEdit) holder;
mHolder.bindItems();
}
holder.itemView.setTag(this);
}
private class ViewHolderEdit extends RecyclerView.ViewHolder implements TextWatcher {
private EditText edit;
private ViewHolderEdit(View itemView) {
super(itemView);
edit = itemView.findViewById(R.id.edit);
InputMethodManager imm = (InputMethodManager) itemView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInputFromInputMethod(edit.getWindowToken(), 0);
}
private void bindItems() {
edit.addTextChangedListener(this);
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String editString = edit.getText().toString();
Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(editString);
if (matcher.find()) {
if (!editString.trim().equalsIgnoreCase("")) {
addItem(editString.trim());
edit.setText("");
edit.requestFocus();
}
}
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
}
}
private class ViewHolderBox extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView text;
private ViewHolderBox(View itemView) {
super(itemView);
text = itemView.findViewById(R.id.text);
text.setOnClickListener(this);
}
private void bindItems() {
String item = (String) objectList.get(getAdapterPosition());
text.setText(item);
}
#Override
public void onClick(View view) {
removeItem(getAdapterPosition());
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="resume.eugene.com.testing.MainActivity" />
recycler_box.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center">
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="34dp"
android:layout_marginBottom="2dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="2dp"
android:background="#90CAF9"
android:clickable="true"
android:gravity="center"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:text="Testing" />
</LinearLayout>
recycler_edit_text.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:id="#+id/edit"
android:layout_width="wrap_content"
android:layout_height="34dp"
android:layout_marginBottom="2dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginTop="2dp"
android:background="#android:color/transparent"
android:gravity="center_vertical"
android:hint="Add Item"
android:minWidth="50dp"
android:textSize="15sp" />
</LinearLayout>

AnimateLayoutChanges doesn't work with RecyclerView

I have a screen with a Recyclerview and others Elements inside of LinearLayout. The problem is when I remove a item of the RecyclerView, animateLayoutChanges doesn't work in this case. Does anayone know why this happen??
XML
<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="match_parent"
tools:context="com.example.alvaro.resizetest.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<LinearLayout
android:id="#+id/test1"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorAccent"
android:gravity="center_vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LinearLayout"
android:textColor="#FFFFFF"
android:textSize="22sp"/>
</LinearLayout>
<LinearLayout
android:id="#+id/test2"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorPrimaryDark"
android:gravity="center_vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LinearLayout"
android:textColor="#FFFFFF"
android:textSize="22sp"/>
</LinearLayout>
<LinearLayout
android:id="#+id/test3"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorAccent"
android:gravity="center_vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LinearLayout"
android:textColor="#FFFFFF"
android:textSize="22sp"/>
</LinearLayout>
<LinearLayout
android:id="#+id/test4"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorPrimaryDark"
android:gravity="center_vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LinearLayout"
android:textColor="#FFFFFF"
android:textSize="22sp"/>
</LinearLayout>
</LinearLayout>
JAVA
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
Adapter adapter = new Adapter();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
recyclerView.setNestedScrollingEnabled(true);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
view.setVisibility(View.GONE);
}
};
findViewById(R.id.test1).setOnClickListener(listener);
findViewById(R.id.test2).setOnClickListener(listener);
findViewById(R.id.test3).setOnClickListener(listener);
findViewById(R.id.test4).setOnClickListener(listener);
}
class Adapter extends RecyclerView.Adapter<Adapter.Holder>{
int size = 3;
public Adapter() {
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = getLayoutInflater().inflate(R.layout.item, parent, false);
return new Holder(view);
}
#Override
public void onBindViewHolder(Holder holder, int position) {
}
#Override
public int getItemCount() {
return size;
}
class Holder extends RecyclerView.ViewHolder {
public Holder(final View itemView) {
super(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
size --;
notifyItemRemoved(getAdapterPosition());
}
});
}
}
}
After a while I got a solution. I made a function to animate the recyclerView height.
JAVA
public class MainActivity extends AppCompatActivity {
private final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
Adapter adapter = new Adapter(recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this) {
#Override
public boolean canScrollVertically() {
return false;
}
};
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
recyclerView.setNestedScrollingEnabled(true);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
view.setVisibility(View.GONE);
}
};
findViewById(R.id.test1).setOnClickListener(listener);
findViewById(R.id.test2).setOnClickListener(listener);
findViewById(R.id.test3).setOnClickListener(listener);
findViewById(R.id.test4).setOnClickListener(listener);
}
public void animateHeight(final View v, final int height) {
final int initialHeight = v.getMeasuredHeight();
int duration = 500;
Interpolator interpolator = new AccelerateInterpolator(2);
// I have to set the same height before the animation because there is a glitch
// in the beginning of the animation
v.getLayoutParams().height = initialHeight;
v.requestLayout();
Animation a = new Animation() {
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
Log.d(TAG, "InterpolatedTime: " + interpolatedTime);
Log.d(TAG, "Collapsing height: " + (initialHeight - (int) (height * interpolatedTime)));
v.getLayoutParams().height = initialHeight - (int) (height * interpolatedTime);
v.requestLayout();
}
#Override
public boolean willChangeBounds() {
return true;
}
};
a.setDuration(duration);
a.setInterpolator(interpolator);
v.startAnimation(a);
}
class Adapter extends RecyclerView.Adapter<Adapter.Holder> {
RecyclerView mRecyclerView;
int size = 3;
public Adapter(RecyclerView recyclerView) {
mRecyclerView = recyclerView;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = getLayoutInflater().inflate(R.layout.item, parent, false);
return new Holder(view);
}
#Override
public void onBindViewHolder(Holder holder, int position) {
}
#Override
public int getItemCount() {
return size;
}
class Holder extends RecyclerView.ViewHolder {
public Holder(final View itemView) {
super(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
size--;
notifyItemRemoved(getAdapterPosition());
animateHeight((View) itemView.getParent(), itemView.getMeasuredHeight());
}
});
}
}
}
}
What worked for me was simply adding the following code to onCreate:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
((ViewGroup) findViewById(R.id.llRoot)).getLayoutTransition()
.enableTransitionType(LayoutTransition.CHANGING);
}
where llRoot is your LinearLayout containing RecyclerView.
You do need to keep android:animateLayoutChanges="true" on your LinearLayout, otherwise it crashes.
I believe if you want to support this below JellyBean, you would need your custom solution.
Explanation on the solution is here: https://proandroiddev.com/the-little-secret-of-android-animatelayoutchanges-e4caab2fddec

Categories

Resources