ViewPager not displaying properly - java

I was trying to do this,
What I made is,
I have tried HorizontalScrollView in ListView
But can't get it properly.
Any help will be appreciated.
Here is my xml
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="8"
android:orientation="vertical">
<com.android.ViewPagerContainer
android:id="#+id/container"
android:layout_width="wrap_content"
android:layout_height="fill_parent">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</com.android.ViewPagerContainer>
</LinearLayout>
My Code is
private class ViewAdapter extends PagerAdapter {
private int count = values.size();
#Override
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == object);
}
#Override
public LinearLayout instantiateItem(ViewGroup container, int position) {
LinearLayout llViewOuter = new LinearLayout(getActivity());
llViewOuter.setOrientation(LinearLayout.VERTICAL);
ImageView thumb_image = new ImageView(getActivity());
thumb_image.setImageResource(R.drawable.optionnor);
thumb_image.setScaleType(ImageView.ScaleType.FIT_CENTER);
llViewOuter.addView(thumb_image);
TextView tmpT = new TextView(getActivity());
tmpT.setText(values.get(position));
tmpT.setGravity(Gravity.CENTER);
llViewOuter.addView(tmpT);
final ImageView checkBox = new ImageView(getActivity());
checkBox.setImageResource(R.drawable.optionnor);
checkBox.setAdjustViewBounds(true);
checkBox.setScaleType(ImageView.ScaleType.FIT_CENTER);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//checkbox2.setImageResource(R.drawable.option);
checkBox.setImageResource(R.drawable.optionselected);
}
});
llViewOuter.addView(checkBox);
((ViewPager) container).addView(llViewOuter);
return llViewOuter;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((LinearLayout) object);
}
}

You can use this Horizontal ListView library https://github.com/EmirWeb/parchment.
public class ListView<ADAPTER extends Adapter> extends AbstractAdapterView<ADAPTER,View>
implements OnLongClickListener, OnClickListener,
OnSelectedListener, AdapterViewHandler {
public ListView(final Context context) {
super(context);
}
public ListView(final Context context, final AttributeSet attributeSet) {
super(context, attributeSet);
}
public ListView(final Context context, final AttributeSet attributeSet, final int defStyle) {
super(context, attributeSet, defStyle);
}
#Override
protected AdapterViewInitializer<View> getAdapterViewInitializer(final Context context, final AttributeSet attributeSet) {
final Attributes attributes = new Attributes(context, attributeSet);
final boolean isViewPager = attributes.isViewPager();
final boolean isVerticalScroll = attributes.isVertical();
final int cellSpacing = (int) attributes.getCellSpacing();
final boolean isCircularScroll = attributes.isCircularScroll();
final boolean snapToPosition = attributes.isSnapToPosition();
final int viewPagerInterval = attributes.getViewPagerInterval();
final SnapPosition snapPosition = attributes.getSnapPosition();
final boolean selectOnSnap = attributes.selectOnSnap();
final boolean selectWhileScrolling = attributes.selectWhileScrolling();
final LayoutManagerAttributes layoutManagerAttributes = new LayoutManagerAttributes(isCircularScroll, snapToPosition, isViewPager, viewPagerInterval, snapPosition, cellSpacing, selectOnSnap, selectWhileScrolling, isVerticalScroll);
final AdapterViewManager adapterViewManager = new AdapterViewManager();
final ListLayoutManager listLayoutManager = new ListLayoutManager(this, this, adapterViewManager, layoutManagerAttributes);
final AdapterViewInitializer<View> adapterViewAdapterViewInitializer = createAdapterViewInitializer(context, isViewPager, adapterViewManager, listLayoutManager, isVerticalScroll);
return adapterViewAdapterViewInitializer;
}
}
Hope you like it.

Related

Listview- clicking on the title to show the description

