Android Master-Detail Application - android

I am trying to achieve the following -
"A master-detail two pane flow and the datasource in JSON will be fetched via volley".
My struggle is that I do not know how to transfer data when clickEvent() occured on Master Panel.
I have followed a few tutorials such as
http://mobileappdocs.com/android.html
http://www.techotopia.com/index.php/An_Android_Master/Detail_Flow_Tutorial
I still didn't get that part.
Is it because I am using the default master-detail layout from Android Studio in which only the right(detail) panel is Fragment and the left is not.
Should both the panels need to be Fragments?
My Codes and Progress : I have already done the layouts and I am struggling with the behind Java codes.
guest_list.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"
android:baselineAligned="false"
android:divider="?android:attr/dividerHorizontal"
android:orientation="horizontal"
android:showDividers="none"
tools:context="awesome.pyie.com.finalapp.GuestListActivity">
<!--
This layout is a two-pane layout for the Guests
master/detail flow.
-->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#color/AppDarkGrey">
<SearchView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:id="#+id/searchView"
android:background="#color/AppLightGrey"
android:iconifiedByDefault="false"
android:queryHint="Search">
</SearchView>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/guest_list"
android:name="awesome.pyie.com.finalapp.GuestListFragment"
android:layout_width="308dp"
android:layout_height="match_parent"
app:layoutManager="LinearLayoutManager"
tools:context="awesome.pyie.com.finalapp.GuestListActivity"
tools:listitem="#layout/guest_list_content" />
</LinearLayout>
<FrameLayout
android:background="#color/AppLightGrey"
android:id="#+id/guest_detail_container"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/add_mid_one"
android:id="#+id/imageView"
android:layout_gravity="center"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="onClick"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Add Guest"
android:textColor="#color/AppWhite"
android:id="#+id/textView"
android:layout_gravity="center"
android:layout_below="#+id/imageView"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</FrameLayout>
guest_list_content.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/display1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#color/AppDarkGrey"> <!--Slave Layout-->
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/profile_image"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="#drawable/logo"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
app:civ_border_width="2dp"
app:civ_border_color="#83848A"/>
<TextView
android:id="#+id/id"
android:textColor="#color/AppWhite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:layout_marginRight="10dp"
android:layout_alignTop="#+id/profile_image"
android:layout_alignStart="#+id/content" />
<TextView
android:id="#+id/content"
android:textColor="#color/AppBlue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:layout_marginLeft="#dimen/text_margin"
android:layout_marginRight="#dimen/text_margin"
android:layout_alignBottom="#+id/profile_image"
android:layout_toEndOf="#+id/profile_image"
android:layout_marginStart="26dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/AppTime"
android:text="5:58pm"
android:layout_marginRight="10dp"
android:layout_centerVertical="true"
android:layout_alignParentEnd="true" />
<View android:background="#color/AppLightGrey" android:layout_width="fill_parent" android:layout_height="1dip" />
MyListActivity (Contains Pop Up Dialog Please ignore that Part)
package awesome.pyie.com.finalapp;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.SearchView;
import android.util.DisplayMetrics;
import android.view.View.OnClickListener;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Dialog;
import android.widget.Toast;
import org.w3c.dom.Text;
import awesome.pyie.com.finalapp.dummy.DummyContent;
import java.util.List;
public class GuestListActivity extends AppCompatActivity {
private boolean mTwoPane;
final Context context = this;
//API END POINT
public static final String JSON_URL = "*******";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_guest_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Toolbar title Removed
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.findViewById(R.id.textView2).setVisibility(View.INVISIBLE);
toolbar.findViewById(R.id.addTop).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.add_user_dialog);
dialog.show();
//Calculate Device Width and height
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
Window window = dialog.getWindow();
window.setLayout((int)(dpWidth), (int)((dpHeight)+50));
window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
TextView cancelText = (TextView) dialog.findViewById(R.id.textView2);
cancelText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
});
View recyclerView = findViewById(R.id.guest_list);
assert recyclerView != null;
setupRecyclerView((RecyclerView) recyclerView);
if (findViewById(R.id.guest_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
toolbar.findViewById(R.id.textView2).setVisibility(View.VISIBLE);
}
}
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(DummyContent.ITEMS));
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<DummyContent.DummyItem> mValues;
public SimpleItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.guest_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);
final ImageView imageView =(ImageView)findViewById(R.id.imageView);
final TextView textView = (TextView)findViewById(R.id.textView);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
//Code Here
imageView.setVisibility(View.GONE);
textView.setVisibility(View.GONE);
//Ends Here
Bundle arguments = new Bundle();
arguments.putString(GuestDetailFragment.ARG_ITEM_ID, holder.mItem.id);
GuestDetailFragment fragment = new GuestDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.guest_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, GuestDetailActivity.class);
intent.putExtra(GuestDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
}
});
imageView.setOnClickListener(new View.OnClickListener() {
//Start new list activity
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.add_user_dialog);
dialog.show();
//Calculate Device Width and height
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
Window window = dialog.getWindow();
window.setLayout((int)(dpWidth), (int)((dpHeight)+50));
window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
TextView cancelText = (TextView) dialog.findViewById(R.id.textView2);
cancelText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
}); //Add Button Function - will display the add page
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public DummyContent.DummyItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
If you guys want me to post any codes please let me know. Thanks in advanced!

