How to implement SelectionTracker in Java not Kotlin - java

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!

Related

size of recycler view item changes when user scrolls down and up

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>

Android Studio Grid View doesn't show when I run the app

I created a Java class that should display something like this:
But this is what I get when I run the app:
It doesn't show what I wanted and Android Studio doesn't show any error in Logcat, so I don't know why it's not working.
This is the code for the class SetsActivity:
package com.example.myquiz;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.GridView;
import android.widget.Toolbar;
public class SetsActivity extends AppCompatActivity {
private GridView sets_grid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sets);
androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.set_toolbar);
//setSupportActionBar(toolbar);
String title = getIntent().getStringExtra("CATEGORY");
getSupportActionBar().setTitle(title);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
sets_grid = findViewById(R.id.sets_gridview);
SetsAdapter adapter = new SetsAdapter(2);
sets_grid.setAdapter(adapter);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home)
{
SetsActivity.this.finish();
}
return super.onOptionsItemSelected(item);
}
}
I also created an adapter class SetsAdapter so I'm gonna post the code for it as well:
package com.example.myquiz;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class SetsAdapter extends BaseAdapter {
private int numOfSets;
public SetsAdapter(int numOfSets) {
this.numOfSets = numOfSets;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.set_item_layout, parent, false);
} else {
view = convertView;
}
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(parent.getContext(),QuestionActivity.class);
parent.getContext().startActivity(intent);
}
});
((TextView) view.findViewById(R.id.setNo_tv)).setText(String.valueOf(position + 1));
return view;
}
}
And here is the code for the XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SetsActivity"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="#+id/set_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
></androidx.appcompat.widget.Toolbar>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sets"
android:textSize="26sp"
android:textStyle="bold"
android:padding="16dp" />
<GridView
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="#+id/sets_gridview"
android:layout_weight="1"
android:gravity="center"
android:horizontalSpacing="16dp"
android:verticalSpacing="16dp"
android:padding="16dp"
android:columnWidth="100dp"
android:numColumns="auto_fit"
></GridView>
</LinearLayout>
Here is the code for the XML file set_item_layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="100dp"
android:orientation="vertical"
android:gravity="center"
android:background="#drawable/round_corner"
android:backgroundTint="#FFC3C3"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:id="#+id/setNo_tv"
android:textStyle="bold"
android:textColor="#android:color/black"
android:textSize="45sp"></TextView>
</LinearLayout>
The getCount() method in the SetsAdapter should return numOfSets not 0.
#Override
public int getCount() {
return numOfSets;
}

in RecyclerView i want onclicklistner operation

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()
});

Viewpager in Dialog?

