CardView not inflating in RecyclerView - android

I cannot figure out why I can't see the CardView when I run the app. It shows in the design window in Android Studio, but when I run the app, there are no errors that come up, and the app functions normally, with the exception of the CardView not showing.
Before I post my code, here is what I've tried researching to see if I was making the same errors:
CardView not shown in RecyclerView
card view not showing up
(apparently, I need to have more than 10 reputation to post more than 2 links, just know there was about 10)
Please know that I'm relatively new to development and RecyclerView and that I really did try my best to google/stackoverflow for an answer and I tried implementing all of them, but there wasn't one that worked for me. Either it's something I'm not seeing, or I'm just not experienced enough to notice. Either way, I would really appreciate any help.
Here are my gradle dependencies:
ext {
// versions for libraries that multiple dependencies
supportLibVersion = '25.1.0'
dagger = '2.7'
butterknife = '8.4.0'
pocketknife = '3.2.1'
}
dependencies {
// Support Libraries
compile "com.android.support:appcompat-v7:${supportLibVersion}"
compile "com.android.support:design:${supportLibVersion}"
compile "com.android.support:support-v4:${supportLibVersion}"
compile "com.android.support:cardview-v7:${supportLibVersion}"
compile "com.android.support:recyclerview-v7:${supportLibVersion}"
//recyclerview from brian wernick
compile 'com.devbrackets.android:recyclerext:2.0.1'
Here is the MainActivity:
public class MainActivity extends BaseActivity implements BottomNavigationView.OnNavigationItemSelectedListener, ViewPager.OnPageChangeListener {
#Inject
EventBus bus;
#BindView(R.id.bottomNavigation)
BottomNavigationView bottomNavigation;
#BindView(R.id.viewpager)
ViewPager viewPager;
private SwipeFragmentPagerAdapter adapter;
#Override
protected int getLayoutResourceId() {
return R.layout.activity_main;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Injector.get().inject(this);
PocketKnife.restoreInstanceState(this, savedInstanceState);
bottomNavigation.setOnNavigationItemSelectedListener(this);
adapter = new SwipeFragmentPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(this);
bus.postSticky(new ViewPagerEvent(adapter.getItem(0).getClass()));
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int position;
if (item.getItemId() == R.id.menu_item_explore) {
position = 1;
} else if (item.getItemId() == R.id.menu_item_my_goals) {
position = 2;
} else if (item.getItemId() == R.id.menu_item_profile) {
position = 3;
} else {
position = 0;
}
viewPager.setCurrentItem(position, false);
return true;
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//required empty method
}
#Override
public void onPageSelected(int position) {
MenuItem menuItem = bottomNavigation.getMenu().getItem(position);
if (menuItem != null) {
menuItem.setChecked(true);
bus.postSticky(new ViewPagerEvent(adapter.getItem(position).getClass()));
}
}
#Override
public void onPageScrollStateChanged(int state) {
//required empty method
}
}
Here is my adapter:
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.view.ViewGroup;
import com.devbrackets.android.recyclerext.adapter.RecyclerListAdapter;
import com.devbrackets.android.recyclerext.adapter.viewholder.ClickableViewHolder;
import agency.rain.android.simple.things.model.ExploreData;
import agency.rain.android.simple.things.ui.activity.ClickActivity;
import agency.rain.android.simple.things.ui.activity.adapter.viewholder.ExploreViewHolder;
public class ExploreAdapter extends RecyclerListAdapter<ExploreViewHolder, ExploreData> implements ClickableViewHolder.OnClickListener {
private Context context;
public ExploreAdapter(Context context) {
this.context = context;
}
#Override
public ExploreViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return ExploreViewHolder.newInstance(parent, this);
}
#Override
public void onBindViewHolder(ExploreViewHolder holder, int position) {
final ExploreData data = getItem(position);
if (data == null) {
return;
}
holder.bindData(data);
}
#Override
public void onClick(#NonNull ClickableViewHolder viewHolder) {
final ExploreData data = getItem(viewHolder.getAdapterPosition());
Intent repListIntent = new Intent(context, ClickActivity.class);
context.startActivity(repListIntent);
}
}
This is my ViewHolder:
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.devbrackets.android.recyclerext.adapter.viewholder.ClickableViewHolder;
import agency.rain.android.simple.things.R;
import agency.rain.android.simple.things.model.ExploreData;
import butterknife.BindView;
import butterknife.ButterKnife;
public class ExploreViewHolder extends ClickableViewHolder {
#BindView(R.id.card_view_explore)
CardView cv;
#BindView(R.id.explore_placeholder_text)
TextView ept;
#BindView(R.id.explore_placeholder_image)
ImageView epi;
private ExploreViewHolder(#NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public static ExploreViewHolder newInstance(ViewGroup parent, ClickableViewHolder.OnClickListener listener) {
final ExploreViewHolder viewHolder = new ExploreViewHolder(
LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_explore, parent, false));
viewHolder.setOnClickListener(listener);
return viewHolder;
}
public void bindData(ExploreData data) {
ept.setText(data.getExploreText());
epi.setImageResource(data.getExploreImage());
}
}
This is my Data object:
import java.io.Serializable;
public class ExploreData implements Serializable {
private String exploreText;
private int exploreImage;
public int getExploreImage() {
return exploreImage;
}
public String getExploreText() {
return exploreText;
}
}
This is the Fragment that should be showing the CardView:
public class ExploreFragment extends BaseFragment implements AdapterView.OnItemClickListener {
#BindView(R.id.explore_recycler_view)
RecyclerView exploreRecyclerView;
private Unbinder unbinder;
private ExploreAdapter exploreAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_explore, container, false);
Injector.get().inject(this);
unbinder = ButterKnife.bind(this, view);
PocketKnife.bindArguments(this);
final LinearLayoutManager exploreLayoutManager = new LinearLayoutManager(getActivity());
exploreRecyclerView.setLayoutManager(exploreLayoutManager);
exploreAdapter = new ExploreAdapter(getActivity());
exploreRecyclerView.setAdapter(exploreAdapter);
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onDestroy() {
super.onDestroy();
if (unbinder != null) {
unbinder.unbind();
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_explore, menu);
}
#Override
protected int getTitleResourceId() {
return R.string.explore_title_text;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
The Fragment xml:
<?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="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/explore_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</LinearLayout>
And last but not least, the list_item xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view_explore"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="4dp"
android:clickable="true"
card_view:cardBackgroundColor="#android:color/white"
android:background="?android:attr/selectableItemBackground"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/explore_placeholder_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/drop_the_pounds"
android:textColor="#android:color/black"
android:textAllCaps="true" />
<ImageView
android:id="#+id/explore_placeholder_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/challengeimage"
android:layout_marginRight="65dp"
android:layout_marginEnd="65dp" />
</RelativeLayout>
</android.support.v7.widget.CardView>

Related

Is there any simple way to make FirebaseRecyclerAdapter for implementation 'com.firebaseui:firebase-ui-database:4.0.1'

Let me get straight to the point. I have searched many times about RECYCLE VIEW and CARD VIEW. I have already tried many tips and yet I still can't find out which one is the best and the latest.
I have the feeling that this one firebase-ui (FirebaseRecyclerAdapter) is the easiest one to implement in recycle view and card view.
"implementation 'com.firebaseui:firebase-ui-database:4.0.1'"
What I found out was an error at
#Override //It says 'Method does not override from its superclass.
protected void populateViewHolder(HomeViewHolder homeViewHolder, home model, int position){
homeViewHolder.setTitle(model.getTitle());
homeViewHolder.setShortDescription(model.getShortDescription());
}
I think this one is not available for the latest update for 4.0.1
I put the code in Fragment.
FragmentHome.java
package my.package.sports;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
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 android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
/**
* A simple {#link Fragment} subclass.
*/
public class FragmentHome extends Fragment {
private FirebaseRecyclerAdapter firebaseRecyclerAdapterHome;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mainView = inflater.inflate(R.layout.fragment_home, container, false);
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("home");
databaseReference.keepSynced(true);
RecyclerView recyclerView = mainView.findViewById(R.id.recycleView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//FirebaseRecyclerAdapter
firebaseRecyclerAdapterHome = new FirebaseRecyclerAdapter<home, HomeViewHolder>(home.class, R.layout.home_row, HomeViewHolder.class, databaseReference) {
#NonNull
#Override
public HomeViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return null;
}
#Override
protected void onBindViewHolder(HomeViewHolder holder, int position, home model) {
}
#Override //It says 'Method does not override from its superclass.(Only Here the Error)
protected void populateViewHolder(HomeViewHolder homeViewHolder, home model, int position) {
homeViewHolder.setTitle(model.getTitle());
homeViewHolder.setShortDescription(model.getShortDescription());
}
};
recyclerView.setAdapter(firebaseRecyclerAdapterHome);
return mainView;
}
public static class HomeViewHolder extends RecyclerView.ViewHolder {
View viewData;
public HomeViewHolder(View viewItem) {
super(viewItem);
viewData = viewItem;
}
public void setTitle(String title) {
TextView textViewTitle = viewData.findViewById(R.id.home_row_title);
textViewTitle.setText(title);
}
public void setShortDescription(String shortDescription) {
TextView textViewShortDescription = viewData.findViewById(R.id.home_row_short_description);
textViewShortDescription.setText(shortDescription);
}
}
#Override
public void onStart() {
super.onStart();
firebaseRecyclerAdapterHome.startListening();
}
#Override
public void onStop() {
super.onStop();
firebaseRecyclerAdapterHome.stopListening();
}
}
home.class
package my.package.sports;
public class home {
private String title;
private String shortDescription;
home() {
}
public home(String title, String shortDescription) {
this.title = title;
this.shortDescription = shortDescription;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getShortDescription() {
return shortDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
}
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<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=".FragmentHome">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycleView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
home_row.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="7dp"
android:elevation="90dp"
android:orientation="vertical"
app:cardCornerRadius="11dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="245dp"
android:background="#color/colorPrimaryDark"
android:orientation="vertical">
<TextView
android:id="#+id/home_row_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="7dp"
android:text="Title"
android:textColor="#color/colorText"
android:textSize="20sp" />
<TextView
android:id="#+id/home_row_short_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="7dp"
android:text="Short Description" />
</LinearLayout>
</android.support.v7.widget.CardView>
Please help me to make recycleView and cardView for Fragment and apply to firebase.
You should use THIS guide where details how to use it
you should use this structure in order to populate the RecyclerView with Firebase-UI
The FirebaseRecyclerAdapter binds a Query to a RecyclerView. When data is added, removed, or changed these updates are automatically applied to your UI in real-time.
First, configure the adapter by building FirebaseRecyclerOptions.
FirebaseRecyclerOptions<home> options =
new FirebaseRecyclerOptions.Builder<home>()
.setQuery(query, home.class)
.build();
Next create the FirebaseRecyclerAdapter object. You should already have a ViewHolder subclass for displaying each item
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<home, HomeViewHolder>(options) {
#Override
public HomeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.message for each item
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.message, parent, false);
return new HomeViewHolder(view);
}
#Override
protected void onBindViewHolder(HomeViewHolder holder, int position, home model) {
// Bind the Chat object to the ChatHolder
// ...
}
};
and don't forget about this
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
I have solved my question by downgrading the firebaseui.
implementation 'com.firebaseui:firebase-ui-database:0.4.0'
And I use populateViewHolder as it supports for 0.4.0
FirebaseRecyclerAdapter<home, HomeViewHolder> firebaseRecyclerAdapterHome =
new FirebaseRecyclerAdapter<home, HomeViewHolder>(
home.class,
R.layout.home_row,
HomeViewHolder.class,
databaseReference
) {
#Override
protected void populateViewHolder(HomeViewHolder viewHolder, home model, int position) {
viewHolder.setDetails(getContext(), model.getImage(),model.getTitle(), model.getDate(), model.getShortDescription());
}
};
//setAdapter
recyclerView.setAdapter(firebaseRecyclerAdapterHome);