Related

How to remove the last item in recyclerview adapter by a button?

I have a recyclerview and I want to delete the last item on it when I click a button that is not in the recyclerview. I want to delete the item and notify the adapter that the item is deleted so I can enter another item. By the way, the items I enter are by edittext and a button.
activity_main.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="match_parent"
tools:context="com.example.brecyclerview.MainActivity"
android:orientation="vertical">
<EditText
android:id="#+id/edit_ten"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Score"
android:inputType="numberSigned|number" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/btn_add"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="btn_add"
android:text="Add"
tools:ignore="OnClick" />
<Button
android:id="#+id/btn_undo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="btn_undo"
android:text="Undo"
tools:ignore="OnClick" />
<Button
android:id="#+id/btn_new"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="btn_new"
android:text="New Game" />
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycleViewContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:itemCount="8" />
</LinearLayout>
list_item.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="wrap_content">
<RelativeLayout
android:id="#+id/singleRow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<ImageView
android:id="#+id/userImg"
android:src="#mipmap/ic_launcher"
android:layout_width="60dp"
android:layout_height="60dp" />
<TextView
android:id="#+id/pNametxt"
android:text="User Name"
android:textSize="20sp"
android:layout_marginTop="6dp"
android:maxLines="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/userImg"
android:layout_toEndOf="#+id/userImg"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp" />
</RelativeLayout>
<View
android:layout_below="#+id/singleRow"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#f2f2f2" />
</RelativeLayout>
MainActivity.java:
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
int total = 0;
Button button;
Button button1;
Button button2;
EditText editText;
TextView personName;
RecyclerView recyclerView;
RecyclerView.Adapter mAdapter;
RecyclerView.LayoutManager layoutManager;
List<PersonUtils> personUtilsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.btn_add);
button1 = (Button)findViewById(R.id.btn_undo);
button2 = (Button)findViewById(R.id.btn_new);
editText = (EditText)findViewById(R.id.edit_ten);
personName = (TextView)findViewById(R.id.pNametxt);
recyclerView = (RecyclerView) findViewById(R.id.recycleViewContainer);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
personUtilsList = new ArrayList<>();
mAdapter = new CustomRecyclerAdapter(this, personUtilsList);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v == button2) {
MainActivity.this.finish();
startActivity(new Intent(MainActivity.this, MainActivity.class));
}}});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = 0; i<personUtilsList.size(); i++)
{
total = personUtilsList.get(i).getPersonName();
}
total += Integer.parseInt(editText.getText().toString());
personUtilsList.add(new PersonUtils(total));
recyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
editText.setText("");
}});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = 0; i<personUtilsList.size(); i++)
{
personUtilsList.remove(i).getPersonName();
personUtilsList.remove(new PersonUtils(total));
recyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}}
});
}}
CustomRecyclerAdapter.java:
import android.content.Context;
import android.preference.PreferenceScreen;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class CustomRecyclerAdapter extends RecyclerView.Adapter<CustomRecyclerAdapter.ViewHolder> {
private Context context;
private List<PersonUtils> personUtils;
public CustomRecyclerAdapter(Context context, List personUtils) {
this.context = context;
this.personUtils = personUtils;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.itemView.setTag(personUtils.get(position));
PersonUtils pu = personUtils.get(position);
holder.pName.setText(String.valueOf(pu.getPersonName()));
}
#Override
public int getItemCount() {
return (personUtils.size()>8)?8:personUtils.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public TextView pName;
final Button deleteButton;
public ViewHolder(final View itemView) {
super(itemView);
pName = (TextView) itemView.findViewById(R.id.pNametxt);
deleteButton = (Button) itemView.findViewById(R.id.btn_undo);
}
}}
PersonUtils.java:
public class PersonUtils {
private Integer personName;
public static void remove(int index) {
}
public Integer getPersonName() {
return personName;
}
public void setPersonName(Integer personName) {
this.personName = personName;
}
public PersonUtils(Integer personName) {
this.personName = personName;
}
}
I expect to delete the last item (integer) in the recyclerview and notify the adapter so I can edit the value when needed.
You can add a method in your adapter to remove last item in the list:
public ViewHolder removeLastItem() {
if (personUtils == null || personUtils.isEmpty()) return;
personUtils.removeAt(personUtils.getSize()-1);
notifyDataSetChanged();
}
When the button is clicked, just call:
adapter.removeLastItem()
Check if you are in the last index, then remove the item and use notifyItemRemoved to notify any registered observers:
if(currentPosition == 0){
listOfItems.removeAt(currentPosition)
notifyItemRemoved(currentPosition)
}

How to fix OnItemClickListener on ListView

