I have multiple options for a poll and user can select only one option. i am getting options in recycler view with a checkbox and textview.
i want to uncheck previous selected checkbox if user select another checkbox and get selected text by pressing submit button.
here is my recycler view code.
public class Poll_Options_recyclerView_Adapter extends RecyclerView.Adapter<Poll_Options_recyclerView_Adapter.MyViewHolder> {
public List<Poll_Option_Result> result = new ArrayList<>();
Context mycontext;
public Poll_Options_recyclerView_Adapter(List<Poll_Option_Result> result, Context context) {
this.result = result;
this.mycontext = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_option_rec_list, parent, false);
return new MyViewHolder(itemView, mycontext, result);
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView poll_option;
CheckBox checkBox;
List<Poll_Option_Result> result_List = new ArrayList<>();
Context mycontext;
public MyViewHolder(View itemView, Context mycontext, List<Poll_Option_Result> result_List) {
super(itemView);
this.result_List = result_List;
this.mycontext = mycontext;
poll_option = (TextView) itemView.findViewById(R.id.optionA);
checkBox=(CheckBox)itemView.findViewById(R.id.check_box);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
}
}
#Override
public void onBindViewHolder(Poll_Options_recyclerView_Adapter.MyViewHolder holder, int position) {
final Poll_Option_Result ResultList = result.get(position);
holder.poll_option.setText(ResultList.getOption());
}
#Override
public int getItemCount() {
return result.size();
}
}
and here is my recycler view custom xml code.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="5"
>
<CheckBox
android:id="#+id/check_box"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"/>
<TextView
android:layout_width="0dp"
android:layout_weight="4.5"
android:layout_height="wrap_content"
android:text="xyz"
android:layout_marginLeft="20dp"
android:textColor="#color/colortoolbartitle"
android:padding="5dp"
android:id="#+id/optionA"/>
private int mCheckedPostion = -1;// no selection by default
Done by adding this code in onBindViewHolder
#Override
public void onBindViewHolder(final Poll_Options_recyclerView_Adapter.MyViewHolder holder, final int position) {
final Poll_Option_Result ResultList = result.get(position);
holder.poll_option.setText(ResultList.getOption());
//check checkbox and uncheck previous selected button
holder.checkBox.setChecked(position == mCheckedPostion);
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (position == mCheckedPostion) {
holder.checkBox.setChecked(false);
StringGen.username = "";
mCheckedPostion = -1;
} else {
mCheckedPostion = position;
StringGen.username = holder.poll_option.getText().toString();
Toast.makeText(mycontext, "select : "+position+holder.poll_option.getText(), Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
}
}
});
}
Related
Hey I'm doing filtering data on my project using bottom Sheet with view-pager and two fragments i can pass data from activity to view-pager adapter and get in fragment through constructor but how can i get data from fragment to activity using bottom-sheet
this is how i send data from activity
adapter = new PagerAdapters(this.getSupportFragmentManager(),
tabLayout.getTabCount(),_id);
and receive data with constructor in fragment
public Filterfragment(String _id) {
this._id = _id;
}
And I'm using recyclerview to show data like this
So how can i send id of the item to activity so i can reload my recyclerview data when the apply button click.
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/bottom_sheet"
android:background="#android:color/white"
app:behavior_peekHeight="0dp"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:tabGravity="fill"
app:tabMode="fixed"
app:tabPadding="0dp"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_below="#id/tabs"
android:layout_above="#id/applyBtn"
android:layout_height="match_parent"
/>
<Button
android:id="#+id/applyBtn"
android:layout_width="match_parent"
android:text="Apply"
android:layout_alignParentBottom="true"
android:layout_height="wrap_content" />
</RelativeLayout>
This is main recyclerview adapter
public class FilterAdapter extends RecyclerView.Adapter<FilterAdapter.FilterViewHolder> {
private static final String TAG = "FilterAdapter";
Context context;
List<TagTypeResult> tagTypeModels;
public static int current_pos = -1;
TagAdapter tagAdapter;
int rotationAngle = 0;
public FilterAdapter(Context context, List<TagTypeResult> tagTypeModels) {
this.context = context;
this.tagTypeModels = tagTypeModels;
}
#NonNull
#Override
public FilterViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.filter_row_item,parent,false);
return new FilterAdapter.FilterViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull FilterViewHolder filterViewHolder, int i) {
TagTypeResult tagTypeModel = tagTypeModels.get(i);
filterViewHolder.txt.setText(tagTypeModel.getName());
filterViewHolder.sub_list_recycler.setVisibility(View.GONE);
if (tagTypeModel.getTagsLists() != null) {
if (tagTypeModel.getTagsLists().size() <= 0) {
filterViewHolder.arrow.setVisibility(View.GONE);
filterViewHolder.arrow.setRotationX(180);
} else {
filterViewHolder.arrow.setVisibility(View.VISIBLE);
filterViewHolder.arrow.setRotationX(0);
}
}else {
filterViewHolder.arrow.setVisibility(View.GONE);
}
tagAdapter = new TagAdapter(context, tagTypeModel.getTagsLists(), new TagInterface() {
#Override
public void tagClick(View view, int pos, String tagID) {
Log.d(TAG, "tagClick: "+tagID);
}
});
filterViewHolder.sub_list_recycler.setAdapter(tagAdapter);
tagAdapter.notifyDataSetChanged();
if (current_pos == filterViewHolder.getAdapterPosition()){
if (filterViewHolder.sub_list_recycler.getVisibility() == View.GONE) {
filterViewHolder.sub_list_recycler.setVisibility(View.VISIBLE);
}else {
filterViewHolder.sub_list_recycler.setVisibility(View.GONE);
}
}else {
Log.i(TAG, "onBindViewHolder: sublist gone "+tagTypeModel.getName());
filterViewHolder.sub_list_recycler.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return tagTypeModels.size();
}
class FilterViewHolder extends RecyclerView.ViewHolder {
TextView txt;
ImageView arrow;
RecyclerView sub_list_recycler;
RelativeLayout linearLayout;
FilterViewHolder(#NonNull View itemView) {
super(itemView);
txt = itemView.findViewById(R.id.txt);
arrow = itemView.findViewById(R.id.arrow);
linearLayout = itemView.findViewById(R.id.main_cat_lay);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "onClick: "+current_pos);
if (current_pos != getAdapterPosition()) {
current_pos = getAdapterPosition();
notifyDataSetChanged();
}
else{
current_pos = -1;
notifyDataSetChanged();
}
}
});
sub_list_recycler = itemView.findViewById(R.id.sub_list_recycler);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(context) {
#Override
public boolean canScrollVertically() {
return false;
}
};
sub_list_recycler.setLayoutManager(mLayoutManager);
sub_list_recycler.addItemDecoration(new SimpleDividerItemDecoration(context));
}
}
}
sub recyclerView adapter :
public class TagAdapter extends RecyclerView.Adapter<TagAdapter.TagViewHolder> {
private static final String TAG = "SublistAdapter";
Context context;
List<TagsList> tagsLists;
int pos = -1;
TagInterface tagInterface;
public TagAdapter(Context context, List<TagsList> tagsLists,TagInterface tagInterface) {
this.context = context;
this.tagsLists = tagsLists;
this.tagInterface = tagInterface;
}
#NonNull
#Override
public TagViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.tag_item,parent,false);
return new TagAdapter.TagViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull TagViewHolder tagViewHolder, int i) {
TagsList tagsList = tagsLists.get(i);
tagViewHolder.tagtxt.setText(tagsList.getName());
if (tagsList.isChecked()){
tagViewHolder.tagName.setChecked(true);
}else {
tagViewHolder.tagName.setChecked(false);
}
}
#Override
public int getItemCount() {
return tagsLists.size();
}
public class TagViewHolder extends RecyclerView.ViewHolder {
TextView tagtxt;
CheckBox tagName;
RelativeLayout childClik;
public TagViewHolder(#NonNull View itemView) {
super(itemView);
//pri_txt = itemView.findViewById(R.id.pri_txt);
tagName = itemView.findViewById(R.id.tagName);
tagtxt = itemView.findViewById(R.id.tagtxt);
childClik = itemView.findViewById(R.id.childClik);
tagName.setEnabled(false);
childClik.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isChecked = true;
if (isChecked)
{
tagsLists.get(getAdapterPosition()).setChecked(true);
tagName.setChecked(true);
tagInterface.tagClick(v,getAdapterPosition(),tagsLists.get(getAdapterPosition()).get_id());
Toast.makeText(context, "[pos]"+tagsLists.get(getAdapterPosition()).get_id(), Toast.LENGTH_SHORT).show();
}else
{
tagsLists.get(getAdapterPosition()).setChecked(false);
tagName.setChecked(false);
}
}
});
}
}
}
I'm using only one SwitchCompat in my RecyclerView adapter. I need position of the clicked item on RecyclerView and it's working fine when I use TextView instead of SwitchCompat. But SwitchCompat have no response and no position returned.
Can anyone help me please? Here's the Adapter file.
public class Setting_Recycler_Adapter extends RecyclerView.Adapter<Setting_Recycler_Adapter.ViewHolder> {
private static final String TAG = "val" ;
private Context mContext;
private ArrayList<Channel_Model> channelsData;
private Setting_Recycler_Adapter.ClickInterface click;
public Setting_Recycler_Adapter(Context mContext, ArrayList<Channel_Model> data,Setting_Recycler_Adapter.ClickInterface clik) {
this.mContext = mContext;
this.channelsData = data;
this.click = clik;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
SwitchCompat mSwitchCompat;
public ViewHolder(View itemView) {
super(itemView);
mSwitchCompat = (SwitchCompat) itemView.findViewById(R.id.setting_channel_switch);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
click.posClicked((short)getAdapterPosition());
}
}
#Override
public Setting_Recycler_Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.setting_recycler, parent, false);
return new Setting_Recycler_Adapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(final Setting_Recycler_Adapter.ViewHolder holder, int position) {
holder.mSwitchCompat.setText(channelsData.get(position).getTitle());
holder.mSwitchCompat.setChecked(channelsData.get(position).isChannel());
}
#Override
public int getItemCount() {
return channelsData.size();
}
interface ClickInterface{void posClicked(short p);
}
And the RecyclerView layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layoutDirection="rtl"
android:textDirection="rtl">
<android.support.v7.widget.SwitchCompat
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/setting_channel_switch"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:text="channel Name"
android:textSize="17sp"/>
</LinearLayout>
You need to set the onSetCheckedChangeListener along with onTouchListener for your SwitchCompat. So the implementation inside your ViewHolder class should look like the following.
public class ViewHolder extends RecyclerView.ViewHolder {
SwitchCompat mSwitchCompat;
Boolean isTouched = false;
public ViewHolder(View itemView) {
super(itemView);
mSwitchCompat = (SwitchCompat) itemView.findViewById(R.id.setting_channel_switch);
mSwitchCompat.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
isTouched = true;
return false;
}
});
mSwitchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isTouched) {
isTouched = false;
if (isChecked) {
click.posClicked((short)getAdapterPosition());
} else {
// Do something on un-checking the SwitchCompat
}
}
}
});
}
}
Hope that helps!
I want to add, for each row in ListView, a checkbox which will be activated and shown on long press, I don't know whether I think correctly, I should add in row layout a Checkbox which is default hidden and when action start all check box on list will be shown and able to check?
To show CheckBox on each row:
1. Add an extra boolean variable isLongPressed to your adapter class and initialized with default false value from adapter constructor.
2. In your adapter getView()/ onBindViewHolder() method add an condition like this:
CheckBox checkBox = (CheckBox) view.findViewById(R.id.check);
if(isLongPressed)
{
checkBox.setVisibility(View.VISIBLE);
} else {
checkBox.setVisibility(View.GONE);
}
3. Add an method showCheckbox() to your adapter class to update ListView with checkbox visible state.
public void showCheckbox()
{
isLongPressed = true;
notifyDataSetChanged(); // Required for update
}
4. Call showCheckbox() from onItemLongClick:
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "Long Click", Toast.LENGTH_SHORT).show();
your_adapter.showCheckbox();
return true;
}
});
Here is good tutorial about Contextual Action Mode
Hope this will help~
Try this:
We will use a recyclerview, and a checkbox adapter
Chechbox Adapter layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="#dimen/checkbox_adapter_item_height"
android:gravity="center_vertical"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal">
<CheckBox
android:id="#+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:theme="#style/MyCheckBoxTheme"
android:clickable="false"
android:longClickable="false"
android:focusable="false"/>
<TextView
android:id="#+id/tvItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="item1"
android:visibility="visible"
android:padding="6dp"
android:paddingStart="12dp"
android:textColor="#color/colorMaterialBlack"
android:textSize="16sp" />
</LinearLayout>
A style for checkbox, keep this in style
<style name="MyCheckBoxTheme" parent="Theme.AppCompat.Light">
<item name="colorControlNormal">#color/colorBlackDimText</item>
<item name="colorControlActivated">#color/greenStatus</item>
</style>
A Model for the Checkbox adapter you can define/add/remove vars in your model
public class CheckboxTitlesData {
private String title;
private boolean isSelected;
public CheckboxTitlesData(String title, boolean isSelected) {
this.title = title;
this.isSelected = isSelected;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
}
Checkbox Adapter
public class CheckboxTitleAdapter extends RecyclerView.Adapter<CheckboxTitleAdapter.ViewHolder> implements GenericAdapterInterface{
List<CheckboxTitlesData> dataList = new ArrayList<>();
private CheckboxTitlesData previousSelection;
protected MyApplication.MenuSelectionListener listener;
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(getRootLayout(), parent, false);
return new ViewHolder(view);
}
public CheckboxTitleAdapter(MyApplication.MenuSelectionListener listener){
this.listener = listener;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
CheckboxTitlesData data = dataList.get(position);
if (data.isSelected()){
previousSelection = data;
holder.checkBox.setChecked(true);
}else holder.checkBox.setChecked(false);
holder.tvItem.setText(data.getTitle());
}
#Override
public int getItemCount() {
return dataList.size();
}
#Override
public void changeData(List dataList) throws IllegalArgumentException{
if (dataList == null || dataList.size() <= 0)
return;
if (!(dataList.get(0) instanceof CheckboxTitlesData))
throw new IllegalArgumentException("Required data type \"CheckboxTitlesData\"");
this.dataList.clear();
this.dataList.addAll(dataList);
(new Handler(Looper.getMainLooper())).postDelayed(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
}, 100);
}
#Override
public int getRootLayout() {
return R.layout.adapter_title_checkbox;
}
#Override
public void setOnClickListener(RecyclerView.ViewHolder holder) {
holder.itemView.setOnLongClickListener((View.OnLongClickListener) holder);
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
#Bind(R.id.tvItem)
TextView tvItem;
#Bind(R.id.checkbox)
CheckBox checkBox;
ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
itemView.setOnClickListener(this);
setOnClickListener(this);
}
#Override
public boolean onLongClick(View v) {
final int pos = dataList.indexOf(previousSelection);
if (pos == getAdapterPosition())
return;
if (listener != null)
listener.onMenuSelected(dataList.get(getAdapterPosition()));
CheckboxTitlesData data = dataList.get(getAdapterPosition());
data.setSelected(true);
dataList.set(getAdapterPosition(), data);
if (pos != -1) {
previousSelection.setSelected(false);
dataList.set(pos, previousSelection);
}
(new Handler(Looper.getMainLooper())).postDelayed(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
}, 100);
return true
}
}
}
Interface, u can remove the interface if you wanted, I just use this for my adapters usually for readability for other dev:
public interface GenericAdapterInterface {
void changeData(List dataList) throws Exception;
int getRootLayout();
void setOnClickListener(RecyclerView.ViewHolder holder);
}
Recycler view layout xml, add the recyclerview whr you need, this is just an eg
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/llBody"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingEnd="#dimen/padding_normal"
android:paddingStart="#dimen/padding_normal">
<android.support.v7.widget.RecyclerView
android:id="#+id/rvMenu"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
Activity/fragment that uses the recycler view must do this
#Bind(R.id.rvMenu)
RecyclerView rvMenu;
private CheckboxTitleAdapter menuAdapter;
//Define an interface for callback on long press
public interface YourOwnInterface {
void onLonPress(Object data);
}
private void setUpRecycleView() {
RecyclerView.LayoutManager mLayoutManager = new
LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
rvMenu.setHasFixedSize(false);
rvMenu.setLayoutManager(mLayoutManager);
rvMenu.setItemAnimator(new DefaultItemAnimator());
YourOwnInterface listener = new YourOwnInterface () {
#Override
public void onLonPress(Object data) {
updateView((CheckboxTitlesData) data);
}
};
//this interface is needed wen a longpress is made adapter and the callback is given to your Acitivity/Fragment you can perform necessary opreation
menuAdapter = new CheckboxTitleAdapter(listener);
rvMenu.setAdapter(menuAdapter);
}
private void updateView(CheckboxTitlesData data) {
//perform operation on long press
}
Done it works
I have a RecyclerView implementing a LinearLayout of CardViews through an adapter. Inside each CardView, I have a spinner. What I need to do is get the CardViews position when a spinner is selected. Ex.. if I have 10 CardViews in a list on the screen with a spinner in each, and a select a value from the spinner in the 5th item, I need to get that 5th position as well as the selected value.
I'm able to get the selected value just fine. The issue is with getting the CardViews position. The CardViews are being generated from an ArrayList.
I will include my code below along with an image of the desired results. Any help is greatly appreciated!!
RecyclerView Adapter
public class PopularAdapter extends RecyclerView.Adapter<PopularAdapter.MyViewHolder> {
PopularFragment mPopularFragment;
private Context mContext;
private ArrayList<GameData> gameDataArr = new ArrayList<GameData>();
private String userId;
public PopularAdapter(Context context, ArrayList<GameData> gameDataArr, PopularFragment mPopularFragment, String userId) {
mContext = context;
this.gameDataArr = gameDataArr;
this.mPopularFragment = mPopularFragment;
this.userId = userId;
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView title;
public ImageView thumbnail;
private CardView mCardView;
PopularFragment mPopularFragment;
Spinner mGameSpinner;
LinearLayout mSpinnerLayout;
public MyViewHolder(View view, final PopularFragment mPopularFragment, final String userId) {
super(view);
this.mPopularFragment = mPopularFragment;
mSpinnerLayout = (LinearLayout) view.findViewById(R.id.spinner_layout);
title = (TextView) view.findViewById(R.id.item_title);
thumbnail = (ImageView) view.findViewById(R.id.item_main_img);
mCardView = (CardView) view.findViewById(R.id.item_cardview);
mCardView.setOnClickListener(this);
mGameSpinner = (Spinner) view.findViewById(R.id.game_spinner_options);
mGameSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
//String ASIN = gameDataArr.get(position).getAmazonId();
System.out.println(parent.getId()); // <--- prints the same value for each item.
if(userId == null){
Toast.makeText(mPopularFragment.getActivity(), "You must be logged in.", Toast.LENGTH_LONG).show();
return;
}
FirebaseDbHelper mFirebaseDbHelper = new FirebaseDbHelper();
if(position == 0){
// remove from db
// mFirebaseDbHelper.removeOwnedGame(ASIN, userId);
} else if(position == 1){
// add to owned games
// mFirebaseDbHelper.addOwnedGame(ASIN, userId);
} else {
// add to wishlist games
// mFirebaseDbHelper.addWishlistGame(ASIN, userId);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public void onClick(View view) {
System.out.println("click: " + getPosition());
//mPopularFragment.openGameActivity(getPosition());
}
}
#Override
public PopularAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
System.out.println("parent: " + parent);
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
return new PopularAdapter.MyViewHolder(itemView, mPopularFragment, userId);
}
#Override
public void onBindViewHolder(final PopularAdapter.MyViewHolder holder, final int position) {
GameData game = gameDataArr.get(position);
holder.title.setText(game.getTitle());
Picasso.with(mContext).load(game.getFeatImgUrl()).resize(160, 200).into(holder.thumbnail);
}
#Override
public int getItemCount() {
return gameDataArr.size();
}
}
CardView
<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/item_cardview"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginBottom="0dp"
card_view:cardCornerRadius="4dp"
>
<LinearLayout
android:padding="16dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/item_main_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_toLeftOf="#+id/right_content"
android:scaleType="fitXY"
android:adjustViewBounds="false"/>
<LinearLayout
android:id="#+id/right_content"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="16dp" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Spinner
android:id="#+id/game_spinner_options"
android:entries="#array/game_dropdown"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Spinner>
<Button
android:text="Buy Now"
android:id="#+id/game_buy_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
Popular Fragment
public class PopularFragment extends Fragment {
#BindView(R.id.popular_recyclerView)
RecyclerView mPopularRecyclerView;
private RecyclerView.Adapter mAdapter;
private ArrayList<GameData> gamesArray = new ArrayList<GameData>();
ApiResultsObject apiResults;
private FirebaseAuth auth;
private FirebaseUser user;
private FirebaseAuth.AuthStateListener authListener;
private String userId;
public PopularFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_popular, container, false);
ButterKnife.bind(this, view);
// bus instance
MyBus.getInstance().register(this);
// get api url
// trigger async task
// use results
String amazonApiUrl = getAmazonApiUrl();
if(amazonApiUrl != null){
new AmazonAsyncTask().execute(amazonApiUrl);
}
//get firebase auth instance
auth = FirebaseAuth.getInstance();
//get current user
user = FirebaseAuth.getInstance().getCurrentUser();
//add a auth listener
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
System.out.println("User logged in. Game activity.");
userId = user.getUid();
} else {
// User is signed out
System.out.println("User not logged in. Game activity");
}
}
};
// Inflate the layout for this fragment
return view;
}
private String getAmazonApiUrl() {
String amazonApiUrl = "";
AmazonQuery amazonQuery = new AmazonQuery("ItemSearch");
amazonApiUrl = amazonQuery.buildUrl();
return amazonApiUrl;
}
private void setData(ApiResultsObject data) {
gamesArray = data.getGamesArray();
if (data != null) {
mAdapter = new PopularAdapter(getActivity().getBaseContext(), gamesArray, this, userId);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
mPopularRecyclerView.setLayoutManager(mLayoutManager);
mPopularRecyclerView.setAdapter(mAdapter);
}
}
#Subscribe
public void onAsyncTaskResults(BrowseAsyncTaskResult event) {
apiResults = event.getResults();
if (apiResults != null) {
setData(apiResults);
}
}
#Override
public void onDestroy() {
MyBus.getInstance().unregister(this);
super.onDestroy();
}
#Override
public void onStart() {
super.onStart();
auth.addAuthStateListener(authListener);
}
#Override
public void onStop() {
super.onStop();
if (authListener != null) {
auth.removeAuthStateListener(authListener);
}
}
}
You can set an OnClickListener on mGameSpinner in your onBindViewHolder().
onBindViewHolder(final PopularAdapter.MyViewHolder holder, final int position)
You can then store/use the position parameter as it will be the index into your gameArray for that particular spinner. You can then use that index to grab the spinner's currently selected value and do whatever you need to do with it.
I think you should set a tag for each view in the RV through the holder in onBindViewHolder. Something like:
holder.itemView.setTag(game.getId());
The game's Id should be one of the data points in the ArrayList you passed into the Adpater. So it'd be easier to add a getId() method to your game object.
Once you have an integer Id to call on that's unique to each game in the list, you can simply find that Id within the Spinner's onItemSelectedListener with:
int ID = (int) holder.itemView.getTag();
Then you can use ID within your if-else statements to know which game within your card list the spinner is selected for.
#Override
public void onBindViewHolder(final LanguagesAdapter.MyViewHolder holder, final int position) {
holder.edit_language_name.setText(edit_languageDetails_ArrayList.get(position).getEt_language_name());
sp_langage_rating=edit_languageDetails_ArrayList.get(position).getEt_language_ratings();
String ss=sp_langage_rating;
if(sp_langage_rating != null) {
if(sp_langage_rating.equals("Beginner"))
{
adapterLanguage = new ArrayAdapter<CharSequence>(context, R.layout.my_spinner_items, strarray_language);
adapterLanguage.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.sp_languages.setAdapter(adapterLanguage);
}
else if(sp_langage_rating.equals("Intermediate")) {
adapterLanguage = new ArrayAdapter<CharSequence>(context, R.layout.my_spinner_items, strarray_language1);
adapterLanguage.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.sp_languages.setAdapter(adapterLanguage);
}else if(sp_langage_rating.equals("Expert")){
adapterLanguage = new ArrayAdapter<CharSequence>(context, R.layout.my_spinner_items, strarray_language2);
adapterLanguage.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.sp_languages.setAdapter(adapterLanguage);
}
}else{
adapterLanguage = new ArrayAdapter<CharSequence>(context, R.layout.my_spinner_items, strarray_language);
adapterLanguage.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.sp_languages.setAdapter(adapterLanguage);
}
Log.d("print","yes");
}
I have multiple recyclerViews ,which should appear after another XML view, but they just don't , am using an adapter class to manage this. after using log.v I found that the the functions itself"in Adappter class" arent called , and i don't know why ??
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.linah.movielessonapp.Detailed_Movie">
<TextView
android:id="#+id/MovieTitle"
... />
<ImageView
android:id="#+id/MovieImage"
.../>
<TextView
android:id="#+id/MovieReview"
... />
<Button
android:id="#+id/Favbutton"
... />
<TextView
android:id="#+id/Date"
... />
<TextView
android:id="#+id/Rate"
.../>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/Trailers_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/MovieReview" />
<android.support.v7.widget.RecyclerView
android:id="#+id/reviews_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/Trailers_recycler_view"
/>
</LinearLayout>
</RelativeLayout>
</ScrollView>
public class Detailed_Movie extends AppCompatActivity {
public static List<Movie_Details> movieDetailsList = new ArrayList<>();
private String ID;
public String Trailer_OR_Review = "trailer";
private boolean noConnection;
private boolean trailersDone;
private int trailersSize;
private static MoviesDetailedAdapter mAdapter;
private RecyclerView TrailerRecyclerView, ReviewsRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed__movie);
TrailerRecyclerView = (RecyclerView) findViewById(R.id.Trailers_recycler_view);
ReviewsRecyclerView = (RecyclerView) findViewById(R.id.reviews_recycler_view);
new getData().execute("trailer");
// adapter
mAdapter = new MoviesDetailedAdapter(movieDetailsList,TrailerRecyclerView.getContext(),Trailer_OR_Review);
// mAdapter = new MoviesDetailedAdapter(movieDetailsList,ReviewsRecyclerView.getContext(),Trailer_OR_Review);
TrailerRecyclerView.setLayoutManager(new LinearLayoutManager(TrailerRecyclerView.getContext()));
// ReviewsRecyclerView.setLayoutManager(new LinearLayoutManager(ReviewsRecyclerView.getContext()));
TrailerRecyclerView.setItemAnimator(new DefaultItemAnimator());
// ReviewsRecyclerView.setItemAnimator(new DefaultItemAnimator());
noConnection = false;
if(isOnline(Detailed_Movie.this)) {
new getData().execute("trailer");
mAdapter.notifyDataSetChanged();
}
// set the adapter
TrailerRecyclerView.setAdapter(mAdapter);
prepareMovieData();
Intent i = getIntent();
// http://api.themoviedb.org/3/movie/{id}/videos
String ImgPath = "http://image.tmdb.org/t/p/w185/";
String VideoPath = "http://www.youtube.com/watch?v=";
String MovieTitle = i.getExtras().getString("title");
Toast.makeText(getApplicationContext(),MovieTitle+" is selected!", Toast.LENGTH_SHORT).show();
ImageView img = (ImageView)findViewById(R.id.MovieImage);
TextView Title = (TextView)findViewById(R.id.MovieTitle);
TextView Review = (TextView)findViewById(R.id.MovieReview);
TextView Date = (TextView)findViewById(R.id.Date);
TextView Rate = (TextView)findViewById(R.id.Rate);
Button Fav = (Button) findViewById(R.id.Favbutton);
// get data from intent
assert Title != null;
Title. setText(i.getExtras().getString("title"));
assert Review != null;
Review.setText(i.getExtras().getString("review"));
assert Rate != null;
Rate. setText(i.getExtras().getString("rate"));
assert Date != null;
Date. setText(i.getExtras().getString("date"));
ID = i.getExtras().getString("id");
String Imgurl = i.getExtras().getString("img");
// append ImgPath
switch (ImgPath = new StringBuilder()
.append(ImgPath)
.append(Imgurl)
.toString()) {
}
// append VideoPath
VideoPath = new StringBuilder()
.append(VideoPath)
.append("6uEMl2BtcqQ")
.toString();
// VideoPath = VideoPath + getString(R.string.API_KEY);
final String finalVideoPath = VideoPath;
if (Fav != null) {
Fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(finalVideoPath));
startActivity(intent);
}
});
}
Picasso.with(this)
.load(ImgPath)
.placeholder(R.drawable.loading) //this is optional the image to display while the url image is downloading
.error(R.drawable.error) //this is also optional if some error has occurred in downloading the image
.into(img);
TrailerRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), TrailerRecyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
Movie_Details movie = movieDetailsList.get(position);
if (position < trailersSize) {
// String link = ((TextView) findViewById(R.id.Link)).getText().toString();
// String link = movie.getKey();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=" + movie.getKey())));
}
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
private void prepareMovieData() {
Movie_Details movie = new Movie_Details("MovieTrailer","6uEMl2BtcqQ","Linah","verynice");
movieDetailsList.add(movie);
mAdapter.notifyDataSetChanged();
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private MainActivity.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final MainActivity.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
public RecyclerTouchListener(Context applicationContext, RecyclerView trailerRecyclerView, ClickListener clickListener) {
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public class getData extends AsyncTask<String, Void, Void> {
...
}
}
class MoviesDetailedAdapter
public class MoviesDetailedAdapter extends RecyclerView.Adapter {
private List<Movie_Details> moviesList;
private Context context;
public String Trailer_OR_Review = "trailer";
public TextView TrailerName , Author , Content , TrailerLink ;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
public MyViewHolder(View view) {
super(view);
Log.v("here","MyViewHolder");
TrailerName = (TextView) view.findViewById(R.id.Name);
Author = (TextView) view.findViewById(R.id.Author);
TrailerLink = (TextView) view.findViewById(R.id.Link);
Content = (TextView) view.findViewById(R.id.Content);
view.setOnCreateContextMenuListener(this);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
}
}
public MoviesDetailedAdapter(List<Movie_Details> moviesList,Context context, String trailerORReview) {
this.moviesList = moviesList;
this.context = context;
Trailer_OR_Review = trailerORReview;
Log.v("here","madapter");
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
Log.v("here","onCreateViewHolder");
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.trailers_layout, parent, false);
/*
if (Trailer_OR_Review.equals("trailers")){
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.trailers_layout, parent, false);
}
else{
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.reviews_layout, parent, false);
}*/
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Log.v("here","onBindViewHolder");
Movie_Details movie_details = moviesList.get(position);
Log.v("here",movie_details.getContent());
Log.v("here",movie_details.getName());
TrailerName.setText(movie_details.getName());
TrailerLink.setText(movie_details.getKey());
/*
if (Trailer_OR_Review.equals("trailers")){
TrailerName.setText(movie_details.getName());
TrailerLink.setText(movie_details.getKey());
}
else{
Author.setText(movie_details.getAuthor());
Content.setText(movie_details.getContent());
}*/
}