Code is for recyclerview I want to implement click operation in child option separately.
how should i implement the given code below this code?
this my project code with adapter,child,parent
adapter.java
package com.blipclap.engineering_solution.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bignerdranch.expandablerecyclerview.Adapter.ExpandableRecyclerAdapter;
import com.bignerdranch.expandablerecyclerview.Model.ParentObject;
import com.blipclap.engineering_solution.Models.TitleChild;
import com.blipclap.engineering_solution.Models.TitleParent;
import com.blipclap.engineering_solution.R;
import com.blipclap.engineering_solution.ViewHolder.TitleChildViewHolder;
import com.blipclap.engineering_solution.ViewHolder.TitleParentViewHolder;
import java.util.List;
public class adapter extends ExpandableRecyclerAdapter<TitleParentViewHolder,TitleChildViewHolder> {
LayoutInflater inflater;
public adapter(Context context, List<ParentObject> parentItemList) {
super(context, parentItemList);
inflater=LayoutInflater.from(context);
}
#Override
public TitleParentViewHolder onCreateParentViewHolder(ViewGroup viewGroup) {
View view=inflater.inflate(R.layout.list_parent,viewGroup,false);
return new TitleParentViewHolder(view);
}
#Override
public TitleChildViewHolder onCreateChildViewHolder(ViewGroup viewGroup) {
View view=inflater.inflate(R.layout.list_child,viewGroup,false);
return new TitleChildViewHolder(view); }
#Override
public void onBindParentViewHolder(TitleParentViewHolder titleParentViewHolder, int i, Object o) {
TitleParent title =(TitleParent)o;
titleParentViewHolder._textview.setText(title.getTitle());
}
#Override
public void onBindChildViewHolder(TitleChildViewHolder titleChildViewHolder, int i, Object o) {
TitleChild title =(TitleChild)o;
titleChildViewHolder.op1.setText(title.getop1());
titleChildViewHolder.op2.setText(title.getop2());
titleChildViewHolder.op3.setText(title.getop3());
titleChildViewHolder.op4.setText(title.getop4());
titleChildViewHolder.op5.setText(title.getop5());
}
}
TitleChild.java
package com.blipclap.engineering_solution.Models;
public class TitleChild {
public String op1;
public String op2;
public String op3;
public String op4;
public String op5;
public TitleChild(String op1, String op2, String op3, String op4,String op5) {
this.op1 = op1;
this.op2 = op2;
this.op3 = op3;
this.op4 = op4;
this.op5 = op5;
}
public String getop1() {return op1;}
public void setop1(String op1) {this.op1 = op1;}
public String getop2() {return op2;}
public void setop2(String op2) {this.op2 = op2;}
public String getop3() {return op3;}
public void setop3(String op3) {this.op3 = op3;}
public String getop4() {return op4;}
public void setop4(String op4) {this.op4 = op4;}
public String getop5() {return op5;}
public void setop5(String op5) {this.op5 = op5;}
}
TitleCreator.java
package com.blipclap.engineering_solution.Models;
import android.content.Context;
import java.util.ArrayList;
import java.util.List;
public class TitleCreator {
static TitleCreator _titleCreator;
List<TitleParent> _titleParents;
public TitleCreator(Context context) {
_titleParents = new ArrayList<>();
for (int i=1;i<=8;i++)
{
TitleParent title = new TitleParent(String.format("SEM%d",i));
_titleParents.add(title);
}
}
public static TitleCreator get(Context context)
{
if (_titleCreator==null)
_titleCreator=new TitleCreator(context);
return _titleCreator;
}
public List<TitleParent> getall() {
return _titleParents;
}
}
**TitleParent.java**
package com.blipclap.engineering_solution.Models;
import com.bignerdranch.expandablerecyclerview.Model.ParentObject;
import java.util.List;
import java.util.UUID;
public class TitleParent implements ParentObject {
private List<Object> mChildrenList;
private UUID _id;
private String title;
public TitleParent(String title) {
this.title = title;
_id=UUID.randomUUID();
}
public UUID get_id() {
return _id;
}
public void set_id(UUID _id) {
this._id = _id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public List<Object> getChildObjectList() {
return mChildrenList;
}
#Override
public void setChildObjectList(List<Object> list) {
mChildrenList=list;
}
}
TitleChildViewHolder.java
package com.blipclap.engineering_solution.ViewHolder;
import android.view.View;
import android.widget.TextView;
import com.bignerdranch.expandablerecyclerview.ViewHolder.ChildViewHolder;
import com.blipclap.engineering_solution.R;
public class TitleChildViewHolder extends ChildViewHolder {
public TextView op1,op2,op3,op4,op5;
public TitleChildViewHolder(View itemView) {
super(itemView);
op1 =(TextView)itemView.findViewById(R.id.op1);
op2 =(TextView)itemView.findViewById(R.id.op2);
op3 =(TextView)itemView.findViewById(R.id.op3);
op4 =(TextView)itemView.findViewById(R.id.op4);
op5 =(TextView)itemView.findViewById(R.id.op5);
}
}
TitleParentViewHolder.java
package com.blipclap.engineering_solution.ViewHolder;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import com.bignerdranch.expandablerecyclerview.ViewHolder.ParentViewHolder;
import com.blipclap.engineering_solution.R;
public class TitleParentViewHolder extends ParentViewHolder {
public TextView _textview;
public ImageButton _imagebutton;
public TitleParentViewHolder(View itemView) {
super(itemView);
_textview = (TextView)itemView.findViewById(R.id.parentTitle);
_imagebutton =(ImageButton) itemView.findViewById(R.id.expandArrow);
}
}
SYFragment.java
package com.blipclap.engineering_solution;
import android.os.Bundle;
import android.support.annotation.Nullable;
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.bignerdranch.expandablerecyclerview.Model.ParentObject;
import com.blipclap.engineering_solution.Adapter.adapter;
import com.blipclap.engineering_solution.Models.TitleChild;
import com.blipclap.engineering_solution.Models.TitleCreator;
import com.blipclap.engineering_solution.Models.TitleParent;
import java.util.ArrayList;
import java.util.List;
public class SYFragment extends Fragment {
RecyclerView recyclerView;
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
((adapter)recyclerView.getAdapter()).onSaveInstanceState(outState);
}
private List<ParentObject> initData() {
TitleCreator titleCreator =TitleCreator.get(getActivity());
List<TitleParent> titles = titleCreator.getall();
List<ParentObject> parentObjects =new ArrayList<>();
for (TitleParent title:titles)
{
List<Object> childList =new ArrayList<>();
childList.add(new TitleChild("I.T","C.E","EXTC","MECH","CIVIL" ));
title.setChildObjectList(childList);
parentObjects.add(title);
}
return parentObjects;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//returning our layout file
//change R.layout.yourlayoutfilename for each of your fragments
super.onCreate(savedInstanceState);
View rootView =inflater.inflate(R.layout.fragment_sy, container, false);
recyclerView =(RecyclerView)rootView.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter adapter =new adapter(getActivity(),initData());
adapter.setParentClickableViewAnimationDefaultDuration();
adapter.setParentAndIconExpandOnClick(true);
recyclerView.setAdapter(adapter);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("Syllabus");
}
}
list_child.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/op1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="op1" />
<TextView
android:id="#+id/op2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/op1"
android:padding="8dp"
android:text="op2" />
<TextView
android:id="#+id/op3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/op2"
android:padding="8dp"
android:text="op3" />
<TextView
android:id="#+id/op4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/op3"
android:padding="8dp"
android:text="op4" />
<TextView
android:id="#+id/op5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/op4"
android:padding="8dp"
android:text="op5" />
</RelativeLayout>
</android.support.v7.widget.CardView>
**list_parent.xml**
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/parentTitle"
android:padding="16dp"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/expandArrow"
android:visibility="gone"
android:layout_alignParentRight="true"
android:layout_margin="8dp"
android:src="#android:drawable/arrow_down_float"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
fragment_sy.xml
<FrameLayout 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.blipclap.engineering_solution.SYFragment">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerview"></android.support.v7.widget.RecyclerView>
</FrameLayout>
click code
How should i implement this code in my project it should be like whenever i click clid option specific pdf should open
Anyone can help with this.
whenever i add this i end up with errors.
#Override
public void onBindChildViewHolder(IssueViewHolder issueViewHolder, int position, Object childListItem) {
Issue issue = (Issue) childListItem;
issueViewHolder.bind(issue);
issueViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//your code
}
});
}
Define interface in your adapter class
public interface onItemClickListener {
void onItemClicked(View view, int position);
}
public void setOnItemClickListener(onItemClickListener listener) {
this.onItemClickListener = listener;
}
On your Custom View Holder Implement View.OnClickListner and set Click Listener for required view.
public static class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CustomViewHolder(View itemView){
super(itemView);
yourview.setOnClickListener(this);
}
#Override
public void onClick(View view) {
onItemClickListener.onItemClicked(view, getAdapterPosition());
}
}
Now in the Adapter object just add setOnItemClickListener and you can bifurcate click event using the id of the view.
yourAdapter.setOnItemClickListener(new YourAdapter.onItemClickListener() {
#Override
public void onItemClicked(View view, int position) {
// view.getId()
});
Related
I am working on a chat functionality to implement in my app. The purpose is that when a message comes from another user, the message item will align parent's start and when the user sends a message, it will align to the end. The send button on upper left corner simulates the other user sending a message. The problem is that when items recycles, some of them mathes the width of parent layout. I do not really understand why this happens and how to fix it. Thanks in advance...
package com.example.messageapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.content.Context;
import android.database.Observable;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button sendBtn;
Button otherSendBtn;
EditText editText;
RecyclerView recyclerView;
MessagesAdapter adapter;
List<ChatMessage> messageList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageList=new ArrayList<>();
sendBtn=findViewById(R.id.sendBtn);
otherSendBtn=findViewById(R.id.otherSendBtn);
editText=findViewById(R.id.editText);
recyclerView=findViewById(R.id.recyclerView);
adapter=new MessagesAdapter(this,messageList);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
for(int i=0; i<4; i++){
if(i%2==0){
messageList.add(new ChatMessage("from him","self"));
}else{
messageList.add(new ChatMessage("from me","other"));
}
adapter.notifyItemInserted(messageList.size()-1);
}
otherSendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
messageList.add(new ChatMessage("random","other"));
adapter.notifyItemInserted(messageList.size()-1);
}
});
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String txt=editText.getText().toString();
messageList.add(new ChatMessage(txt, "self"));
adapter.notifyItemInserted(messageList.size()-1);
editText.setText("");
hideKeyboardFrom(MainActivity.this, view);
}
});
}
public static void hideKeyboardFrom(Context context, View view) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
model class for messages
package com.example.messageapp;
public class ChatMessage {
public String text;
public String user;
public ChatMessage(String text, String user) {
this.text = text;
this.user = user;
}
}
recycler view adapter
package com.example.messageapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MessagesAdapter extends RecyclerView.Adapter {
Context context;
List<ChatMessage> messages;
public void setMessages(List<ChatMessage> messages) {
this.messages = messages;
}
public MessagesAdapter(Context context, List<ChatMessage> messages) {
this.context = context;
this.messages = messages;
}
private static class MessageViewHolder extends RecyclerView.ViewHolder{
TextView textView;
RelativeLayout relativeLayout;
public MessageViewHolder(#NonNull View itemView) {
super(itemView);
textView=itemView.findViewById(R.id.messageTextView);
relativeLayout=itemView.findViewById(R.id.item_parent);
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v= LayoutInflater.from(context).inflate(R.layout.message_item,parent,false);
return new MessageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
ChatMessage message=messages.get(position);
((MessageViewHolder) holder).textView.setText(message.text);
RelativeLayout.LayoutParams params= (RelativeLayout.LayoutParams) ((MessageViewHolder) holder).relativeLayout.getLayoutParams();
if(message.user.equals("self")){
params.addRule(RelativeLayout.ALIGN_PARENT_END);
((MessageViewHolder) holder).relativeLayout.setBackgroundColor(context.getResources().getColor(R.color.teal_200));
}else{
params.addRule(RelativeLayout.ALIGN_PARENT_START);
((MessageViewHolder) holder).relativeLayout.setBackgroundColor(context.getResources().getColor(R.color.purple_200));
}
((MessageViewHolder) holder).relativeLayout.setLayoutParams(params);
}
#Override
public int getItemCount() {
return messages.size();
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="10dp">
<RelativeLayout
android:id="#+id/item_parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/teal_700">
<TextView
android:padding="10dp"
android:id="#+id/messageTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
</RelativeLayout>
<?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=".MainActivity">
<Button
android:id="#+id/otherSendBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="send"
android:layout_centerHorizontal="true"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/otherSendBtn"
tools:listitem="#layout/message_item"/>
<RelativeLayout
android:id="#+id/linear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toStartOf="#+id/sendBtn"
android:layout_marginEnd="5dp"/>
<Button
android:background="#drawable/ic_baseline_send_24"
android:id="#+id/sendBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
</RelativeLayout>
activity_main.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rView"
android:layout_width="409dp"
android:layout_height="729dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
2.activity_frame.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 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="500dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView"
android:layout_width="411dp"
android:layout_height="360dp"
android:scaleType="centerCrop"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:srcCompat="#tools:sample/avatars"
android:contentDescription="#string/todo" />
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/textview1"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView"
app:layout_constraintVertical_bias="0.173" />
<TextView
android:id="#+id/textView2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/textview2"
android:maxLines="1"
android:ellipsize="end"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/textView1"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView1" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
HDNews.java
package com.example.android.hdnews;
public class HDNews {
private String title;
private String author;
private String image;
public HDNews(String title, String author, String image) {
this.title = title;
this.author = author;
this.image = image;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getImage() {
return image;
}
}
MainActivity.java
package com.example.android.hdnews;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.widget.LinearLayout;
import com.android.volley.NetworkResponse;
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.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ArrayList al;
private HDNewsAdapter hdNewsAdapter;
private RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView=findViewById(R.id.rView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
al=new ArrayList<HDNews>();
requestQueue= Volley.newRequestQueue(this);
extractingDataFromInternet();
}
//http://newsapi.org/v2/top-headlines?country=in&apiKey=94bf8bcc374b494485309e325e3656f9
public void extractingDataFromInternet(){
String url="http://newsapi.org/v2/top-headlines?country=in&category=business&apiKey=94bf8bcc374b494485309e325e3656f9";
JsonObjectRequest JsonObjReq=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("articles");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject ca = jsonArray.getJSONObject(i);
String authorNames = ca.optString("author");
String titleNames = ca.optString("title");
String imageUrls = ca.getString("urlToImage");
al.add(new HDNews(titleNames, authorNames, imageUrls));
}
hdNewsAdapter = new HDNewsAdapter(MainActivity.this, al);
recyclerView.setAdapter(hdNewsAdapter);
} catch ( JSONException e ) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(JsonObjReq);
}
}
HDNewsAdapter
package com.example.android.hdnews;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class HDNewsAdapter extends RecyclerView.Adapter<HDNewsAdapter.ViewHolder>{
private Context context;
private ArrayList<HDNews> al;
public HDNewsAdapter(Context context, ArrayList<HDNews> al) {
this.context = context;
this.al = al;
}
#NonNull
#Override
public HDNewsAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View views= LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_frame,parent,false);
return new ViewHolder(views);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
HDNews currentposition=al.get(position);
String imgurl=currentposition.getImage();
String athName=currentposition.getAuthor();
String ttleName=currentposition.getTitle();
holder.titleName01.setText(ttleName);
holder.authorName01.setText(athName);
Glide.with(context).load(imgurl).into(holder.imageurl01);
}
#Override
public int getItemCount() {
return al.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView authorName01;
public TextView titleName01;
public ImageView imageurl01;
public ViewHolder(#NonNull View itemView) {
super(itemView);
authorName01=itemView.findViewById(R.id.textView1);
titleName01=itemView.findViewById(R.id.textView2);
imageurl01=itemView.findViewById(R.id.imageView);
}
#Override
public void onClick(View view) {
}
}
}
On Android, I want to users to be able to select multiple rows from a list. I read that I can use SelectionTracker with a RecyclerView to enable list-item selection.
But all the code examples are in Kotlin. Are there any examples of SelectionTracker in Java?
Here is a settings menu that allows the user to choose multiple settings. To begin the selection, the user has to long press any setting. Then they can tap any setting to choose more.
Activity
package com.locuslabs.android.sdk;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.selection.ItemDetailsLookup;
import androidx.recyclerview.selection.Selection;
import androidx.recyclerview.selection.SelectionPredicates;
import androidx.recyclerview.selection.SelectionTracker;
import androidx.recyclerview.selection.StableIdKeyProvider;
import androidx.recyclerview.selection.StorageStrategy;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import com.locuslabs.android.sdk.api.ConfigurationExperiments;
import com.locuslabs.android.sdk.api.MapExperiments;
import com.locuslabs.android.sdk.api.MapViewExperiments;
import com.locuslabs.android.sdk.api.PositionExperiments;
import com.locuslabs.android.sdk.api.VenueExperiments;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
public class SettingsActivity extends Activity {
private static final String TAG = "SettingsActivity";
SelectionTracker<Long> selectedSettingTracker;
private RecyclerView settingsRecyclerView;
private List<String> listOfUsableApis;
private ApiSettings mApiSettings;
private void setApiSettings(List<String> settingNamesSelected) {
for (String settingName : settingNamesSelected) {
if (settingName.equals(getResources().getString(R.string.api_setting_draw_line)))
mApiSettings.mDrawLine = true;
if (settingName.equals(getResources().getString(R.string.api_setting_search)))
mApiSettings.mLogSearch = true;
/* omitted rest of options for brevity */
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mApiSettings = new ApiSettings();
setContentView(R.layout.activity_settings);
settingsRecyclerView = findViewById(R.id.settingsRecyclerView);
settingsRecyclerView.setLayoutManager(new LinearLayoutManager(this));
Button backButton = findViewById(R.id.settings_back_button);
Button saveButton = findViewById(R.id.settings_apply_button);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setApiSettings(getSettingNamesSelected());
Intent intent = new Intent();
intent.putExtra("apiSettings", new Gson().toJson(mApiSettings));
setResult(RESULT_OK, intent);
finish();
}
});
listOfUsableApis = /* omitted for brevity */
final SettingsAdapter settingsAdapter = new SettingsAdapter();
settingsRecyclerView.setAdapter(settingsAdapter);
// Handle selection of settings
selectedSettingTracker = new SelectionTracker.Builder<Long>(
"selectedSettingTrackerId",
settingsRecyclerView,
new StableIdKeyProvider(settingsRecyclerView),
new SettingsDetailsLookup(),
StorageStrategy.createLongStorage()
).
withSelectionPredicate(SelectionPredicates.<Long>createSelectAnything()).
build();
}
private List<String> getSettingNamesSelected() {
Selection<Long> settingsSelection = selectedSettingTracker.getSelection();
Iterator<Long> settingSelectionIterator = settingsSelection.iterator();
List<String> settingNamesSelected = new ArrayList<>();
while (settingSelectionIterator.hasNext()) {
Long settingSelectionId = settingSelectionIterator.next();
String settingNameSelected = listOfUsableApis.get(settingSelectionId.intValue());
settingNamesSelected.add(settingNameSelected);
}
return settingNamesSelected;
}
public static class ApiSettings {
public boolean mDrawLine = false;
public boolean mWalkSimulator = false;
/* omitted most options for brevity */
public ApiSettings() {
}
}
private class SettingsAdapter extends RecyclerView.Adapter<SettingsAdapter.SettingViewHolder> {
public SettingsAdapter() {
setHasStableIds(true);
}
#NonNull
#Override
public SettingViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
TextView textView = (TextView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.setting_list_item, parent, false);
SettingViewHolder settingViewHolder = new SettingViewHolder(textView);
return settingViewHolder;
}
#Override
public void onBindViewHolder(#NonNull SettingViewHolder holder, final int position) {
holder.textView.setText(listOfUsableApis.get(position));
holder.textView.setActivated(selectedSettingTracker.isSelected((long) position));
holder.position = position;
}
#Override
public int getItemCount() {
return listOfUsableApis.size();
}
#Override
public long getItemId(int position) {
return Long.valueOf(position);
}
public class SettingViewHolder extends RecyclerView.ViewHolder {
public int position;
public TextView textView;
public SettingViewHolder(TextView v) {
super(v);
textView = v;
}
}
}
private class SettingsDetailsLookup extends ItemDetailsLookup<Long> {
#Nullable
#Override
public ItemDetails<Long> getItemDetails(#NonNull MotionEvent event) {
View view = settingsRecyclerView.findChildViewUnder(event.getX(), event.getY());
if (view != null) {
final RecyclerView.ViewHolder viewHolder = settingsRecyclerView.getChildViewHolder(view);
if (viewHolder instanceof SettingsAdapter.SettingViewHolder) {
final SettingsAdapter.SettingViewHolder settingViewHolder = (SettingsAdapter.SettingViewHolder) viewHolder;
return new ItemDetailsLookup.ItemDetails<Long>() {
#Override
public int getPosition() {
return viewHolder.getAdapterPosition();
}
#Nullable
#Override
public Long getSelectionKey() {
return Long.valueOf(settingViewHolder.position);
}
};
}
}
return null;
}
}
}
Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:baselineAligned="false"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#454545"
android:weightSum="100">
<Button
android:id="#+id/settings_back_button"
android:background="#454545"
android:drawableStart="#drawable/arrow_white"
android:drawableLeft="#drawable/arrow_white"
android:layout_gravity="start"
android:layout_width="#dimen/ll_mdu_10"
android:layout_height="#dimen/ll_mdu_10"
android:layout_weight="5"/>
<Space
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="90"
/>
<Button
android:id="#+id/settings_apply_button"
android:background="#454545"
android:drawableStart="#android:drawable/ic_menu_save"
android:drawableLeft="#android:drawable/ic_menu_save"
android:layout_gravity="end"
android:layout_width="#dimen/ll_mdu_10"
android:layout_height="#dimen/ll_mdu_10"
android:layout_weight="5"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingBottom="#dimen/activity_vertical_margin">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Long-press for first setting, then tap other settings for multiple selection"
app:layout_constraintBottom_toTopOf="#+id/settingsRecyclerView"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/settingsRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
</LinearLayout>
</LinearLayout>
Layout setting_list_item.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/setting_list_item_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/setting_background"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:textAppearance="?android:attr/textAppearanceListItemSmall" />
Background drawable setting_background.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#android:color/holo_green_dark" android:state_activated="true" />
<item android:drawable="#android:color/white" />
</selector>
References:
https://developer.android.com/guide/topics/ui/layout/recyclerview#select This documentation is hard to read. It needs an example.
https://proandroiddev.com/a-guide-to-recyclerview-selection-3ed9f2381504 Hard to read Kotlin example
https://www.youtube.com/watch?v=jdKUm8tGogw&feature=youtu.be&list=PLWz5rJ2EKKc9Gq6FEnSXClhYkWAStbwlC&t=980 Google IO intro to this feature (but in Kotlin)
https://medium.com/#Dalvin/android-recycler-view-with-multiple-item-selections-b2af90eb5825 Another Java example!
I try to lunch a recyclerview of external database. so i prepared mydatabase.db.zip and putt it into assets/database folder.after writing codes i found an error NullPointerException.i dont know where the problem is. please help
Data model:
package com.example.myapplication.DataModel;
public class Name {
public int id;
public String name;
public String meaning;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMeaning() {
return meaning;
}
public void setMeaning(String meaning) {
this.meaning = meaning;
}
}
MyDatabase.java
package com.example.myapplication;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class MyDatabase extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "niniaad.db";
private static final int DATABASE_VERSION = 1;
private static final String TBL_NAME="names";
private static final String COL_ID="id";
private static final String COL_NAME="name";
private static final String COL_MEAN="mean";
public MyDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public Cursor getData(){
SQLiteDatabase sqLiteDatabase=this.getReadableDatabase();
Cursor cursor=sqLiteDatabase.rawQuery("SELECT * FROM "+TBL_NAME,null);
return cursor;
}
}
SecondRecycler.java
package com.example.myapplication;
import android.database.Cursor;
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.RelativeLayout;
import com.example.myapplication.Adapter.NameAdapter;
import com.example.myapplication.Adapter.StudentAdapter;
import com.example.myapplication.DataModel.Name;
import com.example.myapplication.DataModel.Students;
import java.util.ArrayList;
import java.util.List;
public class SecondRecycler extends AppCompatActivity {
RecyclerView recyclerView;
List<Name> nameList;
MyDatabase myDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second_recycler);
setupviews();
getDataFromSqlite();
}
private void getDataFromSqlite() {
Cursor cursor= myDatabase.getData();
for (cursor.moveToFirst(); !cursor.isAfterLast() ; cursor.moveToNext()) {
Name name=new Name();
name.setName(cursor.getString(0));
name.setMeaning(cursor.getString(1));
nameList.add(name);
}
recyclerView.setAdapter(new NameAdapter(SecondRecycler.this,nameList));
}
private void setupviews() {
MyDatabase myDatabase=new MyDatabase(this);
recyclerView = (RecyclerView) findViewById(R.id.rv_secondrecycler);
recyclerView.setLayoutManager(new LinearLayoutManager(SecondRecycler.this));
}
}
Adapter
package com.example.myapplication.Adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.myapplication.DataModel.Name;
import com.example.myapplication.R;
import java.util.List;
public class NameAdapter extends RecyclerView.Adapter<NameAdapter.NameViewHolder> {
public Context context;
public List<Name> nameList;
public NameAdapter(Context context, List<Name> nameList) {
this.context = context;
this.nameList = nameList;
}
#NonNull
#Override
public NameViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.secondrecycler_row, viewGroup, false);
return new NameViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull NameViewHolder nameViewHolder, int position) {
Name name = nameList.get(position);
nameViewHolder.txtName.setText(name.getName());
nameViewHolder.txtMean.setText(name.getMeaning());
}
#Override
public int getItemCount() {
return nameList.size();
}
public class NameViewHolder extends RecyclerView.ViewHolder {
TextView txtName, txtMean;
public NameViewHolder(#NonNull View itemView) {
super(itemView);
txtName = (TextView) itemView.findViewById(R.id.txt_name_Secondrecycler);
txtMean = (TextView) itemView.findViewById(R.id.txt_mean_seconrecycler);
}
}
}
activity_second_recycler.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=".SecondRecycler">
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_secondrecycler"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
recycler_row.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
tools:context=".SecondRecycler">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/txt_name_Secondrecycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:textColor="#000"
tools:text="name"
android:textAlignment="center"
/>
<TextView
android:layout_below="#id/txt_name_Secondrecycler"
android:id="#+id/txt_mean_seconrecycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:textColor="#FF0000"
tools:text="mean"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
I am trying to make my first app using android studio. On the main activity I am trying to create a menu in the style of a grid using the RecyclerView. I want each menu option to have a title, description and a image.
Currently there are only 3 options on the menu whilst I'm testing. When I debug my app it kinda works but not as I expected. In that when it loads it shows the titles of the 3 options in my arrayList but not the descriptions or the images. I have checked that the description and image fields are correctly populated in my arrayList. I am not sure why it is only showing the titles? Below is my code.
code - XML
activity_main
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mark.spanishapp.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/esp_menu"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.constraint.ConstraintLayout>
menu_layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#FFFFFF"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/title"
android:textStyle="bold"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/menuImg"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
code - Java
MainActivity
package com.example.mark.spanishapp;
import android.database.sqlite.SQLiteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private final static String TAG = "MainActivity";
DBHandler dbHandler = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHandler = new DBHandler(this);
try {
dbHandler.createDataBase();
}catch (IOException ioe){
throw new Error("unable to create database");
}
try{
dbHandler.openDataBase();
}catch (SQLException sqle)
{
Log.e(TAG, sqle.getMessage());
}
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.esp_menu);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 2);
recyclerView.setLayoutManager(layoutManager);
ArrayList<MenuEsp> menuList = dbHandler.Get_MenuList();
MyAdapter adapter = new MyAdapter(getApplicationContext(), menuList);
recyclerView.setAdapter(adapter);
}
}
MenuEsp
package com.example.mark.spanishapp;
public class MenuEsp {
public String getMenu() {
return menu;
}
public void setMenu(String menu) {
this.menu = menu;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
this.imageName = imageName;
}
private String menu;
private String description;
private String imageName;
}
MyAdapter
package com.example.mark.spanishapp;
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 java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<MenuEsp> menuList;
private Context context;
public MyAdapter(Context context, ArrayList<MenuEsp> menuList){
this.context = context;
this.menuList = menuList;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.menu_layout, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
holder.title.setText(menuList.get(position).getMenu());
holder.img.setScaleType(ImageView.ScaleType.CENTER_CROP);
int id = this.context.getResources().getIdentifier(menuList.get(position).getImageName(), "drawable", this.context.getPackageName());
holder.img.setImageResource(id);
}
#Override
public int getItemCount() {
return menuList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView title;
private TextView descirption;
private ImageView img;
public ViewHolder(View view) {
super(view);
descirption = (TextView)view.findViewById(R.id.description);
title = (TextView)view.findViewById(R.id.title);
img = (ImageView) view.findViewById(R.id.menuImg);
}
}
}
Set value of description in onBindViewholder
ie
holder.descirption.setText(menuList.get(position).getDescription());
next,
change code from
int id = this.context.getResources().getIdentifier(menuList.get(position).getImageName(), "drawable", this.context.getPackageName());
holder.img.setImageResource(id);
To
holder.img.setImageResource(Integer.parseInt(menuList.get(position).getImageName()));
make changes to your onBindViewHolder() method in your Adapter class
int id = this.context.getResources().getIdentifier(menuList.get(position).getImageName(), "drawable", this.context.getPackageName());
holder.img.setImageResource(id);
holder.descirption.setText(menuList.get(position).getDescription());