Im doing Dream app on Android. I have a ListView view containing a title and description that are stored in separate TextView. I want the titles to be displayed in the listView view and only after clicking one of them to display the description. After pressing another title, I want the previous description to collapse and show another, attached to the given title.
I want to my notes look this way:
Android dream
This is my adapter class where I think I need to add a few lines to solve my problem
class SennikListAdapter extends BaseAdapter implements Filterable {
private ArrayList<Sennik> mOriginalValues; // Original Values
private ArrayList<Sennik> mDisplayedValues; // Values to be displayed
LayoutInflater inflater;
public SennikListAdapter(Context context, ArrayList<Sennik> mProductArrayList) {
this.mOriginalValues = mProductArrayList;
this.mDisplayedValues = mProductArrayList;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return mDisplayedValues.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
RelativeLayout llContainer;
TextView titleOfDream, descriptionOfDream;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.customlayout, null);
holder.llContainer = (RelativeLayout) convertView.findViewById(R.id.llContainer);
holder.titleOfDream = (TextView) convertView.findViewById(R.id.titleTextView);
holder.descriptionOfDream = (TextView) convertView.findViewById(R.id.descriptionTextView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.titleOfDream.setText(mDisplayedValues.get(position).getTitleOfDream());
holder.descriptionOfDream.setText(mDisplayedValues.get(position).getDescriptionOfDream() + "");
return convertView;
}
I wanted to do something like this in getView method, but there is an error "Veriable 'holder' is accessed from within inner class, needs to be declered final". If i change to final still doesn't work
holder.titleOfDream.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.descriptionOfDream.getVisibility() == View.GONE)
{
//expandedChildList.set(arg2, true);
holder.descriptionOfDream.setVisibility(View.VISIBLE);
}
else
{
//expandedChildList.set(arg2, false);
holder.descriptionOfDream.setVisibility(View.GONE);
}
}
});
Do you have any ideas how to do this? I checked so many tutorials but didn't find, and im sure it isn't difficult :(
Maybe this would be helpful
this is Fragment class
public class SennikFragment extends Fragment {
private List<String> fileName;
private List<String> fileContent;
private ArrayList<Sennik> sen = new ArrayList<Sennik>();
private SennikListAdapter adapter;
private EditText editText;
private ListView listView;
private AssetManager assets;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sennik, container, false);
// inicjalizacja pól
fileName = new ArrayList<>();
fileContent = new ArrayList<>();
editText=(EditText) view.findViewById(R.id.searchFilter);
listView=(ListView) view.findViewById(R.id.listView);
assets = getActivity().getAssets();
//dodanie do pola wyszukiwania obiektu nasłuchującego zmian w tekście
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (adapter != null) {
adapter.getFilter().filter(s.toString());
} else {
Log.d("filter", "no filter availible");
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
//uzupełnienie listy tytułów i opisów snu z folderu assets
try {
//Pobranie nazw wszystkich plików
String[] paths = assets.list("");
String text="";
/* Usunięcie z nazw plików ich rozszerzenia formatu */
for (String path : paths) {
if (path.equals("images") || path.equals("sounds") || path.equals("webkit"))
continue;
fileName.add(path.replace(".txt", " "));
InputStream is= assets.open(path);
int size=is.available();
byte[]buffer=new byte[size];
is.read(buffer);
is.close();
text=new String(buffer);
fileContent.add(text);
}
} catch (IOException ex) {
Log.e(TAG, "Bład podczas ładowania plików", ex);
}
//dodanie do listy z modelu Sennik tytułów i opisów snu
for(int i=0; i<fileName.size(); i++){
sen.add(new Sennik(fileName.get(i), fileContent.get(i)));
}
adapter=new SennikListAdapter((Context)getActivity(),sen);
listView.setAdapter(adapter);
return view;
}
}
this is description class
public class Sennik {
private String titleOfDream;
private String descriptionOfDream;
public Sennik(String titleOfDream, String descriptionOfDream) {
this.titleOfDream = titleOfDream;
this.descriptionOfDream = descriptionOfDream;
}
public String getTitleOfDream() {
return titleOfDream;
}
public void setTitleOfDream(String titleOfDream) {
this.titleOfDream = titleOfDream;
}
public String getDescriptionOfDream() {
return descriptionOfDream;
}
public void setDescriptionOfDream(String descriptionOfDream) {
this.descriptionOfDream = descriptionOfDream;
}
}
and my layouts:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:id="#+id/llContainer">
<TextView
android:id="#+id/titleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="20dp"
android:textColor="#color/colorAccent"
android:text="TextView" />
<TextView
android:id="#+id/descriptionTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/titleTextView"
android:layout_centerHorizontal="true"
android:textColorHighlight="#color/colorPrimary"
android:textStyle="italic"
android:gravity="center"
android:textColor="#color/colorPrimary"
android:text="TextView" />
<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">
<EditText
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="#+id/searchFilter"></EditText>
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/searchFilter">
</ListView>
EDIT
problem solved!
I just add a line to my Adapter class to hide the description
holder.descriptionOfDream.setVisibility(View.GONE);
so the whole Adapter class look like:
class SennikListAdapter extends BaseAdapter implements Filterable {
private ArrayList<Sennik> mOriginalValues; // Original Values
private ArrayList<Sennik> mDisplayedValues; // Values to be displayed
LayoutInflater inflater;
public SennikListAdapter(Context context, ArrayList<Sennik> mProductArrayList) {
this.mOriginalValues = mProductArrayList;
this.mDisplayedValues = mProductArrayList;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return mDisplayedValues.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
RelativeLayout llContainer;
TextView titleOfDream, descriptionOfDream;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.customlayout, null);
holder.llContainer = (RelativeLayout) convertView.findViewById(R.id.llContainer);
holder.titleOfDream = (TextView) convertView.findViewById(R.id.titleTextView);
holder.descriptionOfDream = (TextView) convertView.findViewById(R.id.descriptionTextView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.titleOfDream.setText(mDisplayedValues.get(position).getTitleOfDream());
holder.descriptionOfDream.setText(mDisplayedValues.get(position).getDescriptionOfDream() + "");
holder.descriptionOfDream.setVisibility(View.GONE);
return convertView;
}
And in Fragment class i use setOnItemClickListener method on listView (setOnClickListener doesn't work)
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView descriptionOfDream= (TextView) view.findViewById(R.id.descriptionTextView);
if(descriptionOfDream.getVisibility()==view.GONE){
descriptionOfDream.setVisibility(view.VISIBLE);
}
else
{
descriptionOfDream.setVisibility(view.GONE);
}
}
});
So the whole Fragment class look like:
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sennik, container, false);
// inicjalizacja pól
fileName = new ArrayList<>();
fileContent = new ArrayList<>();
editText=(EditText) view.findViewById(R.id.searchFilter);
listView=(ListView) view.findViewById(R.id.listView);
assets = getActivity().getAssets();
//dodanie do pola wyszukiwania obiektu nasłuchującego zmian w tekście
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (adapter != null) {
adapter.getFilter().filter(s.toString());
} else {
Log.d("filter", "no filter availible");
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
//uzupełnienie listy tytułów i opisów snu z folderu assets
try {
//Pobranie nazw wszystkich plików
String[] paths = assets.list("");
String text="";
/* Usunięcie z nazw plików ich rozszerzenia formatu */
for (String path : paths) {
if (path.equals("images") || path.equals("sounds") || path.equals("webkit"))
continue;
fileName.add(path.replace(".txt", " "));
InputStream is= assets.open(path);
int size=is.available();
byte[]buffer=new byte[size];
is.read(buffer);
is.close();
text=new String(buffer);
fileContent.add(text);
}
} catch (IOException ex) {
Log.e(TAG, "Bład podczas ładowania plików", ex);
}
//dodanie do listy z modelu Sennik tytułów i opisów snu
for(int i=0; i<fileName.size(); i++){
sen.add(new Sennik(fileName.get(i), fileContent.get(i)));
}
adapter=new SennikListAdapter((Context)getActivity(),sen);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView descriptionOfDream= (TextView) view.findViewById(R.id.descriptionTextView);
if(descriptionOfDream.getVisibility()==view.GONE){
descriptionOfDream.setVisibility(view.VISIBLE);
}
else
{
descriptionOfDream.setVisibility(view.GONE);
}
}
});
return view;
}
}
Works excelent <3
First you need to create a class Extending LinearLayout and give some Expanding/collapsing
capabilities to It. Then define your description Textview as a child of that.
public class ExpandableLinearLayout extends LinearLayout {
private boolean expanded;
private int duration;
public ExpandableLinearLayout(Context context) {
super(context);
}
public ExpandableLinearLayout(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public ExpandableLinearLayout(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public ExpandableLinearLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(attrs);
}
private void init(AttributeSet attributeSet) {
TypedArray customValues = getContext().obtainStyledAttributes(attributeSet, R.styleable.ExpandableLinearLayout);
duration = customValues.getInt(R.styleable.ExpandableLinearLayout_expandDuration, -1);
customValues.recycle();
}
public boolean isExpanded() {
return expanded;
}
public void setExpanded(boolean expanded) {
this.expanded = expanded;
}
public void toggle() {
if (expanded)
expandView(this);
else
hideView(this);
}
private void expandView(final View view) {
view.measure(WindowManager.LayoutParams.MATCH_PARENT
, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
final int targetHeight = view.getMeasuredHeight();
// Older versions of android (pre API 21) cancel animations for views with a height of 0.
view.getLayoutParams().height = 1;
view.setVisibility(View.VISIBLE);
Animation a = new Animation() {
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
view.getLayoutParams().height = interpolatedTime == 1
? targetHeight : (int) (targetHeight * interpolatedTime);
view.requestLayout();
}
#Override
public boolean willChangeBounds() {
return true;
}
};
if (duration == -1)
a.setDuration((int) (targetHeight / view.getContext().getResources().getDisplayMetrics().density * 1.5));
else
a.setDuration(duration);
view.startAnimation(a);
}
private void hideView(final View view) {
final int initialHeight = view.getMeasuredHeight();
Animation a = new Animation() {
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if (interpolatedTime == 1) {
view.setVisibility(View.GONE);
} else {
view.getLayoutParams().height = initialHeight - (int) (initialHeight * interpolatedTime);
view.requestLayout();
}
}
#Override
public boolean willChangeBounds() {
return true;
}
};
if (duration == -1)
a.setDuration((int) (initialHeight / view.getContext().getResources().getDisplayMetrics().density * 1.5));
else
a.setDuration(duration);
view.startAnimation(a);
}
}
Just Inflate this class into your xml layout file and create descriotion textView inside of it.
Add The following Code snippet into your Adapter class to call that when An Item gets a Click. It will Expand/Collapse the LinearLayout with an Animaiton.
private void initializeClicks() {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (expandableLinearLayout.isExpanded()) {
expandableLinearLayout.setExpanded(false);
expandableLinearLayout.toggle();
orderList.get(getAdapterPosition()).setExpanded(false);
} else {
expandableLinearLayout.setExpanded(true);
orderList.get(getAdapterPosition()).setExpanded(true);
expandableLinearLayout.toggle();
if(lastExpandedCardPosition!=getAdapterPosition() && recyclerView.findViewHolderForAdapterPosition(lastExpandedCardPosition)!=null){
((ExpandableLinearLayout)recyclerView.findViewHolderForAdapterPosition(lastExpandedCardPosition).itemView.findViewById(R.id.expandedLinearLayout)).setExpanded(false);
orderList.get(lastExpandedCardPosition).setExpanded(false);
((ExpandableLinearLayout)recyclerView.findViewHolderForAdapterPosition(lastExpandedCardPosition).itemView.findViewById(R.id.expandedLinearLayout)).toggle();
}
else if(lastExpandedCardPosition!=getAdapterPosition() && recyclerView.findViewHolderForAdapterPosition(lastExpandedCardPosition)==null){
orderList.get(lastExpandedCardPosition).setExpanded(false);
}
lastExpandedCardPosition = getAdapterPosition();
}
}
});
}
Finally call the Method above in your Clicklistenr like this:
holder.titleOfDream.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.descriptionOfDream.getVisibility() == View.GONE)
{
expandableLinearLayout.setVisibility(View.VISIBLE);
expandableLinearLayout.setExpanded(true);
}
else
{
expandableLinearLayout.setVisibility(View.GONE);
expandableLinearLayout.setExpanded(false);
}
}
});
For a more detailed Explanation about this Method see this post on Medium.com.
And dont forget to give a clap to this post.
You have to call this method in your code`
holder.descriptionOfDream.requestLayout();
So basically, your new code looks like this
holder.titleOfDream.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.descriptionOfDream.getVisibility() == View.GONE)
{
//expandedChildList.set(arg2, true);
holder.descriptionOfDream.setVisibility(View.VISIBLE);
holder.descriptionOfDream.requestLayout();
}
else
{
//expandedChildList.set(arg2, false);
holder.descriptionOfDream.setVisibility(View.GONE);
holder.descriptionOfDream.requestLayout();
}
}
});
Hope that helps.
Keep in mind that the holder variable must be final like below
final ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.customlayout, null);
holder.llContainer = (RelativeLayout) convertView.findViewById(R.id.llContainer);
holder.titleOfDream = (TextView) convertView.findViewById(R.id.titleTextView);
holder.descriptionOfDream = (TextView) convertView.findViewById(R.id.descriptionTextView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.titleOfDream.setText(mDisplayedValues.get(position).getTitleOfDream());
holder.descriptionOfDream.setText(mDisplayedValues.get(position).getDescriptionOfDream() + "");
return convertView;

how to callback from fragment to activity With bottom sheet

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

RecyclerView Android Dynamic Height

I am looking at creating dynamic heights in my RecyclerView to be responsive across all devices. Currently this works fine but for the first two rows at the start I have a double cell and the height of these two rows gets set to the first cell. I want instead this cell on both the first and second row to match the height of the last cell and become a rectangle. I have tried a few ways but none seem to work I am not sure where the problem is but I hope someone can show me. I will attach screenshots and the code below.
SquareLayout.java
public class SquareLayout extends LinearLayout {
public SquareLayout(Context context) {
super(context);
}
public SquareLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onMeasure(int width, int height) {
// int width = MeasureSpec.getSize(widthMeasureSpec);
//int height = MeasureSpec.getSize(heightMeasureSpec);
// note we are applying the width value as the height
//if(width>=370){
// super.onMeasure(widthMeasureSpec, widthMeasureSpec/2);
// }
// else{
// super.onMeasure(widthMeasureSpec, widthMeasureSpec);
// }
super.onMeasure(width, width);
// Log.d("int","int is: "+ width);
}
}
DataAdapter.java
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private ArrayList<AndroidVersion> android;
private Context context;
public DataAdapter(Context context,ArrayList<AndroidVersion> android) {
this.android = android;
this.context = context;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, int i) {
// int width = viewHolder.tv_android.getMeasuredWidth() / 2; //returns -1
Log.d("MYINT", "value: " + i);
//Picasso.with(context).load(android.get(i).getAndroid_image_url()).resize(240, 120).into(viewHolder.img_android);
}
#Override
public int getItemCount() {
return android.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private LinearLayout testheight;
private ImageView img_android;
public ViewHolder(View view) {
super(view);
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private final String android_version_names[] = {
"test1",
"test2",
"test3",
"test4",
"test5",
"test6",
"test7",
"test8",
"test9",
"test10"
};
private final String android_image_urls[] = {
"http://example.com/images/test.png",
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews(){
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.card_recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getApplicationContext(),3);
ArrayList<AndroidVersion> androidVersions = prepareData();
((GridLayoutManager) mLayoutManager).setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
#Override
public int getSpanSize(int position) {
if (position == 0 || position == 2) {
return 2; // ITEMS AT POSITION 1 AND 6 OCCUPY 3 SPACES
}
else {
return 1; // OTHER ITEMS OCCUPY ONLY A SINGLE SPACE
}
}
});
recyclerView.setLayoutManager(mLayoutManager);
DataAdapter adapter = new DataAdapter(getApplicationContext(), androidVersions);
recyclerView.setAdapter(adapter);
}
private ArrayList<AndroidVersion> prepareData(){
ArrayList<AndroidVersion> android_version = new ArrayList<>();
for(int i=0;i<android_version_names.length;i++){
AndroidVersion androidVersion = new AndroidVersion();
androidVersion.setAndroid_version_name(android_version_names[i]);
androidVersion.setAndroid_image_url(android_image_urls[i]);
android_version.add(androidVersion);
}
return android_version;
}
}
row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<example.SquareLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#android:color/transparent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:layout_marginStart="10dp"
android:background="#color/reloadedpurple"
android:elevation="6dp"
android:orientation="vertical">
<ImageView
android:id="#+id/img_android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true" />
<TextView
android:id="#+id/tv_android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:textColor="#FFFFFF"
android:textStyle="bold" />
</LinearLayout>
</example.SquareLayout>

ViewPager inside a recyclerview

Before marking this as a duplicate i have tried all the solutions but nothing worked. Please go through the question and help me.
I have a recycler view that will have multiple viewPagers and both will scroll individually. I cant seem to implement this. My Code is as follows
RecyclerView Adapter
public class Adapter extends RecyclerView.Adapter<Adapter.holder> {
private final LayoutInflater mLayoutInflater;
private final Context context;
private final RecyclerView r;
private OnLoadMoreListener onLoadMoreListener;
ArrayList<ceo> mArray = new ArrayList<>();
private int heightPixels;
private int widthPixels;
MainActivity contextActivity;
public holder mh;
public Adapter(Context mContext, final RecyclerView r,MainActivity conts) {
contextActivity=conts;
this.r=r;
context = mContext;
mLayoutInflater = LayoutInflater.from(mContext);
r.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (!r.canScrollVertically(1)) {
onLoadMoreListener.onLoadMore();
}
}
});
}
public void setmArray(ArrayList<ceo> mArray) {
this.mArray = mArray;
Log.e("This->", mArray.toString());
notifyItemRangeChanged(0, mArray.size());
}
#Override
public holder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = mLayoutInflater.inflate(R.layout.recycler_custom_photo,viewGroup, false);
mh = new Adapter.holder(v);
return mh;
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
#Override
public void onBindViewHolder(holder holder, int i) {
ViewPagerAdapter mp = new ViewPagerAdapter(context,mArray);
holder.vp.setAdapter(mp);
}
#Override
public int getItemCount() {
return mArray.size();
}
class holder extends RecyclerView.ViewHolder {
ViewPager vp;
public holder(View itemView) {
super(itemView);
vp=(ViewPager)itemView.findViewById(R.id.pager);
}
}
}
View Pager Adapter
public class ViewPagerAdapter extends PagerAdapter {
ArrayList<ceo> alias=null;
private boolean tk=true;
Context mcov;
public ViewPager(Context context,ArrayList<ceo> checkAlias) {
mcov=context;
this.alias=checkAlias;
}
#Override
public int getCount() {
Log.e("Sze",alias.size()+"");
return alias.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
public void setNestedIndic(boolean token)
{
tk=token;
}
public Bitmap decodeFile(File f) {
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
//The new size we want to scale to
final int REQUIRED_SIZE = 290;
//Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater mlAy = (LayoutInflater) mcov
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View m=mlAy.inflate(R.layout.custom_photo, container, false);
ImageView mimg=(ImageView)m.findViewById(R.id.mainImageFeed);
TextView tc=(TextView)m.findViewById(R.id.texr);
String path=alias.get(position).getPath();
Log.e("Pos",""+position);
tc.setText(position+" ");
container.addView(m);
return m;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((android.support.v4.view.ViewPager) container).removeView((RelativeLayout) object);
}
}
recycler_custom_photo.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
custom_photo.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#313131"
android:id="#+id/taken"
android:layout_height="wrap_content">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/old"
android:id="#+id/mainImageFeed"
android:layout_centerVertical="true"
android:adjustViewBounds="true"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/texr"
android:textSize="40dp"
/>
</RelativeLayout>
What changes do i need to make to make these work? Thank You for answering!
The code was fine. The thing i missed out was adding a specific height to the viewpager inside the recyclerview. Also i instantiated the LayoutInflater in the constructor of the PagerAdapter and not instantiateItem. Hope this helps someone in the future!

ExpandableListView OnChildClickListener doesn't work

Adapter
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context mContext;
private ExpandableListView mExpandableListView;
private List <Grupe> mGroupCollection;
private int[] groupStatus;
public ExpandableListAdapter() {}
public ExpandableListAdapter(Context pContext,
ExpandableListView pExpandableListView,
List <Grupe> pGroupCollection) {
mContext = pContext;
mGroupCollection = pGroupCollection;
mExpandableListView = pExpandableListView;
groupStatus = new int[mGroupCollection.size()];
setListEvent();
}
private void setListEvent() {
mExpandableListView
.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int arg0) {
groupStatus[arg0] = 1;
}
});
mExpandableListView
.setOnGroupCollapseListener(new OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int arg0) {
groupStatus[arg0] = 0;
}
});
}
#Override
public String getChild(int arg0, int arg1) {
return mGroupCollection.get(arg0).getChildren().get(arg0).getPrimaoc_Poruke();
}
#Override
public long getChildId(int arg0, int arg1) {
return 0;
}
#Override
public View getChildView(int arg0, int arg1, boolean arg2, View arg3,
ViewGroup arg4) {
ChildHolder childHolder;
if (arg3 == null) {
arg3 = LayoutInflater.from(mContext).inflate(
R.layout.list_group_item, null);
childHolder = new ChildHolder();
childHolder.title = (TextView) arg3.findViewById(R.id.item_title);
arg3.setTag(childHolder);
} else {
childHolder = (ChildHolder) arg3.getTag();
}
childHolder.title.setText(mGroupCollection.get(arg0).getChildren().get(arg1).getPrimaoc_Poruke());
return arg3;
}
#Override
public int getChildrenCount(int arg0) {
return mGroupCollection.get(arg0).getChildren().size();
}
#Override
public Object getGroup(int arg0) {
return mGroupCollection.get(arg0);
}
#Override
public int getGroupCount() {
return mGroupCollection.size();
}
#Override
public long getGroupId(int arg0) {
return arg0;
}
#Override
public View getGroupView(int arg0, boolean arg1, View arg2, ViewGroup arg3) {
GroupHolder groupHolder;
if (arg2 == null) {
arg2 = LayoutInflater.from(mContext).inflate(R.layout.list_group, null);
groupHolder = new GroupHolder();
groupHolder.img = (ImageView) arg2.findViewById(R.id.tag_img);
groupHolder.title = (TextView) arg2.findViewById(R.id.group_title);
arg2.setTag(groupHolder);
} else {
groupHolder = (GroupHolder) arg2.getTag();
}
if (groupStatus[arg0] == 0) {
groupHolder.img.setImageResource(R.drawable.group_down);
} else {
groupHolder.img.setImageResource(R.drawable.group_up);
}
groupHolder.title.setText(mGroupCollection.get(arg0).getTip());
return arg2;
}
class GroupHolder {
ImageView img;
TextView title;
}
class ChildHolder {
TextView title;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int arg0, int arg1) {
return true;
}
}
MainActivity
public class Glavna extends Activity implements OnClickListener, OnChildClickListener {
private List <Grupe> mGroupCollection;
private ExpandableListView mExpandableListView;
private ExpandableListAdapter adapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_glavna);
prepareResource();
initPage();
}
private void initPage() {
mExpandableListView = (ExpandableListView) findViewById(R.id.expandableListView1);
adapter = new ExpandableListAdapter(this,mExpandableListView, mGroupCollection);
mExpandableListView.setAdapter(adapter);
mExpandableListView.setOnChildClickListener(this);
}
private void prepareResource() {
mGroupCollection = new ArrayList <Grupe> ();
ge.setTip("Online korisnici");
mGroupCollection.add(ge);
AktivniChat gi = new AktivniChat(1, "receiver 1", new Korisnik(1, "sender1"));
mGroupCollection.get(0).setAktivniChat(gi);
}
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
return true;
}
}
Set android:focusable="false" on all elements.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:baselineAligned="false"
android:paddingTop="5dip"
android:focusable="false">
<LinearLayout
android:id="#+id/groupItem"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#FFF385"
android:clickable="false"
android:focusable="false">
<TextView
android:id="#+id/item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FF84"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="sample"
android:textColor="#000000"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
Don't forget to enable child Selectable property..
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
It worked for me too... All items in layout (of the child) must be set to focusable="false" and clickable="false". But if you have buttons in child layout this will not work.

Categories