So here is the gist of the issue, I have implemented RecyclerViews in several activities successfully, however this particular RecyclerView DOES NOT DISPLAY ANYTHING!
I have created a fragment within a tablayout to display, and also rewritten the code thrice. Here is the code for the entire fragment(View is inflating fine, along with a searchbar on top of the recycler) adapter is at the bottom. I have left OnBindViewHolder blank on purpose as I wrote it twice before aldready without any results. Any help would be appreciated.
Fragment + Adapter code:
public static class EditJob extends Fragment {
ServerRequests serverRequests;
UserLocalStore userLocalStore;
User receivedUser;
EditText searchJob;
ImageView searchBtn;
RecyclerView editJobRecycler;
MyRecyclerAdapter editJobAdapter;
ArrayList<Job> arrayJob;
TextView noJobSearch;
#Override
public void onAttach(Context context) {
super.onAttach(context);
serverRequests = new ServerRequests(context);
userLocalStore = new UserLocalStore(context);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_edit_job, container, false);
receivedUser = userLocalStore.getAllDetails();
arrayJob = new ArrayList<>();
noJobSearch = (TextView) view.findViewById(R.id.noJobEdit);
searchJob = (EditText) view.findViewById(R.id.etEditJob);
searchBtn = (ImageView) view.findViewById(R.id.editJobImage);
editJobRecycler = (RecyclerView) view.findViewById(R.id.jobEditRecycler);
editJobAdapter = new MyRecyclerAdapter(arrayJob);
editJobRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
editJobRecycler.setAdapter(editJobAdapter);
searchBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
searchJob();
}
});
return view;
}
public void searchJob() {
arrayJob.clear();
serverRequests.searchJobListings(searchJob.getText().toString(), new GetJobObjectsCallBack() {
#Override
public void done(Job[] returnedJobs) {
if (returnedJobs == null || returnedJobs.length == 0) {
noJobSearch.setVisibility(View.VISIBLE);
} else {
noJobSearch.setVisibility(View.GONE);
for (int i = 0; i < returnedJobs.length; i++) {
arrayJob.add(i, returnedJobs[i]);
}
editJobAdapter = new MyRecyclerAdapter(arrayJob);
editJobRecycler.setAdapter(editJobAdapter);
editJobAdapter.notifyDataSetChanged();
}
}
});
}
private class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.VH> {
ArrayList<Job> jobArray;
public MyRecyclerAdapter(ArrayList<Job> jl) {
jobArray = jl;
}
public class VH extends RecyclerView.ViewHolder {
TextView jobID, jobPosition, jobExperience, jobRemarks, jobLocation, jobDescription, jobDomain;
EditText etjobID, etjobPosition, etjobExperience, etjobRemarks, etjobLocation, etjobDescription, etjobDomain;
Button bEditJob;
public VH(View v) {
super(v);
jobID = (TextView) v.findViewById(R.id.returnedJobID);
jobExperience = (TextView) v.findViewById(R.id.returnedJobExperience);
jobRemarks = (TextView) v.findViewById(R.id.returnedJobRemarks);
jobLocation = (TextView) v.findViewById(R.id.returnedJobLocation);
jobDescription = (TextView) v.findViewById(R.id.returnedJobDescription);
jobDomain = (TextView) v.findViewById(R.id.returnedJobDomain);
jobPosition = (TextView) v.findViewById(R.id.returnedJobPosition);
etjobID = (EditText) v.findViewById(R.id.etreturnedJobID);
etjobPosition = (EditText) v.findViewById(R.id.etreturnedJobPosition);
etjobExperience = (EditText) v.findViewById(R.id.etreturnedJobExperience);
etjobRemarks = (EditText) v.findViewById(R.id.etreturnedJobRemarks);
etjobLocation = (EditText) v.findViewById(R.id.etreturnedJobLocation);
etjobDescription = (EditText) v.findViewById(R.id.etreturnedJobDescription);
etjobDomain = (EditText) v.findViewById(R.id.etreturnedJobDomain);
bEditJob = (Button) v.findViewById(R.id.bEditJob);
}
}
#Override
public VH onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater li = LayoutInflater.from(parent.getContext());
View v = li.inflate(R.layout.job_edit_listview, parent);
return new VH(v);
}
#Override
public void onBindViewHolder(VH holder, int position) {
Job current = jobArray.get(position);
}
#Override
public int getItemCount() {
System.out.println("jobarray size = " + jobArray.size());
return jobArray.size();
}
}
}
XML for the fragment:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
style="#style/FloatingTextView"
android:layout_marginTop="10dp"
android:elevation="6dp"
android:layout_width="match_parent"
android:layout_height="50dp"
android:animateLayoutChanges="true">
<EditText
android:id="#+id/etEditJob"
style="#style/FloatingTextView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="0.5dp"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/editJobDivider"
android:elevation="0dp"
android:hint="Enter a search term"
android:translationZ="0dp" />
<View
android:id="#+id/editJobDivider"
android:layout_width="1dp"
android:layout_height="40dp"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/editJobImage"
android:alpha="0.2"
android:background="#color/Black" />
<ImageView
android:id="#+id/editJobImage"
style="#style/FloatingTextView"
android:layout_width="47dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_margin="1dp"
android:alpha="0.5"
android:clickable="true"
android:elevation="0dp"
android:padding="10dp"
android:src="#drawable/ic_search_black_48dp"
android:translationZ="0dp" />
</RelativeLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="No Jobs match your query"
android:id="#+id/noJobEdit"/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="2dp"
android:id="#+id/jobEditRecycler"/>
</LinearLayout>
PS: I have checked the dataset which is returning a size on querying the database, the adapter has been notified too and the getItemCount returns a non-zero size. I am honestly clueless as to what the problem is!
EDIT: Here is the (almost) identical code i used for another static inner class fragment. This implementation works just fine.
public static class JobSearcher extends Fragment {
EditText searchJob;
ImageView searchImage;
RecyclerView searchJobListView;
ArrayList<Job> arrayJob;
ServerRequests serverRequests;
Context parentActivity;
UserLocalStore userLocalStore;
TextView noJobSearch;
MyJobRecyclerAdapter jobArrayAdapter;
User receivedUser;
#Override
public void onAttach(Context activity) {
super.onAttach(activity);
parentActivity = activity;
serverRequests = new ServerRequests(activity);
userLocalStore = new UserLocalStore(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_search_job, container, false);
searchJob = (EditText) v.findViewById(R.id.searchJobEditText);
searchImage = (ImageView) v.findViewById(R.id.searchJobImage);
receivedUser = userLocalStore.getAllDetails();
noJobSearch = (TextView) v.findViewById(R.id.noJobSearch);
searchImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchJob();
}
});
searchJobListView = (RecyclerView) v.findViewById(R.id.jobSearchRecycler);
arrayJob = new ArrayList<>();
jobArrayAdapter = new MyJobRecyclerAdapter(arrayJob);
searchJobListView.setLayoutManager(new LinearLayoutManager(getContext()));
searchJobListView.setAdapter(jobArrayAdapter);
return v;
}
public void searchJob() {
arrayJob.clear();
serverRequests.searchJobListings(searchJob.getText().toString(), new GetJobObjectsCallBack() {
#Override
public void done(Job[] returnedJobs) {
if (returnedJobs == null || returnedJobs.length == 0) {
noJobSearch.setVisibility(View.VISIBLE);
} else {
noJobSearch.setVisibility(View.GONE);
for (int i = 0; i < returnedJobs.length; i++) {
arrayJob.add(i, returnedJobs[i]);
}
jobArrayAdapter = new MyJobRecyclerAdapter(arrayJob);
searchJobListView.setAdapter(jobArrayAdapter);
jobArrayAdapter.notifyDataSetChanged();
}
}
});
}
public class MyJobRecyclerAdapter extends RecyclerView.Adapter<MyJobRecyclerAdapter.ViewHolder> {
ArrayList<Job> arrayJob = new ArrayList<>();
public MyJobRecyclerAdapter(ArrayList<Job> jl) {
arrayJob = jl;
}
#Override
public MyJobRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater li = LayoutInflater.from(parent.getContext());
View inflatedView = li.inflate(R.layout.job_item_list, parent, false);
ViewHolder VH = new ViewHolder(inflatedView);
return VH;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Job currentJob = arrayJob.get(position);
holder.jobDesc.setText("Job Description: " + currentJob.getDescription());
holder.jobID.setText("ID: " + currentJob.getID());
holder.jobRemarks.setText("Remarks: " + currentJob.getRemarks());
holder.jobExperience.setText("Experience Required: " + currentJob.getExperience() + " years");
holder.jobDomain.setText("Domain: " + currentJob.getDomain());
holder.jobLoc.setText("Location: " + currentJob.getLocation());
holder.jobType.setText("Type: " + currentJob.getType());
holder.jobPos.setText("Position: " + currentJob.getPosition());
}
#Override
public int getItemCount() {
return arrayJob.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView jobID, jobDesc, jobType, jobLoc, jobPos, jobRemarks, jobExperience, jobDomain;
Button applyForJob;
public ViewHolder(View itemView) {
super(itemView);
jobID = (TextView) itemView.findViewById(R.id.returnedJobID);
jobDesc = (TextView) itemView.findViewById(R.id.returnedJobDescription);
jobLoc = (TextView) itemView.findViewById(R.id.returnedJobLocation);
jobType = (TextView) itemView.findViewById(R.id.returnedJobType);
jobPos = (TextView) itemView.findViewById(R.id.returnedJobPosition);
jobRemarks = (TextView) itemView.findViewById(R.id.returnedJobRemarks);
jobExperience = (TextView) itemView.findViewById(R.id.returnedJobExperience);
jobDomain = (TextView) itemView.findViewById(R.id.returnedJobDomain);
applyForJob = (Button) itemView.findViewById(R.id.bApplyJob);
applyForJob.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bApplyJob:
serverRequests.applyForJob(receivedUser.getEmail(), receivedUser.getName(), jobID.getText().toString(), jobPos.getText().toString());
}
}
}
}
Your ViewHolder must work with views for display. Example:
public VH(View v) {
super(v);
jobLocation = (TextView) v.findViewById(R.id.returnedJobLocation);
jobLocation.setText("something location");
}
Related
I'm a beigner working on firebase java android. My problem is that i cannot load the recyclerView it is showing that adapter not attached Skipping layout even though I've attached the adapter still its showing the same
Below is my code please help me. Thanks in advance
private RecyclerView bookList,listOrg,listcustom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_work_employee);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
MyCustomWorkRef = FirebaseDatabase.getInstance().getReference().child("WorksCustomAdded");
bookList = findViewById(R.id.myCustomerList);
listcustom = findViewById(R.id.myCustomerListCustom);
bookList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MyWorkEmployeeActivity.this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
bookList.setLayoutManager(linearLayoutManager);
listcustom.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(MyWorkEmployeeActivity.this);
linearLayoutManager2.setReverseLayout(true);
linearLayoutManager2.setStackFromEnd(true);
listcustom.setLayoutManager(linearLayoutManager2);
//LoadDat();
DisplayCustom("ltG284DWVbbxfHlD3vAiiwkEv963","22883b15-d432-42b7-8ba5-1b3d4586ff09");
// DisplayCustom();
}
This is my Display Custom Function
private void DisplayCustom(String cmpnyUID,String empId) {
Toast.makeText(getApplicationContext(), "CompnUID : " + cmpnyUID + "\n empID : "+empId, Toast.LENGTH_SHORT).show();
Query SortPostsInDecendingOrder = MyCustomWorkRef.child(cmpnyUID).orderByChild("empID").equalTo(empId);;
FirebaseRecyclerOptions<MyCustomer> options = new FirebaseRecyclerOptions.Builder<MyCustomer>()
.setQuery(SortPostsInDecendingOrder, MyCustomer.class)
.build();
FirebaseRecyclerAdapter<MyCustomer, MyWorkEmployeeActivity.PBooksViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<MyCustomer, MyWorkEmployeeActivity.PBooksViewHolder>(options)
{
#NonNull
#Override
public MyWorkEmployeeActivity.PBooksViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i)
{
View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.viewwork_list_eng, viewGroup, false);
MyWorkEmployeeActivity.PBooksViewHolder viewHolder =new MyWorkEmployeeActivity.PBooksViewHolder(view);
return viewHolder;
}
#Override
protected void onBindViewHolder(#NonNull MyWorkEmployeeActivity.PBooksViewHolder holder, int position, #NonNull MyCustomer model)
{
final String pos = getRef(position).getKey();
String cmpnyID = model.getCmpnyID();
String wrkID = model.getWrkSiteID();
String engID = model.getEngKey();
String usrID = model.getUsrkey();
holder.bookname.setText(model.getUsrname());
holder.count.setText("Work No: \n"+model.getCnt());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reqIntent = new Intent(MyWorkEmployeeActivity.this, ViewCustomWrkActivity.class);
reqIntent.putExtra("wrkID", model.getWrkSiteID());
reqIntent.putExtra("usrkey","0");
startActivity(reqIntent);
}
});
}
};
listcustom.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
}
public class PBooksViewHolder extends RecyclerView.ViewHolder {
TextView bookname, bookauthor,fees ,count;
ImageView profImage;
LinearLayout mView;
String t_area, b_area, plan, allow;
public PBooksViewHolder(#NonNull View itemView) {
super(itemView);
profImage = itemView.findViewById(R.id.ivRequestProfile);
bookname = itemView.findViewById(R.id.tvRequestUserName);
bookauthor = itemView.findViewById(R.id.tvWorksCompletedEngineerList);
mView = itemView.findViewById(R.id.request_layout);
fees = itemView.findViewById(R.id.tvFeesEngineerList);
count = itemView.findViewById(R.id.wrkCount);
}
}
I found the answer for this problem. In My xml File I've been using match_parent on the height. Which caused the main thread to skip the layout, because it couldn't find the layout scales.
So I changed the value to some standard height in dp. Eg: 600dp. Which defined the layout correctly so now the recyclerView is loading perfectly without skipping the layout.
my XML Code
`
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/myWorkListemp"
android:layout_width="match_parent"
android:layout_height="700dp"
android:layout_marginTop="15dp" />
<androidx.recyclerview.widget.RecyclerView
android:visibility="gone"
android:id="#+id/myCustomerListCustom"
android:layout_width="match_parent"
android:layout_height="700dp"
android:layout_marginTop="15dp" />
</LinearLayout>
`
I have a recycleView (see picture). You see there are 2 buttons too. Here's the layout file.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="#color/white">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_marginLeft="10dp"
android:id="#+id/main_picture"
android:layout_width="45dp"
android:layout_height="50dp"
android:src="#drawable/pfl_img"
android:layout_centerVertical="true"
android:layout_alignParentStart="true" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="#id/main_picture"
android:layout_marginRight="5dp"
android:layout_marginLeft="10dp"
android:id="#+id/relativeLayout2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Edem Palonik"
android:textSize="17sp"
android:id="#+id/textName"
android:textColor="#color/black"
android:layout_above="#+id/textDescription"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Profession and ..."
android:textColor="#color/black"
android:textSize="17sp"
android:id="#+id/textDescription"
android:layout_centerVertical="true"
android:layout_alignParentStart="true" />
<ImageView
android:layout_width="20dp"
android:layout_height="18dp"
android:layout_marginTop="2dp"
android:layout_below="#+id/textDescription"
android:id="#+id/historyIcon"
android:layout_alignParentStart="true" />
<TextView
android:layout_marginLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/date"
android:textSize="14sp"
android:text="17/12/2017/13:46"
android:layout_marginTop="2dp"
android:layout_below="#+id/textDescription"
android:layout_toEndOf="#+id/historyIcon" />
</RelativeLayout>
<Button
android:id="#+id/call_button"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_marginRight="10dp"
android:background="#drawable/call_img"
android:layout_centerVertical="true"
android:layout_toStartOf="#+id/sms_button" />
<Button
android:id="#+id/sms_button"
android:layout_width="37dp"
android:layout_height="32dp"
android:background="#drawable/sms_img"
android:layout_alignTop="#+id/call_button"
android:layout_alignParentEnd="true" />
<View
android:layout_width="match_parent"
android:layout_height="0.8dp"
android:layout_alignParentBottom="true"
android:background="#color/gray" />
I know, I can use recyclerViewItemCLickListener, but I wanna click on last 2 buttons separately, so what do I need to do?
So I wanna click on last buttons separately, without clicking all line, I want only last buttons to be clickable.
Here's the java code.
public class ConnectionsFragment extends Fragment {
private View mainView;
private RecyclerView recyclerView;
private List<Connections_item> list;
private Button call, sms;
public ConnectionsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.connections_fragment, container, false);
recyclerView = (RecyclerView) mainView.findViewById(R.id.recycler_connection);
ConnectionsAdapter adapter = new ConnectionsAdapter(getActivity(), list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
init(mainView);
return mainView;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list = new ArrayList<>();
list.add(new Connections_item(R.drawable.pfl_img, "Anun Azganun1", "Inch vor text", R.drawable.missed, "23/11/1998 00:00"));
list.add(new Connections_item(R.drawable.pfl_img, "Anun Azganun2", "Inch vor text", R.drawable.callagain, "24/11/1998 01:00"));
list.add(new Connections_item(R.drawable.pfl_img, "Anun Azganun3", "Inch vor text", R.drawable.missed, "25/11/1998 02:00"));
public void init(View v) {
call = (Button) v.findViewById(R.id.call_button);
sms = (Button) v.findViewById(R.id.sms_button);
// call.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// Toast.makeText(getActivity(), "Whom you wanna call?", Toast.LENGTH_SHORT).show();
// }
// });
// sms.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// Toast.makeText(getActivity(), "Whom you wanna send sms?", Toast.LENGTH_SHORT).show();
// }
// });
}
}
Here's the adapter code.
public class ConnectionsAdapter extends RecyclerView.Adapter<ConnectionsAdapter.MyViewHolder> {
Context context;
List<Connections_item> list = new ArrayList<>();
public ConnectionsAdapter(Context context, List<Connections_item> list) {
this.context = context;
this.list = list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(context).inflate(R.layout.connections_view_item, parent, false);
MyViewHolder holder = new MyViewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.mainImage.setImageResource(list.get(position).getMainImage());
holder.fullName.setText(list.get(position).getFullName());
holder.description.setText(list.get(position).getDescription());
holder.historyImage.setImageResource(list.get(position).getHistoryIcon());
holder.date.setText(list.get(position).getDate());
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
ImageView mainImage, historyImage;
TextView fullName, description, date;
Button call, sms;
public MyViewHolder(View v) {
super(v);
mainImage = (ImageView) v.findViewById(R.id.main_picture);
historyImage = (ImageView) v.findViewById(R.id.historyIcon);
fullName = (TextView) v.findViewById(R.id.textName);
description = (TextView) v.findViewById(R.id.textDescription);
date = (TextView) v.findViewById(R.id.date);
call = (Button) v.findViewById(R.id.call_button);
sms = (Button) v.findViewById(R.id.sms_button);
}
}
}
Using interface you can achieve this
public class TestAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context mContext;
ArrayList<Data> mData;
OnButtonClickListeners onButtonClickListeners;
public TestAdapter(Context mContext, ArrayList<String> mData) {
this.mContext = mContext;
this.mData = mData;
}
public void setOnButtonClickListeners(OnButtonClickListeners listener){
this.onButtonClickListeners = listener;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
MyViewHolder vh;
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
//Bind holder here
}
#Override
public int getItemCount() {
return mData.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
#Bind(R.id.call_button)
Button btnCall;
#Bind(R.id.sms_button)
Button btnSms;
public MyViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
btnCall.setOnClickListener(this);
btnSms.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(this.onButtonClickListeners!=null){
switch (v.getId()) {
case R.id.call_button:
onButtonClickListeners.onCallClick(getAdapterPosition());
break;
case R.id.sms_button:
onButtonClickListeners.onSmsClick(getAdapterPosition());
break;
}
}
}
}
public interface OnButtonClickListeners{
void onCallClick(int position);
void onSmsClick(int position);
}
}
Then After you can use the call to this interface from Activity and Fragment like below
private void setUpRecyclerView(){
mAdapter = new ProfileAdapter(mContext,new ArrayList<String>());
lm = new LinearLayoutManager(getActivity());
rvFeeds.setLayoutManager(lm);
rvFeeds.setAdapter(mAdapter);
mAdapter.setOnButtonClickListeners(new OnButtonClickListeners() {
#Override
public void onCallClick(int position) {
//To do your code here
}
#Override
public void onSmsClick(int position) {
//To do your code here
}
})
}
As adapter holds the recyclerView item and buttons are in the item
so all code related to button will be in the adapter only.
In adapter modify the code :
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.mainImage.setImageResource(list.get(position).getMainImage());
holder.fullName.setText(list.get(position).getFullName());
holder.description.setText(list.get(position).getDescription());
holder.historyImage.setImageResource(list.get(position).getHistoryIcon());
holder.date.setText(list.get(position).getDate());
holder.call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Whom you wanna call?", Toast.LENGTH_SHORT).show();
}
});
holder.sms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Whom you wanna send sms?", }
});
}
In java file just remove call and sms button initialization and listners.
You can try to implement onClickListener to the buttons when you are creating the view in the ViewHolder for the recycler view. Then pass an interface with two methods for two buttons and implement the interface in where ever you require.
Like the example:
public class MyViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View itemView, ButtonClickListener listner) {
super(itemView);
Button b1 = itemView.findViewById(...);
Button b2 = itemView.findViewById(...);
b1.setOnClickListener(view -> listener.onButton1Click());
b2.setOnClickListener(view -> listener.onButton2Click());
}
}
And now the interface
public interface ButtonClickListener {
void onButton1Click();
void onButton2Click();
}
Otherwise, if you are accustomed with bus you can use instead of using interface. It will make the code much cleaner.
This is my wordAdapter. It is not showing any result when I open the Fragment. Please help me as I am a novice android developer. The Fragment page is empty and it is also not showing any error while running. So, please tell what am I missing and what is the problem in this code.
public class wordAdapter extends ArrayAdapter<word> {
private Context context;
private List<word> wrd;
private SharedPreference sharedPreference;
public wordAdapter(Context context, List<word> wrd) {
super(context, R.layout.item, wrd);
this.context = context;
this.wrd = wrd;
sharedPreference = new SharedPreference();
}
private class ViewHolder {
TextView productNameTxt;
TextView productTypeTxt;
ImageView favoriteImg;
}
#Override
public int getCount() {
return wrd.size();
}
#Override
public word getItem(int position) {
return wrd.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item, null);
holder = new ViewHolder();
holder.productNameTxt = (TextView) convertView
.findViewById(R.id.carname);
holder.productTypeTxt = (TextView) convertView
.findViewById(R.id.cartype);
holder.favoriteImg = (ImageView) convertView
.findViewById(R.id.favu);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
word wrdn = (word) getItem(position);
holder.productNameTxt.setText(wrdn.getName());
holder.productTypeTxt.setText(wrdn.getType());
/*If a product exists in shared preferences then set heart_red drawable
* and set a tag*/
if (checkFavoriteItem(wrdn)) {
holder.favoriteImg.setImageResource(R.drawable.fav);
holder.favoriteImg.setTag("red");
} else {
holder.favoriteImg.setImageResource(R.drawable.unfav);
holder.favoriteImg.setTag("grey");
}
return convertView;
}
/*Checks whether a particular product exists in SharedPreferences*/
private boolean checkFavoriteItem(word checkwrdn) {
boolean check = false;
List<word> favorites = sharedPreference.getFavorites(context);
if (favorites != null) {
for (word wrdn : favorites) {
if (wrdn.equals(checkwrdn)) {
check = true;
break;
}
}
}
return check;
}
#Override
public void add(word wrdn) {
super.add(wrdn);
wrd.add(wrdn);
notifyDataSetChanged();
}
#Override
public void remove(word wrdn) {
super.remove(wrdn);
wrd.remove(wrdn);
notifyDataSetChanged();
}
}
This is my word file.
public class word {
private String name;
private String type;
public word(String name, String type) {
super();
this.name = name;
this.type = type;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
}
This is my Fragment file with the data.
public class Cars extends android.support.v4.app.Fragment implements
AdapterView.OnItemClickListener,
AdapterView.OnItemLongClickListener {
public static final String ARG_PAGE = "ARG_PAGE";
public static Favourites newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
Favourites fragment = new Favourites();
fragment.setArguments(args);
return fragment;
}
Activity activity;
ListView productListView;
List<word> wrds;
wordAdapter wrdAdapter;
SharedPreference sharedPreference;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
sharedPreference = new SharedPreference();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list, container,
false);
findViewsById(view);
setProducts();
wrdAdapter = new wordAdapter(activity, wrds);
productListView.setAdapter(wrdAdapter);
productListView.setOnItemClickListener(this);
productListView.setOnItemLongClickListener(this);
return view;
}
private void setProducts() {
word product1 = new word("Lamborghini Huracan", "Sport");
word product2 = new word("Lamborghini Aventador", "Sport");
word product3 = new word("Jaguar XF", "Luxury Sedan");
word product4 = new word("Audi A4", "Luxury Sedan");
word product5 = new word("Ferrari 488", "Sport");
word product6 = new word("BMW i8", "Hybrid Sport");
word product7 = new word("Audi TT", "Sport");
wrds = new ArrayList<word>();
wrds.add(product1);
wrds.add(product2);
wrds.add(product3);
wrds.add(product4);
wrds.add(product5);
wrds.add(product6);
wrds.add(product7);
}
private void findViewsById(View view) {
productListView = (ListView) view.findViewById(R.id.list_product);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
word product = (word) parent.getItemAtPosition(position);
Toast.makeText(activity, product.toString(), Toast.LENGTH_LONG).show();
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int position, long arg3) {
ImageView button = (ImageView) view.findViewById(R.id.favu);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(activity, wrds.get(position));
button.setTag("red");
button.setImageResource(R.drawable.fav);
} else {
sharedPreference.removeFavorite(activity, wrds.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.unfav);
}
return true;
}
#Override
public void onResume() {
getActivity().setTitle(R.string.app_name);
getActivity().getActionBar().setTitle(R.string.app_name);
super.onResume();
}
}
This is my list view.
<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"
android:background="#EDEDED" >
<ListView
android:id="#+id/list_product"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:dividerHeight="10dp"
android:drawSelectorOnTop="true"
android:footerDividersEnabled="false"
android:padding="10dp"
android:scrollbarStyle="outsideOverlay" >
</ListView>
</RelativeLayout>
This is the items view.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants" >
<RelativeLayout
android:id="#+id/pdt_layout_item"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/carname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="6dp" />
<TextView
android:id="#+id/cartype"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/carname"
android:padding="6dp" />
<ImageView
android:id="#+id/favu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="3dp"
android:background="#null" />
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#id/pdt_layout_item"/>
</RelativeLayout>
I have multiple recyclerViews ,which should appear after another XML view, but they just don't , am using an adapter class to manage this. after using log.v I found that the the functions itself"in Adappter class" arent called , and i don't know why ??
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<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="com.example.linah.movielessonapp.Detailed_Movie">
<TextView
android:id="#+id/MovieTitle"
... />
<ImageView
android:id="#+id/MovieImage"
.../>
<TextView
android:id="#+id/MovieReview"
... />
<Button
android:id="#+id/Favbutton"
... />
<TextView
android:id="#+id/Date"
... />
<TextView
android:id="#+id/Rate"
.../>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/Trailers_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/MovieReview" />
<android.support.v7.widget.RecyclerView
android:id="#+id/reviews_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/Trailers_recycler_view"
/>
</LinearLayout>
</RelativeLayout>
</ScrollView>
public class Detailed_Movie extends AppCompatActivity {
public static List<Movie_Details> movieDetailsList = new ArrayList<>();
private String ID;
public String Trailer_OR_Review = "trailer";
private boolean noConnection;
private boolean trailersDone;
private int trailersSize;
private static MoviesDetailedAdapter mAdapter;
private RecyclerView TrailerRecyclerView, ReviewsRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed__movie);
TrailerRecyclerView = (RecyclerView) findViewById(R.id.Trailers_recycler_view);
ReviewsRecyclerView = (RecyclerView) findViewById(R.id.reviews_recycler_view);
new getData().execute("trailer");
// adapter
mAdapter = new MoviesDetailedAdapter(movieDetailsList,TrailerRecyclerView.getContext(),Trailer_OR_Review);
// mAdapter = new MoviesDetailedAdapter(movieDetailsList,ReviewsRecyclerView.getContext(),Trailer_OR_Review);
TrailerRecyclerView.setLayoutManager(new LinearLayoutManager(TrailerRecyclerView.getContext()));
// ReviewsRecyclerView.setLayoutManager(new LinearLayoutManager(ReviewsRecyclerView.getContext()));
TrailerRecyclerView.setItemAnimator(new DefaultItemAnimator());
// ReviewsRecyclerView.setItemAnimator(new DefaultItemAnimator());
noConnection = false;
if(isOnline(Detailed_Movie.this)) {
new getData().execute("trailer");
mAdapter.notifyDataSetChanged();
}
// set the adapter
TrailerRecyclerView.setAdapter(mAdapter);
prepareMovieData();
Intent i = getIntent();
// http://api.themoviedb.org/3/movie/{id}/videos
String ImgPath = "http://image.tmdb.org/t/p/w185/";
String VideoPath = "http://www.youtube.com/watch?v=";
String MovieTitle = i.getExtras().getString("title");
Toast.makeText(getApplicationContext(),MovieTitle+" is selected!", Toast.LENGTH_SHORT).show();
ImageView img = (ImageView)findViewById(R.id.MovieImage);
TextView Title = (TextView)findViewById(R.id.MovieTitle);
TextView Review = (TextView)findViewById(R.id.MovieReview);
TextView Date = (TextView)findViewById(R.id.Date);
TextView Rate = (TextView)findViewById(R.id.Rate);
Button Fav = (Button) findViewById(R.id.Favbutton);
// get data from intent
assert Title != null;
Title. setText(i.getExtras().getString("title"));
assert Review != null;
Review.setText(i.getExtras().getString("review"));
assert Rate != null;
Rate. setText(i.getExtras().getString("rate"));
assert Date != null;
Date. setText(i.getExtras().getString("date"));
ID = i.getExtras().getString("id");
String Imgurl = i.getExtras().getString("img");
// append ImgPath
switch (ImgPath = new StringBuilder()
.append(ImgPath)
.append(Imgurl)
.toString()) {
}
// append VideoPath
VideoPath = new StringBuilder()
.append(VideoPath)
.append("6uEMl2BtcqQ")
.toString();
// VideoPath = VideoPath + getString(R.string.API_KEY);
final String finalVideoPath = VideoPath;
if (Fav != null) {
Fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(finalVideoPath));
startActivity(intent);
}
});
}
Picasso.with(this)
.load(ImgPath)
.placeholder(R.drawable.loading) //this is optional the image to display while the url image is downloading
.error(R.drawable.error) //this is also optional if some error has occurred in downloading the image
.into(img);
TrailerRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), TrailerRecyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
Movie_Details movie = movieDetailsList.get(position);
if (position < trailersSize) {
// String link = ((TextView) findViewById(R.id.Link)).getText().toString();
// String link = movie.getKey();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=" + movie.getKey())));
}
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
private void prepareMovieData() {
Movie_Details movie = new Movie_Details("MovieTrailer","6uEMl2BtcqQ","Linah","verynice");
movieDetailsList.add(movie);
mAdapter.notifyDataSetChanged();
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private MainActivity.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final MainActivity.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
public RecyclerTouchListener(Context applicationContext, RecyclerView trailerRecyclerView, ClickListener clickListener) {
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public class getData extends AsyncTask<String, Void, Void> {
...
}
}
class MoviesDetailedAdapter
public class MoviesDetailedAdapter extends RecyclerView.Adapter {
private List<Movie_Details> moviesList;
private Context context;
public String Trailer_OR_Review = "trailer";
public TextView TrailerName , Author , Content , TrailerLink ;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
public MyViewHolder(View view) {
super(view);
Log.v("here","MyViewHolder");
TrailerName = (TextView) view.findViewById(R.id.Name);
Author = (TextView) view.findViewById(R.id.Author);
TrailerLink = (TextView) view.findViewById(R.id.Link);
Content = (TextView) view.findViewById(R.id.Content);
view.setOnCreateContextMenuListener(this);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
}
}
public MoviesDetailedAdapter(List<Movie_Details> moviesList,Context context, String trailerORReview) {
this.moviesList = moviesList;
this.context = context;
Trailer_OR_Review = trailerORReview;
Log.v("here","madapter");
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
Log.v("here","onCreateViewHolder");
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.trailers_layout, parent, false);
/*
if (Trailer_OR_Review.equals("trailers")){
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.trailers_layout, parent, false);
}
else{
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.reviews_layout, parent, false);
}*/
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Log.v("here","onBindViewHolder");
Movie_Details movie_details = moviesList.get(position);
Log.v("here",movie_details.getContent());
Log.v("here",movie_details.getName());
TrailerName.setText(movie_details.getName());
TrailerLink.setText(movie_details.getKey());
/*
if (Trailer_OR_Review.equals("trailers")){
TrailerName.setText(movie_details.getName());
TrailerLink.setText(movie_details.getKey());
}
else{
Author.setText(movie_details.getAuthor());
Content.setText(movie_details.getContent());
}*/
}
I'm learning Android SDK and I need some advices.
I have custom ListView with BaseAdapter and I want to implement some new feature - Favorite Button.
What I want to do is, when I press the Favorite Button, ListItem goes to the beginning of the list, Favorite image change and all that stuff will be saved in the SharedPrefs.
Someone tell me what I need to do, to make it works?
my existing code:
row.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/layout_element_list"
>
<ImageView
android:id="#+id/icon"
android:layout_width="150dp"
android:padding="5dp"
android:layout_height="150dp"
android:layout_marginLeft="4px"
android:layout_marginRight="10px"
android:layout_marginTop="4px"
android:src="#drawable/radio" >
</ImageView>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/label"
android:paddingTop="20dp"
android:layout_gravity="center_vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:textAlignment="center"
android:text="RadioName"
android:textColor="#color/color1"
android:textSize="30dp" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<TextView
android:id="#+id/label2"
android:layout_gravity="center_vertical"
android:layout_width="fill_parent"
android:layout_weight="1"
android:layout_height="fill_parent"
android:textAlignment="center"
android:text="Description.."
android:textColor="#color/color1"
android:textSize="15dp" />
<ImageView
android:id="#+id/favButton"
android:layout_weight="1"
android:layout_width="fill_parent"
android:padding="5dp"
android:layout_height="fill_parent"
android:layout_marginLeft="4px"
android:layout_marginRight="10px"
android:layout_marginTop="4px"
android:src="#drawable/fav_off" >
</ImageView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
BaseAdapter class:
public class RadioAdapter extends BaseAdapter
{
ArrayList<RadioStation> myList = new ArrayList<RadioStation>();
LayoutInflater inflater;
Context context;
public RadioAdapter(Context context, ArrayList<RadioStation> myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public RadioStation getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if(convertView == null) {
convertView = inflater.inflate(R.layout.activity_menu_row, null);
mViewHolder = new MyViewHolder();
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
mViewHolder.tvTitle = detail(convertView, R.id.label, myList.get(position).getTitle());
mViewHolder.tvDesc = detail(convertView, R.id.label2, myList.get(position).getDescription());
mViewHolder.ivIcon = detail(convertView, R.id.icon, myList.get(position).getImgResId());
return convertView;
}
private TextView detail(View v, int resId, String text) {
TextView tv = (TextView) v.findViewById(resId);
tv.setText(text);
return tv;
}
private ImageView detail(View v, int resId, int icon) {
ImageView iv = (ImageView) v.findViewById(resId);
iv.setImageResource(icon); //
return iv;
}
private class MyViewHolder {
TextView tvTitle, tvDesc;
ImageView ivIcon;
}
}
RadioStation class:
public class RadioStation
{
public String title;
public String description;
public int imgResId;
//getters and setters
public static Comparator<RadioStation> comparatorByRadioName = new Comparator<RadioStation>()
{
#Override
public int compare(RadioStation radioStation, RadioStation radioStation2)
{
String name1 = radioStation.getTitle().toLowerCase();
String name2 = radioStation2.getTitle().toLowerCase();
return name1.compareTo(name2);
}
};
}
ActivityListView:
public class ActivityMenuList extends Activity implements AdapterView.OnItemClickListener
{
private ListView lvDetail;
private Context context = ActivityMenuList.this;
private ArrayList <RadioStation> myList = new ArrayList <RadioStation>();
private String[] names = new String[] { "one", "two", "three" };
private String[] descriptions = new String[] { "notset", "notset", "notset"};
private int[] images = new int[] { R.drawable.one, R.drawable.two, R.drawable.three };
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
getWindow().setBackgroundDrawableResource(R.drawable.bg1);
setContentView(R.layout.activity_menu_list);
lvDetail = (ListView) findViewById(R.id.list);
lvDetail.setOnItemClickListener(this);
getDataInList();
lvDetail.setAdapter(new RadioAdapter(context, myList));
}
private void getDataInList() {
for(int i=0;i<3;i++) {
RadioStation ld = new RadioStation();
ld.setTitle(names[i]);
ld.setDescription(descriptions[i]);
ld.setImgResId(images[i]);
myList.add(ld);
}
Collections.sort(myList, RadioStation.comparatorByRadioName);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
String item = names[i];
Intent e = new Intent(ActivityMenuList.this, ActivityRadioStation.class);
Bundle data = new Bundle();
data.putString("radiostation",item);
e.putExtras(data);
startActivity(e);
}
}
That's a lot of changes you have to do. Let's start with the basic.
Add a boolean to your RadioStation for the favorite state.
public boolean isFavorite;
Next on your getView add the favorite button click listener(add its reference to the viewholder too, but let's keep it simple this time)
public class RadioAdapter extends BaseAdapter
{
ArrayList<RadioStation> myList = new ArrayList<RadioStation>();
LayoutInflater inflater;
Context context;
ListView mListview;
public RadioAdapter(Context context, ArrayList<RadioStation> myList, ListView list) {
this.myList = myList;
this.context = context;
mListView = list;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public RadioStation getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if(convertView == null) {
convertView = inflater.inflate(R.layout.activity_menu_row, null);
mViewHolder = new MyViewHolder();
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
mViewHolder.tvTitle = detail(convertView, R.id.label, myList.get(position).getTitle());
mViewHolder.tvDesc = detail(convertView, R.id.label2, myList.get(position).getDescription());
mViewHolder.ivIcon = detail(convertView, R.id.icon, myList.get(position).getImgResId());
convertView.findViewById(R.id.favButton).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
myList.get(position).isFavorite=! myList.get(position).isFavorite;
//reorder mlist
notifyDataSetChanged();
//mListView. smoothscroll here
}
});
((ImageView) convertView.findViewById(R.id.favButton)).setImageResource(myList.get(position).isFavorite?R.drawable.favoriteOn:R.drawable.favoriteOff);
return convertView;
}
private TextView detail(View v, int resId, String text) {
TextView tv = (TextView) v.findViewById(resId);
tv.setText(text);
return tv;
}
private ImageView detail(View v, int resId, int icon) {
ImageView iv = (ImageView) v.findViewById(resId);
iv.setImageResource(icon); //
return iv;
}
private class MyViewHolder {
TextView tvTitle, tvDesc;
ImageView ivIcon;
}
}
I left commented what you should do on the listener. You should be able to continue from here.
When you create your adapter pass the list as the last parameter on the constructor.
Edited: Removed interface. No need to use it here.