Adding Long Press Listner to Listview inside a Recycler view

I have been searching a lot of tutorials to implement an on item long press Listener on a Listview which is Inside a RecyclerView. So far I had no luck.
I want a menu to more ap after holding the List Item for some time. I am attaching my code here please help me with it.
I have added my complete code Including the MainAcyivity.
I have a tabbed view which contains 3tabs. Inside the tab view, there is a fragment which contains a Listview.
I want the List to be long pressed to bring a popup menu which has as add or delete options.
MainActivity.java
package tabbardemo.com.materialdesigntabs_demo;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static Toolbar toolbar;
private static ViewPager viewPager;
private static TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewPager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);//setting tab over viewpager
//Implementing tab selected listener over tablayout
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());//setting current selected item over viewpager
switch (tab.getPosition()) {
case 0:
Log.e("TAG","TAB1");
break;
case 1:
Log.e("TAG","TAB2");
break;
case 2:
Log.e("TAG","TAB3");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
//Setting View Pager
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new DummyFragment("Inbox"), "Inbox");
adapter.addFrag(new EventsFragment("QA"), "QA");
adapter.addFrag(new EventsFragment("Events"), "Events");
viewPager.setAdapter(adapter);
}
//View Pager fragments setting adapter class
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();//fragment arraylist
private final List<String> mFragmentTitleList = new ArrayList<>();//title arraylist
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
//adding fragments and title method
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
activity_main.xml
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/coordinatorLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- AppBar Layout -->
<android.support.design.widget.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="fill_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<!-- Tab Layout for creating tabs -->
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<!-- Helps handing the Fragments for each Tab -->
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
dummy_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/blue"
android:gravity="center"
android:orientation="vertical">
<!-- Recycler View -->
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="none" />
</LinearLayout>
DummyFragment.java
package tabbardemo.com.materialdesigntabs_demo;
import android.content.Context;
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.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
/**
* Created by SONU on 16/09/15.
*/
public class DummyFragment extends Fragment {
private View view;
private String title;//String for tab title
private static RecyclerView recyclerView;
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
public void onLongItemClick(View view, int position);
}
public DummyFragment(String title) {
this.title = title;//Setting tab title
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.dummy_fragment, container, false);
setRecyclerView();
return view;
}
//Setting recycler view
private void setRecyclerView() {
recyclerView = (RecyclerView) view
.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView
.setLayoutManager(new LinearLayoutManager(getActivity()));//Linear Items
ArrayList<String> arrayList = new ArrayList<>();
for (int i = 0; i < 20; i++) {
arrayList.add(title+" Items " + i);//Adding items to recycler view
}
RecyclerView_Adapter adapter = new RecyclerView_Adapter(getActivity(), arrayList);
recyclerView.setAdapter(adapter);// set adapter on recyclerview
}
}
RecyclerView_Adapter
package tabbardemo.com.materialdesigntabs_demo;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
/**
* Created by SONU on 10/09/15.
*/
public class RecyclerView_Adapter extends
RecyclerView.Adapter<DemoViewHolder> {
private ArrayList<String> arrayList;
private Context context;
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
public RecyclerView_Adapter(Context context,
ArrayList<String> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#Override
public int getItemCount() {
return (null != arrayList ? arrayList.size() : 0);
}
#Override
public void onBindViewHolder(DemoViewHolder holder,
int position) {
final DemoViewHolder mainHolder = (DemoViewHolder) holder;
//Setting text over textview
// mainHolder.bind(arrayList.get(position), listener);
mainHolder.title.setText(arrayList.get(position));
}
#Override
public DemoViewHolder onCreateViewHolder(
ViewGroup viewGroup, int viewType) {
LayoutInflater mInflater = LayoutInflater.from(viewGroup.getContext());
ViewGroup mainGroup = (ViewGroup) mInflater.inflate(
R.layout.item_row, viewGroup, false);
DemoViewHolder mainHolder = new DemoViewHolder(mainGroup) {
#Override
public String toString() {
return super.toString();
}
};
// 13805 ////////////////////////////////
return mainHolder;
}
}
DemoViewHolder.java
package tabbardemo.com.materialdesigntabs_demo;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
/**
* Created by SONU on 31/08/15.
*/
public abstract class DemoViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public DemoViewHolder(View view) {
super(view);
this.title = (TextView) view.findViewById(R.id.cardTitle);
}
}
ite_row.xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/iv_image"
android:padding="10dp"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:src="#mipmap/ic_launcher">
</ImageView>
<TextView
android:id="#+id/cardTitle"
android:layout_toRightOf ="#+id/iv_image"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:padding="15dp"
android:text="Card Title"
android:textColor="#000000"
android:textSize="17sp" ></TextView>
</RelativeLayout>
1- create your menu items (your list item to show on long click)
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/one"
android:title="One"/>
<item
android:id="#+id/two"
android:title="Two"/>
<item
android:id="#+id/three"
android:title="Three"/>
</menu>
2- setup listener and menu.
#Override
public void onBindViewHolder(DemoViewHolder holder, int position) {
holder.title.setText(arrayList.get(position));
holder.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
showMenu(v);
return true;
}
});
}
// method to open a popup menu(list) upon long click in the recyclerView item
private void showMenu(View view){
PopupMenu popup = new PopupMenu(context,view );
popup.getMenuInflater()
.inflate(R.menu.popup_menu, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
return true;
}
});
popup.show();
}
When you are doing setOnItemLongClickListener() in the ListView:
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
// Dialog/Popup will appears here
showAddDeleteDialog();
return true;
}
});
public void showAddDeleteDialog(){
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setCancelable(false);
dialog.setTitle("Add or Delete Dialog");
// dialog.setMessage("Are you sure you want to delete this entry?" );
dialog.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
//Action for "Add".
}
})
.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Action for "Delete".
}
});
final AlertDialog alert = dialog.create();
alert.show();
}