This is java class MainActivity.java
package com.example.mhn.intercoapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.mhn.intercoapp.Adapters.EmployeeDirAdapter;
import com.example.mhn.intercoapp.static_class.EmployeeDir;
import java.util.ArrayList;
public class EmployeeDirectoryActivity extends AppCompatActivity {
ListView listView;
ImageView back_button;
EmployeeDir obj;
ArrayList <EmployeeDir> empDir ;
EmployeeDirAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_employee_directory);
listView = (ListView) findViewById(R.id.listView_emp_directory_xml);
back_button = (ImageView) findViewById(R.id.back_button_header_emp_directory_activity_xml);
obj = new EmployeeDir();
empDir = new ArrayList<>();
adapter = new EmployeeDirAdapter(getApplicationContext(),empDir);
back_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
finish();
}
});
obj.setEmp_name("Hafiz Sadique Umar");
obj.setEmp_email("hsu#gmail.com");
obj.setEmp_contact_num("+923045607057");
empDir.add(obj);
empDir.add(obj);
empDir.add(obj);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
String value = (String)adapter.getItemAtPosition(position);
Intent intent= new Intent(getApplicationContext(),DoneActivity.class);
startActivity(intent);
// assuming string and if you want to get the value on click of list item
// do what you intend to do on click of listview row
}
});
}
}
This is activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".EmployeeDirectoryActivity">
<RelativeLayout
android:id="#+id/relatice_layout_header_emp_directory_activity_xml"
android:background="#color/colorAccent"
android:layout_width="match_parent"
android:layout_alignParentTop="true"
android:layout_height="56dp">
<ImageView
android:id="#+id/back_button_header_emp_directory_activity_xml"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentLeft="true"
android:src="#drawable/back_arrow_header"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Employee Directory"
android:textColor="#fff"
android:textSize="18dp"
android:textStyle="bold"
android:layout_centerInParent="true"
/>
</RelativeLayout>
<ListView
android:clickable="true"
android:id="#+id/listView_emp_directory_xml"
android:layout_below="#id/relatice_layout_header_emp_directory_activity_xml"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</RelativeLayout>
This is Adapter
package com.example.mhn.intercoapp.Adapters;
import android.content.Context;
import android.content.Intent;
import android.text.util.Linkify;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.mhn.intercoapp.MainActivity;
import com.example.mhn.intercoapp.R;
import com.example.mhn.intercoapp.static_class.EmployeeDir;
import java.util.ArrayList;
public class EmployeeDirAdapter extends BaseAdapter {
Context context;
private LayoutInflater inflater;
private ArrayList<EmployeeDir> menuData=new ArrayList<>();
public EmployeeDirAdapter(Context context, ArrayList<EmployeeDir>EmpDir)
{
this.context = context;
this.menuData=EmpDir;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return menuData.size();
}
#Override
public Object getItem(int i) {
return menuData.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolderEmpDir holder;
if (convertView == null) {
holder = new ViewHolderEmpDir();
convertView = inflater.inflate(R.layout.emp_directory_list_row_layout, parent, false);
holder.name = (TextView) convertView.findViewById(R.id.name_textView_emp_directory_list_row_layout);
holder.email = (TextView) convertView.findViewById(R.id.email_textView_emp_directory_list_row_layout);
holder.phone = (TextView) convertView.findViewById(R.id.phone);
holder.pic = (ImageView) convertView.findViewById(R.id.emp_pic_emp_directory_list_row_layout);
holder.viewButton = (ImageView) convertView.findViewById(R.id.view_button_emp_dir_list_row_layout);
convertView.setTag(holder);
}
else
{
holder = (ViewHolderEmpDir) convertView.getTag();
}
holder.name.setText(menuData.get(position).getEmp_name());
holder.email.setText(menuData.get(position).getEmp_email());
holder.phone.setText(menuData.get(position).getEmp_contact_num());
//Linkify.addLinks(holder.email,Linkify.EMAIL_ADDRESSES);
//Linkify.addLinks(holder.phone,Linkify.PHONE_NUMBERS);
holder.pic.setImageResource(R.drawable.user_sign_up);
holder.viewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,MainActivity.class);
}
});
//downloadImage(position,holder);
return convertView;
}
// private void downloadImage(int position,ViewHolderShowAllBooking holder)
// {
// Picasso.with(context)
// .load("http://www.efefoundation.net/inklink/uploads/artist/"+menuData.get(position).getArtistId()+".jpg")
// .fit() // will explain later
// .into(holder.profile);
// }
static class ViewHolderEmpDir
{
TextView name;
TextView email;
TextView phone;
ImageView pic;
ImageView viewButton;
}
}
This is list_row_layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:weightSum="4"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_marginTop="5dp"
android:layout_centerHorizontal="true"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="70dp"
android:background="#color/colorAccent">
<ImageView
android:id="#+id/emp_pic_emp_directory_list_row_layout"
android:layout_marginTop="5dp"
android:layout_width="80dp"
android:layout_height="70dp"
android:layout_marginBottom="5dp"
android:src="#drawable/user_sign_up"/>
</RelativeLayout>
<RelativeLayout
android:background="#color/colorAccent"
android:layout_marginTop="5dp"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="3">
<TextView
android:id="#+id/name_textView_emp_directory_list_row_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:textColor="#fff"
android:textSize="18dp"
android:layout_alignParentLeft="true"
android:text="Husnain"/>
<TextView
android:id="#+id/phone"
android:layout_toRightOf="#id/name_textView_emp_directory_list_row_layout"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:autoLink="phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="***********"
android:textColor="#fff"/>
<TextView
android:id="#+id/email_textView_emp_directory_list_row_layout"
android:layout_alignParentLeft="true"
android:layout_below="#id/name_textView_emp_directory_list_row_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="mhn786#gmail.com"
android:autoLink="email"
android:layout_marginLeft="10dp"
android:textSize="18dp"
android:textColor="#fff"
/>
<ImageView
android:id="#+id/view_button_emp_dir_list_row_layout"
android:src="#drawable/view"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"/>
</RelativeLayout>
</LinearLayout>
When I apply OnItemClickListener it does not do any action like intent inside the func not called. I tried toast too but nothing shown on clicking the listView Items.
I also tried OnItemSlectedListener , it also not worked for me.
What is the problem here with this code. ?
Thanks Every One. Issue was with autolink on email and phone, I make their focusable=false but nothing happened.Then I remove it and guess what? Clicklistener also starts working.
The attribute android:clickable="true" in your ListView could be overriding all of click events of its child views, you should probably remove it:
<ListView
android:clickable="true" <!-- Remove this attribute -->
android:id="#+id/listView_emp_directory_xml"
android:layout_below="#id/relatice_layout_header_emp_directory_activity_xml"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