I'm trying to have a dialog where you can click a "next" button to swipe right to the next screen. I am doing that with a ViewPager and adapter:
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.voicedialog);
dialog.setCanceledOnTouchOutside(false);
MyPageAdapter adapter = new MyPageAdapter();
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(adapter);
However, I get a NullPointerException saying that pager is null. Why is this happening? Here is the Page Adapter class:
public class MyPageAdapter extends PagerAdapter {
public Object instantiateItem(ViewGroup collection, int position) {
int resId = 0;
switch (position) {
case 0:
resId = R.id.voice1;
break;
case 1:
resId = R.id.voice2;
break;
}
return collection.findViewById(resId);
}
#Override
public int getCount() {
return 2;
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
}
Here's my layout for the DIALOG:
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Let me know on how to avoid this situation.
PS: Each of the layouts that should be in the view pager look like this, just diff. text:
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/voice2"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:text="Slide 1!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView2"
android:layout_gravity="center"
android:textSize="50sp" />
</RelativeLayout>
Without Using Enum Class
You should call findViewById on dialog. so for that you have to add dialog before findViewById..
Like this,
ViewPager pager = (ViewPager) dialog.findViewById(R.id.viewpager);
After solving your null pointer exception the other problem's solution here, if you wont use enum class you can use below code...
MainActivity.java
package demo.com.pager;
import android.app.Dialog;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn= (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.voicedialog);
dialog.setCanceledOnTouchOutside(false);
MyPageAdapter adapter = new MyPageAdapter(MainActivity.this);
ViewPager pager = (ViewPager) dialog.findViewById(R.id.viewpager);
pager.setAdapter(adapter);
dialog.show();
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="demo.com.pager.MainActivity">
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
MyPageAdapter.java
package demo.com.pager;
import android.app.FragmentManager;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by rucha on 26/12/16.
*/
public class MyPageAdapter extends PagerAdapter {
Context mContext;
int resId = 0;
public MyPageAdapter(Context context) {
mContext = context;
}
public Object instantiateItem(ViewGroup collection, int position) {
/* int resId = 0;
switch (position) {
case 0:
resId = R.id.voice1;
break;
case 1:
resId = R.id.voice2;
break;
}
return collection.findViewById(resId);*/
LayoutInflater inflater = LayoutInflater.from(mContext);
switch (position) {
case 0:
resId = R.layout.fragment_blue;
break;
case 1:
resId = R.layout.fragment_pink;
break;
}
ViewGroup layout = (ViewGroup) inflater.inflate(resId, collection, false);
collection.addView(layout);
return layout;
}
#Override
public int getCount() {
return 2;
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
}
FragmentBlue.java
package demo.com.pager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import android.support.v4.app.Fragment;
public class FragmentBlue extends Fragment {
private static final String TAG = FragmentBlue.class.getSimpleName();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blue, container, false);
return view;
}
}
fragment_blue.xml
<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="#4ECDC4">
</RelativeLayout>
voicedialog.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Please check and reply.
Using Enum Class
Try this code, This is working if any doubt ask again. Happy to help.
MainActivity.java
package demo.com.dialogdemo;
import android.app.Dialog; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.Window; import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupUIComponents();
setupListeners();
}
private void setupUIComponents() {
button = (Button) findViewById(R.id.button);
}
private void setupListeners() {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialogItemDetails = new Dialog(MainActivity.this);
dialogItemDetails.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialogItemDetails.setContentView(R.layout.dialoglayout);
dialogItemDetails.getWindow().setBackgroundDrawable(
new ColorDrawable(Color.TRANSPARENT));
ViewPager viewPager = (ViewPager) dialogItemDetails.findViewById(R.id.viewPagerItemImages);
viewPager.setAdapter(new CustomPagerAdapter(MainActivity.this));
dialogItemDetails.show();
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dialog" />
</RelativeLayout>
ModelObject1.java
public enum ModelObject1 {
RED(R.string.red, R.layout.fragment_one),
BLUE(R.string.blue, R.layout.fragment_two);
private int mTitleResId;
private int mLayoutResId;
ModelObject1(int titleResId, int layoutResId) {
mTitleResId = titleResId;
mLayoutResId = layoutResId;
}
public int getTitleResId() {
return mTitleResId;
}
public int getLayoutResId() {
return mLayoutResId;
}
}
CustomPagerAdapter.java
package demo.com.dialogdemo;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by rucha on 26/12/16.
*/
public class CustomPagerAdapter extends PagerAdapter {
private Context mContext;
public CustomPagerAdapter(Context context) {
mContext = context;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
ModelObject1 modelObject = ModelObject1.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(modelObject.getLayoutResId(), collection, false);
collection.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return ModelObject1.values().length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
ModelObject1 customPagerEnum = ModelObject1.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}
}
dailoglayout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/txtHeaderTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:text="ITEM IMAGES"
android:textStyle="bold" />
<android.support.v4.view.ViewPager
android:id="#+id/viewPagerItemImages"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white" />
</RelativeLayout>
fragmentone.xml
<?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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="one"/>
</LinearLayout>

RecyclerView with CardView does not work

I am really sorry for such an abstract question but I am loosing my mind here. HERE is my code for RecyclerView activity.
Please tell me what am I missing, because I am new to Android and I've tried for 4 days to figure the CardView out.
The error is
02-26 13:17:36.570 1138-1138/com.parse.starter E/CrashReporting﹕ ParseCrashReporting caught a NullPointerException exception for com.parse.starter. Building report.
02-26 13:17:36.580 1138-1138/com.parse.starter E/CrashReporting﹕ Handling exception for crash
java.lang.NullPointerException
at com.misha.adaptor.ContactAdapter.onBindViewHolder(ContactAdapter.java:31)
at com.misha.adaptor.ContactAdapter.onBindViewHolder(ContactAdapter.java:14)
The main Activity class
package com.parse.starter;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.misha.adaptor.ContactAdapter;
import com.misha.to.ContactInfo;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import java.util.ArrayList;
import java.util.List;
public class CardActivity extends Activity {
String column;
TextView name;
String result;
List<ContactInfo> resultContacts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card);
// getContacts()
List<ContactInfo> list = new ArrayList<>();
ContactInfo ci = new ContactInfo();
ci.name = "Mihail";
ci.gender = "male";
ci.email = "test#gmail.com";
ci.phone = "4152346153";
list.add(ci);
RecyclerView recList = (RecyclerView) findViewById(R.id.cardList);
recList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recList.setLayoutManager(llm);
ContactAdapter adapter = new ContactAdapter(list);
recList.setAdapter(adapter);
// name = (TextView) findViewById(R.id.txtName);
// getMessage("fevK9QPFUW", "Message");
}
public void getMessage(String key, String columnName) {
this.column = columnName;
ParseQuery<ParseObject> query = ParseQuery.getQuery("Messages");
query.getInBackground(key, new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
name.setText(object.getString(column).toString());
} else {
result = "did not work";
}
}
});
}
public List<ContactInfo> getContacts() {
resultContacts = new ArrayList<>();
ParseQuery<ParseObject> contacts = ParseQuery.getQuery("Messages");
List<ParseQuery<ParseObject>> queries = new ArrayList<>();
queries.add(contacts);
ParseQuery<ParseObject> mainQuery = ParseQuery.or(queries);
mainQuery.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> results, ParseException e) {
if (e == null) {
for (ParseObject obj : results) {
String s = obj.getString("Message");
ContactInfo ci = new ContactInfo();
ci.name = s;
ci.email = "email";
ci.phone = "phone";
ci.gender = "gender";
resultContacts.add(ci);
}
}
}
});
return resultContacts;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_card, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
The Adaptor
package com.misha.adaptor;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.misha.to.ContactInfo;
import com.parse.starter.R;
import java.util.List;
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactViewHolder> {
private List<ContactInfo> contactList;
public ContactAdapter(List<ContactInfo> contactList) {
this.contactList = contactList;
}
#Override
public int getItemCount() {
return contactList.size();
}
#Override
public void onBindViewHolder(ContactViewHolder contactViewHolder, int i) {
ContactInfo ci = contactList.get(i);
System.out.println("The ContactInfo = " + ci);
contactViewHolder.vName.setText(ci.name);
contactViewHolder.vPhone.setText(ci.phone);
contactViewHolder.vEmail.setText(ci.email);
contactViewHolder.vGender.setText(ci.gender);
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.activity_card, viewGroup, false);
return new ContactViewHolder(itemView);
}
public class ContactViewHolder extends RecyclerView.ViewHolder {
protected TextView vName;
protected TextView vPhone;
protected TextView vEmail;
protected TextView vGender;
public ContactViewHolder(View v) {
super(v);
vName = (TextView) v.findViewById(R.id.txtName);
vPhone = (TextView) v.findViewById(R.id.txtPhone);
vEmail = (TextView) v.findViewById(R.id.txtEmail);
vGender = (TextView) v.findViewById(R.id.txtGender);
}
}
}
and Here are my layOuts:
activity_card.xml
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".CardActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/cardList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
card_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
card_view:cardCornerRadius="4dp"
android:layout_margin="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtName"
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="#color/bkg_card"
android:text="Name"
android:gravity="center_vertical"
android:textColor="#android:color/white"
android:textSize="14dp" />
<TextView
android:id="#+id/txtPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone"
android:gravity="center_vertical"
android:textSize="10dp"
android:layout_below="#id/txtName"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp" />
<TextView
android:id="#+id/txtEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:gravity="center_vertical"
android:textSize="10dp"
android:layout_below="#id/txtPhone"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp" />
<TextView
android:id="#+id/txtGender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gender"
android:textSize="10dp"
android:layout_marginTop="10dp"
android:layout_alignParentRight="true"
android:layout_marginRight="150dp"
android:layout_alignBaseline="#id/txtEmail" />
</RelativeLayout>
</android.support.v7.widget.CardView>
contactViewHolder.vName is null in your example.
You need to call the constructor for ContactViewHolder in the ContactAdapter constructor.
Got it
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.card_layout, viewGroup, false);
return new ContactViewHolder(itemView);
}
the R.layout.card_layout was set to R.layout.my_activity

Categories