GridView numColumns=auto_fit, prevent items from being stretched

I would like to display items in a dialog. I used GridView. If I don't set the column width manually, GridView used hard-coded column number 2 like figure 1. If I set the column width, then it showed as many columns as possible like figure 2.
The problem is GridView seems to stretch the item to fill the whole screen, when I set a hard-coded width for the item (refer the code below). What can I prevent this? My final destination is to remove the red area in Figure 2. That should shrink the dialogue width by the amount of the red areas.
Figure 1.
Figure 2.
my_dialogue.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TableRow>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Family"/>
<GridView
android:stretchMode="columnWidth"
android:horizontalSpacing="0dp"
android:numColumns="auto_fit"
android:id="#+id/familyGrid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</TableRow>
</TableLayout>
my_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:background="#android:color/holo_red_dark"
android:layout_height="wrap_content">
<ImageView
android:background="#android:color/holo_blue_dark"
android:layout_width="48sp"
android:layout_height="48sp"/>
<TextView
tools:text="Some application"
android:id="#+id/tvLabel"
android:background="#android:color/holo_blue_bright"
android:gravity="center_vertical"
android:layout_width="192sp"
android:layout_height="48sp"/>
</LinearLayout>
MyDialogue.java
package com.example.me.test2;
import android.content.res.Resources;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import static android.util.TypedValue.COMPLEX_UNIT_SP;
import static android.util.TypedValue.applyDimension;
public class MyDialogue extends AppCompatDialogFragment
{
String TAG = this.getClass().getName();
private static MyDialogue instance;
private GridView myGrid;
public static MyDialogue getInstance()
{
if(instance == null)
{
instance = new MyDialogue();
}
return instance;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState)
{
setStyle(STYLE_NO_TITLE, 0);
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.my_dialogue, container, false);
myGrid = (GridView)v.findViewById(R.id.familyGrid);
//If I do not set the column width, it does not know the item width,
//and the column number falls back to 2.
Resources r = getResources();
float px = applyDimension(COMPLEX_UNIT_SP, 192+48, r.getDisplayMetrics());
myGrid.setColumnWidth((int)px);
ArrayList<String> list = new ArrayList<>();
list.add("Father: Homer Simpson");
list.add("Mother: Marge Simpson");
list.add("Son: Bart Simpson");
list.add("Daughter: Lisa Simpson");
list.add("Baby: Maggie Simpson");
list.add("Dog: Santa's L. Helper");
MyAdapter oa = new MyAdapter(list);
myGrid.setAdapter(oa);
return v;
}
class MyAdapter implements ListAdapter
{
List<String> list;
public MyAdapter(List<String> list)
{
this.list = list;
}
#Override
public boolean areAllItemsEnabled()
{
return true;
}
#Override
public boolean isEnabled(int position)
{
return true;
}
#Override
public void registerDataSetObserver(DataSetObserver observer)
{
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer)
{
}
#Override
public int getCount()
{
return list.size();
}
#Override
public Object getItem(int position)
{
return list.get(position);
}
#Override
public long getItemId(int position)
{
return 0;
}
#Override
public boolean hasStableIds()
{
return false;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = View.inflate(myGrid.getContext(), R.layout.my_item, null);
TextView tvLabel = (TextView) v.findViewById(R.id.tvLabel);
tvLabel.setText(list.get(position));
return v;
}
#Override
public int getItemViewType(int position)
{
return 0;
}
#Override
public int getViewTypeCount()
{
return 1;
}
#Override
public boolean isEmpty()
{
return list.isEmpty();
}
}
}
MainActivity.java
package com.example.me.test2;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity
{
String TAG = this.getClass().getName();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnShow = (Button)findViewById(R.id.btnShow);
btnShow.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
FragmentManager manager = getSupportFragmentManager();
AppCompatDialogFragment dialogue = MyDialogue.getInstance();
dialogue.show(manager, "dialogue");
}
});
}
}
if i understood your question, you may want to put the gridView inside a linear layout, setting to grid view to fill the linear layout, but put some padding to the linear layout. good luck.