Facebook Native in feed ads are overlapping to each other in RecyclerView

I have an app which has Recyclerview and I want to put some facebook Native ads in between list items, like every 5 list items 1 native ad will be shown. everything is working perfectly but main problem is when I scroll down adChoice icon is being doubled and on scrolling up also adChoice icons are getting doubled. It seems that ads are overlapping to the previous one.
SCREENSHOT
Any suggestion will help me a lot. Here is the all source code and the official facebook audience network native ad code sample.
dependency
implementation 'com.android.support:cardview-v7:27.1.1'
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.android.volley:volley:1.1.0'
implementation 'com.facebook.android:audience-network-sdk:4.+'
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_id"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
content_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp" >
<TextView
android:id="#+id/textViewHead"
android:text="Heading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"/>
<TextView
android:id="#+id/textViewDesc"
android:text="Description"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
ads_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:orientation="vertical">
<LinearLayout
android:id="#+id/adChoicesContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|right"
android:orientation="vertical"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_gravity="center_vertical"
android:layout_marginBottom="5dp"
android:layout_marginRight="10dp"
android:orientation="horizontal">
<com.facebook.ads.AdIconView
android:id="#+id/adIconView"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
tools:src="#mipmap/ic_launcher"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/tvAdTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:maxLines="1"
android:textColor="#android:color/white"
tools:text="Ad Title"/>
<TextView
android:id="#+id/tvAdBody"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:ellipsize="end"
android:gravity="center_vertical"
android:lines="3"
android:textColor="#android:color/darker_gray"
tools:text="This is an ad description."/>
</LinearLayout>
</LinearLayout>
<com.facebook.ads.MediaView
android:id="#+id/mediaView"
android:layout_width="wrap_content"
android:layout_height="200dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
>
<TextView
android:id="#+id/sponsored_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:lines="1"
android:textColor="#android:color/darker_gray"
android:textSize="10sp"/>
<Button
android:id="#+id/btnCTA"
style="?android:attr/borderlessButtonStyle"
android:layout_width="130dp"
android:layout_height="40dp"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_gravity="right"
android:layout_marginTop="20dp"
android:background="#android:color/darker_gray"
android:gravity="center"
android:paddingLeft="3dp"
android:paddingRight="3dp"
android:text="Install Now"
android:textColor="#android:color/white"
android:textSize="14sp"/>
</RelativeLayout>
</LinearLayout>
ContentModel.java
package com.example.my_demo_app.fb_in-feed_ad;
public class ContentModel {
String head, des;
public ContentModel(String head, String des) {
this.head = head;
this.des = des;
}
public String getHead() {
return head;
}
public String getDes() {
return des;
}
}
MyAdapter.java
package com.example.my_demo_app.fb_in-feed_ad;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.facebook.ads.Ad;
import com.facebook.ads.AdChoicesView;
import com.facebook.ads.AdIconView;
import com.facebook.ads.MediaView;
import com.facebook.ads.NativeAd;
import java.util.ArrayList;
import java.util.List;
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int MENU_ITEM_VIEW_TYPE = 0;
public static final int AD_ITEM_VIEW_TYPE = 1;
private final List<Object> mRecyclerViewItems;
private final Context context;
public MyAdapter(List<Object> recyclerViewItems, Context context) {
this.mRecyclerViewItems = recyclerViewItems;
this.context = context;
}
//--------------------getItemViewType
#Override
public int getItemViewType(int position) {
Object recyclerViewItem = mRecyclerViewItems.get(position);
if (recyclerViewItem instanceof ContentModel) {
return MENU_ITEM_VIEW_TYPE;
} else if (recyclerViewItem instanceof Ad) {
return AD_ITEM_VIEW_TYPE;
} else {
return -1;
}
}
//--------------------getItemCount
#Override
public int getItemCount() {
return mRecyclerViewItems.size();
}
//--------------------onCreateViewHolder
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
if (viewType==MENU_ITEM_VIEW_TYPE){
View menuItemView = inflater.inflate(R.layout.content_layout, parent, false);
return new MenuItemHolder(menuItemView);
}else if (viewType==AD_ITEM_VIEW_TYPE){
View adItemView = inflater.inflate(R.layout.ads_layout, parent, false);
return new AdHolder(adItemView);
}
return null;
}
//--------------------onBindViewHolder
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
int itemType = getItemViewType(position);
if (itemType==MENU_ITEM_VIEW_TYPE){
MenuItemHolder menuItemHolder = (MenuItemHolder) holder;
ContentModel contentModel = (ContentModel) mRecyclerViewItems.get(position);
menuItemHolder.txtH.setText(contentModel.getHead());
menuItemHolder.txtD.setText(contentModel.getDes());
}else if (itemType==AD_ITEM_VIEW_TYPE){
AdHolder nativeAdViewHolder = (AdHolder) holder;
NativeAd nativeAd = (NativeAd) mRecyclerViewItems.get(position);
AdIconView adIconView = nativeAdViewHolder.adIconView;
TextView tvAdTitle = nativeAdViewHolder.tvAdTitle;
TextView tvAdBody = nativeAdViewHolder.tvAdBody;
Button btnCTA = nativeAdViewHolder.btnCTA;
LinearLayout adChoicesContainer = nativeAdViewHolder.adChoicesContainer;
MediaView mediaView = nativeAdViewHolder.mediaView;
TextView sponsorLabel = nativeAdViewHolder.sponsorLabel;
tvAdTitle.setText(nativeAd.getAdvertiserName());
tvAdBody.setText(nativeAd.getAdBodyText());
btnCTA.setText(nativeAd.getAdCallToAction());
sponsorLabel.setText(nativeAd.getSponsoredTranslation());
AdChoicesView adChoicesView = new AdChoicesView(context, nativeAd, true);
adChoicesContainer.addView(adChoicesView);
List<View> clickableViews = new ArrayList<>();
clickableViews.add(btnCTA);
clickableViews.add(mediaView);
nativeAd.registerViewForInteraction(nativeAdViewHolder.container, mediaView, adIconView, clickableViews);
}
}
//--------------------MenuItemHolder
public class MenuItemHolder extends RecyclerView.ViewHolder{
public TextView txtH, txtD;
public MenuItemHolder(View itemView) {
super(itemView);
txtH = (TextView) itemView.findViewById(R.id.textViewHead);
txtD = (TextView) itemView.findViewById(R.id.textViewDesc);
}
}
//--------------------AdHolder
public class AdHolder extends RecyclerView.ViewHolder{
AdIconView adIconView;
TextView tvAdTitle;
TextView tvAdBody;
Button btnCTA;
View container;
TextView sponsorLabel;
LinearLayout adChoicesContainer;
MediaView mediaView;
AdHolder(View itemView) {
super(itemView);
this.container = itemView;
adIconView = (AdIconView) itemView.findViewById(R.id.adIconView);
tvAdTitle = (TextView) itemView.findViewById(R.id.tvAdTitle);
tvAdBody = (TextView) itemView.findViewById(R.id.tvAdBody);
btnCTA = (Button) itemView.findViewById(R.id.btnCTA);
adChoicesContainer = (LinearLayout) itemView.findViewById(R.id.adChoicesContainer);
mediaView = (MediaView) itemView.findViewById(R.id.mediaView);
sponsorLabel = (TextView) itemView.findViewById(R.id.sponsored_label);
}
}
}
MainActivity.java
package com.example.my_demo_app.fb_in-feed_ad;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.facebook.ads.Ad;
import com.facebook.ads.AdError;
import com.facebook.ads.NativeAd;
import com.facebook.ads.NativeAdListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String URL_DATA = "https://res.cloudinary.com/ravi40/raw/upload/v1532239134/my_json/heroes_list.json";
private RecyclerView recyclerView;
private List<Object> mRecyclerViewItems;
MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view_id);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerViewItems = new ArrayList<>();
//--------------------Native Ad
NativeAd nativeAd = new NativeAd(getApplicationContext(), "IMG_16_9_LINK#YOUR_FACEBOOK_NATIVE_AD_PLACEMENT_ID_WILL_GOES_HERE"); // IMG_16_9_LINK# denote only testing purpose
nativeAd.setAdListener(new NativeAdListener() {
#Override
public void onMediaDownloaded(Ad ad) {
}
#Override
public void onError(Ad ad, AdError adError) {
}
#Override
public void onAdLoaded(Ad ad) {
for (int i=4; i<mRecyclerViewItems.size()+4; i+=5)
mRecyclerViewItems.add(i, ad);
adapter.notifyDataSetChanged();
}
#Override
public void onAdClicked(Ad ad) {
}
#Override
public void onLoggingImpression(Ad ad) {
}
});
nativeAd.loadAd();
loadRecyclerViewData();
}
private void loadRecyclerViewData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("heroes");
for (int i = 0; i<array.length(); i++){
JSONObject o = array.getJSONObject(i);
ContentModel item = new ContentModel(
o.getString("name"),
o.getString("about")
);
mRecyclerViewItems.add(item);
}
adapter = new MyAdapter(mRecyclerViewItems, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Ad are getting overlapped when adding in the container. The solution is to clear the container before adding the ads again.
For example:
AdChoicesView adChoicesView = new AdChoicesView(context, nativeAd, true);
// Clear the container.
adChoicesContainer.removeAllViews()
adChoicesContainer.addView(adChoicesView);

onItemClick not working for Card View

It uses retrofit 2.0 to fetch the data from the webservice and bind it to the card view. When I click on the card view having image and textviews, on click is not triggering, rather a strange behaviour is at the very corner edges of the card view onclick is triggering.
Item_row.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"
android:layout_margin="8dp"
card_view:cardCornerRadius="1dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
android:layout_margin="5dp"
android:clickable="true">
<ImageView
android:id="#+id/flowerImage"
android:layout_width="match_parent"
android:layout_height="200dp"
android:focusable="true"
android:clickable="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:visibility="visible"/>
<ImageButton
android:id="#+id/favIcon"
android:layout_width="32dp"
android:layout_height="32dp"
android:scaleType="fitXY"
android:layout_margin="5dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:descendantFocusability="blocksDescendants"
android:background="#drawable/ic_favorite_border"
android:focusable="true"
android:clickable="true"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/flowerImage"
android:orientation="vertical"
>
<TextView
android:id="#+id/flowerName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textColor="#color/colorPrimary"
android:textAppearance="?android:attr/textAppearanceMedium"
android:focusable="true"
android:clickable="true"
android:visibility="visible"/>
<TextView
android:id="#+id/flowerCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small Text"
android:layout_alignBottom="#id/flowerName"
android:textAppearance="?android:attr/textAppearanceSmall"
android:focusable="true"
android:clickable="true"
android:visibility="visible"/>
<TextView
android:id="#+id/flowerPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#id/flowerCategory"
android:text="New Text"
android:focusable="true"
android:clickable="true"
android:visibility="visible"/>
<TextView
android:id="#+id/flowerInstruction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:text="New Text"
android:focusable="true"
android:clickable="true"/>
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
Content_main.xml
Layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="8dp"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"/>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
</LinearLayout>
Main Activity Layout file
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"
android:elevation="8dp"/>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
The code base is following MVC design pattern. Controller does the job of getting the web service data
MainActivity.java
package com.innovation.myapp.jwelleryonrent.View;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import com.innovation.myapp.jwelleryonrent.R;
import com.innovation.myapp.jwelleryonrent.controller.jwelleryController;
import com.innovation.myapp.jwelleryonrent.model.adapter.CustomItemClickListner;
import com.innovation.myapp.jwelleryonrent.model.adapter.JwelleryAdapter;
import com.innovation.myapp.jwelleryonrent.model.pojo.JwelleryCollection;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements jwelleryController.JwelleryCallbackListener {
private Toolbar mToolbar;
private RecyclerView mRecyclerView;
private SwipeRefreshLayout mSwipeRefreshLayout;
private List<JwelleryCollection> mJwelleryList = new ArrayList<>();
private JwelleryAdapter mJwelleryAdapter;
private jwelleryController mController;
private boolean isInFavourites = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
configToolbar();
mController = new jwelleryController(MainActivity.this);
configViews();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.item_row, container, false);
ImageButton imgBtn = (ImageButton) findViewById(R.id.favIcon);
imgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addItemToBag(v);
}
});
return rootView;
}
private void addItemToBag(View v)
{
isInFavourites = true;
ImageButton btnFaviourite = (ImageButton) findViewById(R.id.favIcon);
if(isInFavourites==true) {
btnFaviourite.setImageResource(R.drawable.ic_favorite_white_24dp);
}
else
btnFaviourite.setImageResource(R.drawable.ic_favorite_border);
Snackbar.make(v, "Item added to Favourites", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
private void configToolbar() {
mToolbar = (Toolbar) this.findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
}
private void initializeAdapter()
{
mJwelleryAdapter = new JwelleryAdapter(mJwelleryList, new CustomItemClickListner() {
#Override
public void onItemClick(View v, int position) {
Toast.makeText(MainActivity.this, "Clicked Item: "+position,Toast.LENGTH_LONG).show();
}
});
mRecyclerView.setAdapter(mJwelleryAdapter);
mSwipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorAccent),
getResources().getColor(R.color.colorPrimary),
getResources().getColor(R.color.colorPrimaryDark));
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mController.startFetching();
}
});
}
private void configViews() {
mRecyclerView = (RecyclerView) this.findViewById(R.id.list);
mSwipeRefreshLayout = (SwipeRefreshLayout) this.findViewById(R.id.swipe);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
mRecyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
mController.startFetching();
initializeAdapter();
// mJwelleryAdapter= new JwelleryAdapter(mJwelleryList);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onFetchStart() {
}
#Override
public void onFetchProgress(JwelleryCollection jwellery) {
mJwelleryAdapter.addJwellery(jwellery);
}
#Override
public void onFetchProgress(List<JwelleryCollection> jwelleryList) {
}
#Override
public void onFetchComplete() {
mSwipeRefreshLayout.setRefreshing(false);
}
#Override
public void onFetchFailure() {
}
}
Recycler view uses the adapter view holder pattern to initialize the adapter
JwelleryAdapter class
package com.innovation.myapp.jwelleryonrent.model.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.innovation.myapp.jwelleryonrent.R;
import com.innovation.myapp.jwelleryonrent.View.MainActivity;
import com.innovation.myapp.jwelleryonrent.model.pojo.JwelleryCollection;
import com.innovation.myapp.jwelleryonrent.model.utilities.Constants;
import com.squareup.picasso.Picasso;
import java.util.List;
/**
*
*/
public class JwelleryAdapter extends RecyclerView.Adapter<JwelleryAdapter.Holder> {
private List<JwelleryCollection> mJwelleryCollection;
CustomItemClickListner itemListner;
Context mContext;
public JwelleryAdapter(List<JwelleryCollection> jwellery) {
mJwelleryCollection = jwellery;
}
public JwelleryAdapter( List<JwelleryCollection> jwellery,CustomItemClickListner listner) {
mJwelleryCollection = jwellery;
this.itemListner = listner;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row,parent,false);
final Holder mViewHolder = new Holder(row);
row.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
itemListner.onItemClick(v,mViewHolder.getPosition());
}
});
return mViewHolder;
}
#Override
public void onBindViewHolder(JwelleryAdapter.Holder holder, int position) {
JwelleryCollection currentJwellery = mJwelleryCollection.get(position);
holder.mName.setText(currentJwellery.mName);
holder.mCategory.setText(currentJwellery.mCategory);
holder.mPrice.setText(Double.toString(currentJwellery.mPrice));
holder.mInstructions.setText(currentJwellery.mInstructions);
Picasso.with(holder.itemView.getContext()).load(Constants.PHOTO_URL + currentJwellery.mPhoto).into(holder.mImage);
}
public void addJwellery(JwelleryCollection jwellery) {
mJwelleryCollection.add(jwellery);
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return mJwelleryCollection.size();
}
public class Holder extends RecyclerView.ViewHolder implements View.OnClickListener {
Context contxt;
public TextView mName, mCategory, mPrice, mInstructions;
public ImageView mImage;
public Holder(View itemView) {
super(itemView);
mImage = (ImageView) itemView.findViewById(R.id.flowerImage);
mName = (TextView) itemView.findViewById(R.id.flowerName);
mCategory = (TextView) itemView.findViewById(R.id.flowerCategory);
mPrice = (TextView) itemView.findViewById(R.id.flowerPrice);
mInstructions = (TextView) itemView.findViewById(R.id.flowerInstruction);
}
public Holder(View itemView,int ViewType,Context c) {
// Creating ViewHolder Constructor with View and viewType As a parameter
super(itemView);
contxt = c;
itemView.setClickable(true);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(contxt, "The Item Clicked is: " + getPosition(), Toast.LENGTH_SHORT).show();
}
}
}
CustomerItemClickListner Interface to handle row item on click
package com.innovation.myapp.jwelleryonrent.model.adapter;
import android.view.View;
/**
*
*/
public interface CustomItemClickListner {
public void onItemClick(View v,int position);
}
First create one variable of your interface in your adapter:
CustomItemClickListener mListener;
then like you have set in your OnClick() method:
if (mListener != null) {
mListener.onItemClick(v, getAdapterPosition());
}
and the last thing you need to modify in your adapter is creating new method which you will call later in your activity class for handling listener:
public void setOnItemClickListener(CustomItemClickListener listener) {
mListener = listener;
}
now you can call this method in your activity like this:
adapter.setOnItemClickListener(this); // implement interface
// or
adapter.setOnItemClickListener(new CustomItemClickListener());