ListView with Horizontal ScrollView

I am trying to make a listview which consists of a horizontal scrollview as each one of the rows. I want the elements to be lined up vertically so the view would become scrollable if there are more then a certain amount of items.
However it comes out looking like this.
I am inflating the following xml
single_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:background="#FFFFFF"
android:layout_height="fill_parent">
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.example.jj.library.ChipView
android:layout_weight="1"
android:id="#+id/text_chip_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
This is my adapter to add the views to the view
Adapter.java
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import com.example.jj.library.Chip;
import com.example.jj.library.ChipView;
import com.example.jj.library.ChipViewAdapter;
import com.example.jj.library.OnChipClickListener;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jj on 12/21/2015.
*/
public class LiveFeedAdapter extends ArrayAdapter<LiveFeedDataProvider> implements OnChipClickListener {
private static final String TAG = "LIVEFEED ADAPTER";
Context CTX;
private ChipView mTextChipLayout;
public List<LiveFeedDataProvider> liveFeed_list = new ArrayList<LiveFeedDataProvider>();
public LiveFeedAdapter(Context context, int resource) {
super(context, resource);
CTX = context;
}
#Override
public void add(LiveFeedDataProvider object){
liveFeed_list.add(object);
super.add(object);
}
#Override
public int getCount() {
return liveFeed_list.size();
}
#Override
public LiveFeedDataProvider getItem(int position) {
return liveFeed_list.get(position);
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
if(convertView == null){
LayoutInflater inflator = (LayoutInflater) CTX.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.single_livefeed_row,parent,false);
}
ChipViewAdapter adapterLayout = new MainChipViewAdapter(getContext());
mTextChipLayout = (ChipView) convertView.findViewById(R.id.text_chip_layout);
mTextChipLayout.setAdapter(adapterLayout);
mTextChipLayout.setChipLayoutRes(R.layout.chip_close);
mTextChipLayout.setChipBackgroundColor(CTX.getResources().getColor(R.color.light_blue));
mTextChipLayout.setChipBackgroundColorSelected(CTX.getResources().getColor(R.color.green));
mTextChipLayout.setOnChipClickListener(this);
LiveFeedDataProvider provider = liveFeed_list.get(position);
Log.d(TAG, "LENGTH = " + provider.interests.length);
for(int i = 0; i < provider.interests.length; i++) {
String interest = provider.interests[i];
mTextChipLayout.add(new Tag(interest));
}
return convertView;
}
#Override
public void onChipClick(Chip chip) {
}
}
I solved your problem in a bit different way: I replaced HorizontalScrollView and ListView by a RecyclerView with each row as a RecyclerView which, as I believe, is a preferred layout here.
Here's a result:
(don't pay to much attention to an ugly design :-) )
MainActivity layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#FFFFFF"
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
MainActivity class:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView chipRecyclerView = (RecyclerView)findViewById(R.id.recyclerView);
chipRecyclerView.setLayoutManager(new LinearLayoutManager(this));
ArrayList<String[]> chipsArray = new ArrayList<>();
chipsArray.add(new String[] {"Fitness", "Gaming", "Education","Animals", "Cars"});
.....
chipsArray.add(new String[] {"Education","Animals", "Cars"});
chipRecyclerView.setAdapter(new ListChipsAdapter(chipsArray));
}
}
ListChipsAdapter - adapter for the MainActivity's recycler view. It manages list of rows with chips.
public class ListChipsAdapter extends RecyclerView.Adapter {
private ArrayList<String[]> chipsArray;
public ListChipsAdapter(ArrayList<String[]> chipsArray) {
this.chipsArray = chipsArray;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ChipsViewHolder(new RowChipsView(parent.getContext()));
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((RowChipsView)holder.itemView).setAdapter(new ChipsAdapter(chipsArray.get(position)));
}
#Override
public int getItemCount() {
return chipsArray.size();
}
private class ChipsViewHolder extends RecyclerView.ViewHolder {
public ChipsViewHolder(View itemView) {
super(itemView);
}
}
}
RowChipsView - is a class which represents the particular single row:
public class RowChipsView extends FrameLayout {
public RowChipsView(Context context) {
super(context);
initializeView(context);
}
private void initializeView(Context context) {
LayoutInflater.from(context).inflate(R.layout.single_row, this);
((RecyclerView)findViewById(R.id.recyclerViewHorizontal)).setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
}
public void setAdapter(ChipsAdapter adapter) {
((RecyclerView)findViewById(R.id.recyclerViewHorizontal)).setAdapter(adapter);
}
}
It's Layout is consist of only one RecyclerView:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/recyclerViewHorizontal"
android:layout_width="match_parent"
android:layout_height="56dp"/>
Now, ChipsAdapter - the adapter which is used by each single row:
public class ChipsAdapter extends RecyclerView.Adapter {
private String[] chipsArray;
public ChipsAdapter(String[] chipsArray) {
this.chipsArray = chipsArray;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ChipViewHolder(new ChipView(parent.getContext()));
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((ChipView)holder.itemView).displayItem(chipsArray[position]);
}
#Override
public int getItemCount() {
return chipsArray.length;
}
private class ChipViewHolder extends RecyclerView.ViewHolder {
public ChipViewHolder(View itemView) {
super(itemView);
}
}
}
Now, the last piece is a ChipView:
public class ChipView extends FrameLayout {
public ChipView(Context context) {
super(context);
initializeView(context);
}
private void initializeView(Context context) {
LayoutInflater.from(context).inflate(R.layout.chip_view, this);
}
public void displayItem(String text) {
((TextView)findViewById(R.id.chipTextView)).setText(text);
}
}
and it's layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#drawable/rounded_background"
android:layout_margin="4dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/chipTextView"
android:textColor="#FFFFFF"
android:textSize="24sp"
android:padding="8dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>
I've uploaded the project to my dropbox, so feel free to check it out!
I hope, it helps.

change text size in view pager fragment according seek bar in activity

In my activity (Please see image), I have seek bar and view pager ( have 3 pages).
I want so that, when seek bar in activity change, the text of the fragment size also varies.
How can I do it?
I try it with interface but it not run.
Mainactivity
package com.creativei.viewpagerloop;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private static final String LOG_TAG = "ViewPagerLoop";
public static final String[] content = new String[] {
"Hello Welcome to ViewPager Loop Example. This is first view. Swipe right → for second view, swipe left � for last view.",
"Awesome, now you are on second view. Swipe right → again to go to last view.",
"Finally made it to last view, swipe right → again to go to first view." };
Interface inter;
public MainActivity(Interface inter) {
this.inter = inter;
}
private SeekBar seekBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekBar = (SeekBar) findViewById(R.id.seekBar1);
ViewPager pager = (ViewPager) findViewById(R.id.pager);
TextView counter = (TextView) findViewById(R.id.counter);
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
inter.seekBarChange(progress);
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
SimpleViewPagerAdapter adapter = new SimpleViewPagerAdapter(
getSupportFragmentManager(), pager, content, counter);
pager.setAdapter(adapter);
pager.setOnPageChangeListener(adapter);
pager.setCurrentItem(1, false);
}
public static class SimpleFragment extends Fragment implements Interface {
private TextView textView;
public SimpleFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
String content = getArguments().getString("content");
textView = (TextView) rootView.findViewById(R.id.content);
textView.setText(content);
return rootView;
}
#Override
public void seekBarChange(int id) {
// TODO Auto-generated method stub
textView.setTextSize(id);
}
}
public static class SimpleViewPagerAdapter extends
FragmentStatePagerAdapter implements OnPageChangeListener {
private String[] content;
private ViewPager pager;
private TextView counter;
public SimpleViewPagerAdapter(FragmentManager fm, ViewPager pager,
String[] content, TextView counter) {
super(fm);
this.pager = pager;
this.content = content;
this.counter = counter;
}
#Override
public Fragment getItem(int position) {
SimpleFragment fragment = new SimpleFragment();
Bundle bundle = new Bundle();
int index = position;
bundle.putString("content", content[index]);
fragment.setArguments(bundle);
return fragment;
}
#Override
public int getCount() {
return content.length;
}
#Override
public void onPageSelected(int position) {
}
private String makeCounterText(int pageNo) {
return "Page " + pageNo + " of " + content.length;
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
}
}
Interface
package com.creativei.viewpagerloop;
public interface Interface {
public void seekBarChange(int id);
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.creativei.viewpagerloop.MainActivity"
tools:ignore="MergeRootFrame" >
<SeekBar
android:id="#+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/counter"
android:layout_below="#+id/seekBar1" />
<TextView
android:id="#+id/counter"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:gravity="center_horizontal" />
</RelativeLayout>
fragment_main.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: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="com.creativei.viewpagerloop.SimpleFragment" >
<TextView
android:id="#+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
You can get reference from this example http://sampleprogramz.com/android/seekbar.php

Categories

Resources