CheckBox in recyclerview not working and unable to pass the checked items to another fragment

I have a favorite checkbox in my recyclerview. My problem is checkbox is not clickable inside recyclerview. and i have to pass the ticked recyclerview items to another recyclerview. Really I got stucked here . anyone please help me. Thanks in advance.
recycler_view_item.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="210dp"
android:background="#color/cardview_light_background"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="210dp">
<View
android:id="#+id/divider"
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#color/common_action_bar_splitter" />
<ImageView
android:id="#+id/PROJECT_image"
android:layout_width="match_parent"
android:layout_height="#dimen/list_item_avatar_size"
android:layout_below="#id/divider"
android:background="#drawable/mirlogo"
android:scaleType="fitXY" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" STATUS "
android:background="#color/common_action_bar_splitter"
android:id="#+id/PROJECT_status"
android:rotation="-45"
android:layout_below="#+id/divider"
android:layout_alignLeft="#+id/divider"
android:layout_alignStart="#+id/divider"
android:layout_marginTop="15dp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#80000000"
android:layout_alignParentBottom="true">
<TextView
android:id="#+id/PROJECT_name"
android:textColor="#color/cardview_light_background"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Project"
android:textSize="18sp"
android:textAppearance="?attr/textAppearanceListItem" />
<TextView
android:id="#+id/PROJECT_city"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/PROJECT_name"
android:text="kerala"
android:textColor="#color/common_action_bar_splitter"
android:textSize="16sp"
android:textAppearance="?attr/textAppearanceListItem" />
<TextView
android:id="#+id/PROJECT_type"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/PROJECT_city"
android:text="india"
android:background="#android:color/holo_green_dark"
android:textColor="#color/cardview_light_background"
android:textSize="15sp"
android:textAppearance="?attr/textAppearanceListItem" />
<CheckBox
android:id="#+id/PROJECT_fav"
android:layout_width="30sp"
android:layout_height="30sp"
android:layout_alignBottom="#+id/PROJECT_city"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginRight="5dp"
android:layout_marginEnd="5dp"
android:background="#drawable/selector"
android:button="#null"
/>
</RelativeLayout>
</RelativeLayout>
RecyclerviewAdapter
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.root5solutions.mirrealtors.R;
public class HomeDataManager extends RecyclerView.Adapter<HomeDataManager.RecyclerViewHolder> {
public static class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView mProjectName, mProjectCity, mProjectType, mProjectStatus;
ImageView mImage;
CheckBox mCheck;
RecyclerViewHolder(View itemView) {
super(itemView);
mProjectName = (TextView) itemView.findViewById(R.id.PROJECT_name);
mProjectCity = (TextView) itemView.findViewById(R.id.PROJECT_city);
mProjectType = (TextView) itemView.findViewById(R.id.PROJECT_type);
mProjectStatus = (TextView) itemView.findViewById(R.id.PROJECT_status);
mImage = (ImageView) itemView.findViewById(R.id.PROJECT_image);
mCheck = (CheckBox) itemView.findViewById(R.id.PROJECT_fav);
}
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recyclerview_item, viewGroup, false);
return new RecyclerViewHolder(v);
}
#Override
public void onBindViewHolder(final RecyclerViewHolder viewHolder, int i) {
// get the single element from the main array
final HomeProjects projects = HomeProjects.PROJECTS[i];
// Set the values
viewHolder.mProjectName.setText(projects.get(HomeProjects.Field.NAME));
viewHolder.mProjectCity.setText(projects.get(HomeProjects.Field.CITY));
viewHolder.mProjectType.setText(projects.get(HomeProjects.Field.TYPE));
viewHolder.mProjectStatus.setText(projects.get(HomeProjects.Field.STATUS));
viewHolder.mImage.setImageResource(projects.geti(HomeProjects.Field.IMAGE));
viewHolder.mCheck.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
viewHolder.mCheck.setChecked(!viewHolder.mCheck.isChecked());
Log.d("Tag Name", "Log Message");
}
});
#Override
public int getItemCount() {
return HomeProjects.PROJECTS.length;
}
}
RecyclerviewFragment
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.root5solutions.mirrealtors.HomeRecyclerDetailActivity;
import com.example.root5solutions.mirrealtors.ProjectRecyclerDetailActivity;
import com.example.root5solutions.mirrealtors.R;
import com.example.root5solutions.mirrealtors.projectdatabase.HomeDataManager;
import com.example.root5solutions.mirrealtors.projectdatabase.HomeProjects;
import com.example.root5solutions.mirrealtors.projectdatabase.Projects;
import com.example.root5solutions.mirrealtors.projectdatabase.RecyclerClickListener;
import com.kogitune.activity_transition.ActivityTransitionLauncher;
public class RecyclerTab1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.home_tab1_recycler, container, false);
RecyclerView rv = (RecyclerView) v.findViewById(R.id.home_recyclerview);
LinearLayoutManager llm = new LinearLayoutManager(getContext());
rv.setLayoutManager(llm);
rv.setHasFixedSize(true); // to improve performance
rv.setAdapter(new HomeDataManager()); // the projectdatabase manager is assigner to the RV
rv.addOnItemTouchListener( // and the click is handled
new RecyclerClickListener(getContext(), new RecyclerClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent intent = new Intent(getActivity(), HomeRecyclerDetailActivity.class);
intent.putExtra(HomeRecyclerDetailActivity.ID, HomeProjects.PROJECTS[position].getId());
ActivityTransitionLauncher.with(getActivity()).from(view).launch(intent);
}
}));
return v;
}
}
Remove the onClickListener and set onCheckedChangeListener. Then save your list to an array in Sharedpreference
viewHolder.mCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Snackbar snackbar = Snackbar.make(viewHolder.itemView, "Item Favorited", Snackbar.LENGTH_SHORT);
snackbar.show();
} else {
Snackbar snackbar = Snackbar.make(viewHolder.itemView, "Item Unfavorited", Snackbar.LENGTH_SHORT);
snackbar.show();
}
int position = viewHolder.getAdapterPosition();
mCheckedItems.put(position, isChecked);
List<Integer> selected = new ArrayList<>();
for (int i = 0; i < mCheckedItems.size(); i++) {
final boolean checked = mCheckedItems.valueAt(i);
if (checked) {
selected.add(mCheckedItems.keyAt(i));
}
}
Log.e("Checked Array = ", String.valueOf(selected));
SharedPreferences prefs = v1.getContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putString("Checkbox", String.valueOf(selected));
edit.commit();
Log.e("Shared Preference = ", String.valueOf(edit));
}
});

Categories

Resources