I have a following Fragment class:
public class TabFragment extends Fragment {
....
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_photos_tab, container, false);
TabelAdapter adapt = new TabelAdapter(getActivity().getApplicationContext(), R.layout.list_room_view, flowerList);
setListAdapter(adapt); // Not Working because class is not extended by ListActivity
return view;
}
TabelAdapter class
public class TabelAdapter extends ArrayAdapter<Flower> {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (null == convertView) {
convertView = inflater.inflate(R.layout.list_flower_view, parent, false);
}
Picasso
.with(context)
.load("http://i.imgur.com/rFLNqWI.jpg")
.fit()
.into((ImageView) convertView);
return convertView;
}
list_flower_view.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Flowerimg"
android:layout_width="match_parent"
android:layout_height="200dp"/>
activity_home.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" tools:context=".MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#android:id/list"></ListView>
</RelativeLayout>
When I was working with activity instead of fragment then the whole process was very simple. I extend MainActivity class with ListActivity and add setContentView(R.layout.activity_home); into MainActivity.OnCreate(). I can see the list of Images in ListView.
Question
How to make setListAdapter usable in Fragment class? I am newbie in Android. Any help will be appreciable :)
Edit-1
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
TabFragment photo = new TabFragment();
return photo; // Line (30,24)
} ......
}
If I use ListFragment instead of Fragment then PagerAdapter class os throwing an Error.
Error:(30, 24) error: incompatible types: TabFragment cannot be converted to Fragment
Edit-2
java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
Change Fragment to ListFragment:
public class TabFragment extends ListFragment {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
TabelAdapter adapt = new TabelAdapter(getActivity().getApplicationContext(), R.layout.list_room_view, flowerList);
setListAdapter(adapt);
}
...
}
ListFragment documentation
Tutorial
Related
Below recycler view code is working fine and I can Toast message what recycler view position was selected in RecycleAdapter class. But I want to know how can I get what recycler position selected in HomeFragment class?. I tried to get position by setting onclick listener to Imageview and Textview but gives error as reference to Null. Basically I want to use get(getAbsoluteAdapterPosition() in HomeFragment class to know what item selected and navigate to another Fragment. get(getAbsoluteAdapterPosition() is working as expected inside RecycleAdapter.class
binding.recyclerview.setOnClickListener is not working in HomeFragment.class. no error but no when I click on recycler views this is not shooted.
txt.setOnClickListener is giving error as null refernce which makes sense. because this is inflated in Adapter class but trying to refer in HomeFragement class. So how can I get what selected in homefragment.class. Thanks in advance
HomeFragment.class
'''
public class HomeFragment extends Fragment {
HomeFragmentBinding binding;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.id.home_fragment, container, false);
return v;
}
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
%% some code here %%
recycleAdapter = new RecycleAdapter(list);
binding.recyclerview.setAdapter(recycleAdapter);
TextView txt = (TextView) binding.getRoot().findViewById(R.id.recycler_text);
txt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "Clicked on Image", Toast.LENGTH_SHORT).show();
}
});
binding.recyclerview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "RecyclerView clicked", Toast.LENGTH_SHORT).show();
Log.d("RecyclerViewclicked", " --- ");
}
});
'''
RecycleAdapter.class
'''
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.MyViewHolder>{
RecyclerRowItemsBinding binding;
List<IconsModel> iconsList;
public RecycleAdapter(List<IconsModel> iconslist) {
this.iconsList = iconslist;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflator = LayoutInflater.from(parent.getContext());
View v = inflator.inflate(R.layout.recycler_row_items, parent, false);
MyViewHolder myviewholder = new MyViewHolder(v);
return myviewholder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
IconsModel iconModel = iconsList.get(position);
holder.imageView.setImageResource(iconModel.getImageid());
holder.recyclertext.setText(iconModel.getIconName());
}
#Override
public int getItemCount() {
//return 20;
return iconsList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
TextView recyclertext;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.recycler_image);
recyclertext = itemView.findViewById(R.id.recycler_text);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IconsModel iconModel = iconsList.get(getAbsoluteAdapterPosition());
Toast.makeText(***itemView.getContext(), "Clicked on "+iconModel.getIconName()***, Toast.LENGTH_SHORT).show();
}
});
}
}
;
}
'''
home_fragment.xml
<androidx.constraintlayout.widget.ConstraintLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="1dp"
tools:layout_editor_absoluteY="1dp"
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"/>
</androidx.constraintlayout.widget.ConstraintLayout>
'''
recycler_row.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
android:layout_gravity="center"
android:layout_margin="5dp"
android:orientation="horizontal"
app:cardCornerRadius="5dp"
app:cardElevation="5dp"
app:cardBackgroundColor="#color/home_bg_cardview">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:backgroundTint="#color/home_bg_cardview"
android:weightSum="2">
<ImageView
android:id="#+id/recycler_image"
android:layout_width="0dp"
android:layout_height="120dp"
android:layout_weight="0.5"
app:srcCompat="?android:attr/actionModeWebSearchDrawable"
tools:ignore="ContentDescription" />
<TextView
android:id="#+id/recycler_text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginBottom="29dp"
android:layout_weight="1.5"
android:gravity="center"
android:text="Browse Items"
android:textAlignment="center"
android:textSize="24sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
If you want to get the click event of recyclerview item in HomeFragment ,
Interface It's a good choice
//RecycleAdapter
private RecyclerViewListener recyclerViewListener
public void setRecyclerViewListener(RecyclerViewListener recyclerViewListener){
this.RecyclerViewListener recyclerViewListener ;
}
public Interface RecyclerViewListener{
void onClick(View view);
}
class MyViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
TextView recyclertext;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
recyclertext = itemView.findViewById(R.id.recycler_text);
recyclertext .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(recyclerViewListener !=null)recyclerViewListener.onClick(v)
}
});
}
//HomeFragment
recycleAdapter.setRecyclerViewListener(new RecyclerViewListener{
#Override
public void onClick(View v) {
//todo
}
})
Create Interface Class in your Project
public interface ItemClick {
public void onClick(IconsModel IconsModel,int pos);
}
Interface class call your recyclerAdapter
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.MyViewHolder> {
Context context;
List<IconsModel> iconsList;
ItemClick click;
public TokensListAdapter(Context context, List<IconsModel> iconsList, ItemClick click) {
this.context = context;
this.tokensModelList = tokensModelList;
this.click = click;
}
#NonNull
#Override
public TokensListAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.R.layout.recycler_row_items,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull TokensListAdapter.ViewHolder holder, int position) {
IconsModel iconModel = iconsList.get(position);
holder.imageView.setImageResource(iconModel.getImageid());
holder.recyclertext.setText(iconModel.getIconName());
holder.itemView.setOnClickListener(v -> {
click.onClick(iconModel,position);
});
}
#Override
public int getItemCount() {
return iconsList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView recyclertext;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.recycler_image);
recyclertext = itemView.findViewById(R.id.recycler_text);
}
}
}
Interface Class implement Your Fragment
public class HomeFragment extends Fragment implements ItemClick {
//adapter assign
recycleAdapter = new RecycleAdapter(getContext,list,this);
override method import your fragment
#Override
public void onClick(ItemCLick click, int pos) {
Toast.makeText(getContext(), "Clicked" + pos, Toast.LENGTH_SHORT).show();
}
So I have my main Bottom Navigation Activity, and there is three section one of which is dashboard. And I want to make a grid of categories in there. I've been trying to follow some guides on youtube about creation of GridView, but it seems to not work in this Bottom Navigation Activity. The main issue is that in my custom adapter in method getView it can't resolve R.layout.category_item but the file exists.
I would be grateful for some workaround or explanation of why it happens.
DashboardFragment class:
public class DashboardFragment extends Fragment {
private DashboardViewModel dashboardViewModel;
String[] category_names = {"one","two","three","four","five","six","seven","eight","nine","ten"};
int[] data ={1,2,3,4,5,6,7,8,9,10};
GridView gridView;
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
dashboardViewModel = ViewModelProviders.of(this).get(DashboardViewModel.class);
View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
dashboardViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
}
});
gridView = root.findViewById(R.id.category_grid);
CustomAdapter customAdapter = new CustomAdapter();
gridView.setAdapter(customAdapter);
return root;
}
private class CustomAdapter extends BaseAdapter{
#Override
public int getCount() {
return category_names.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view1 = getLayoutInflater().inflate(R.layout.category_item,null);
return null;
}
}
}
category_item.xml :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".ui.dashboard.DashboardFragment">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</androidx.constraintlayout.widget.ConstraintLayout>
Hi i don't know if it's the solution of your problem but you don't use any context when you inflate your view
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// inflate the layout for each list row
if (convertView == null) {
convertView = LayoutInflater.from(context).
inflate(R.layout.layout_list_view_row_items, parent, false);
}
...
}
i am using "compile 'com.android.support:design:25.1.0'" to implement swipe tablayout. My code has no syntax error but due to some logical error it is not working correctly
Problems: 1) when i slide a page it should move on next tab but it slide or move very slowly and go between two tabs
2) when i come back on privious tabs sometime it does not show even any page and sometime it show wrong page e.g on second tabs it shows third page(fragment)
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabLayout tabLayout;
String[] tabs={"SCORES","NEWS","SERIES"};
tabLayout=(TabLayout) findViewById(R.id.cricTabLayout);
tabLayout.addTab(tabLayout.newTab().setText(tabs[0]));
tabLayout.addTab(tabLayout.newTab().setText(tabs[1]));
tabLayout.addTab(tabLayout.newTab().setText(tabs[2]));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabTextColors(Color.parseColor("#627179"), Color.parseColor("#BF4A32"));
final ViewPager viewPager=(ViewPager)findViewById(R.id.cricPagerView);
final PageAdapter pageAdapter=new PageAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(pageAdapter);
// new line
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
// viewPager.clearOnPageChangeListeners();
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
// Toast.makeText(MainActivity.this,"Tab changed",Toast.LENGTH_LONG).show();
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
PageAdapter.java
public class PageAdapter extends FragmentStatePagerAdapter {
int numOfTabs;
public PageAdapter(FragmentManager fm, int numOfTabs) {
super(fm);
this.numOfTabs=numOfTabs;
}
public PageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
return new ScoreFragment();
case 1:
return new NewsFragment();
case 2:
return new SeriesFragment();
default: return null;
}
}
#Override
public int getCount() {
return numOfTabs;
}
}
ScoreFragment.java
public class ScoreFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=null;
Toast.makeText(getContext(),"Score",Toast.LENGTH_LONG).show();
return view;
}
}
SeriesFragment.java
public class ScoreFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=null;
Toast.makeText(getContext(),"Score",Toast.LENGTH_LONG).show();
return view;
}
}
NewsFragment.java
public class NewsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=null;
Toast.makeText(getContext(),"News",Toast.LENGTH_LONG).show();
return view;
}
}
MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_news"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.apple.crickapp.MainActivity"
android:layout_marginLeft="0dp">
<android.support.design.widget.TabLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:elevation="8dp"
android:background="#color/colorBlack"
android:minHeight="?attr/actionBarSize"
android:id="#+id/cricTabLayout"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
>
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="#+id/cricPagerView"
android:layout_below="#id/cricTabLayout"
>
</android.support.v4.view.ViewPager>
</RelativeLayout>
I'm trying to add viewPager in Fragment. But when I start my application I receive this:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.view.ViewPager.setAdapter(android.support.v4.view.PagerAdapter)' on a null object reference
My MainFragment:
public class YourTasksFragment extends Fragment {
#Bind(R.id.viewpager)
ViewPager viewPager;
#Bind(R.id.tabs)
TabLayout tabLayout;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_your_tasks, container, false);
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "TWO");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager childFragmentManager) {
super(childFragmentManager);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
}
}
Layout:
<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.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
You forgot to setup Butterknife in the onCreateView(), therefore the variable is never initialized.
Do this:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_your_tasks, container, false);
Butterknife.bind(this,v);
return v;
}
Hope it helps!
You forgot to add Butterknife.bind(this, v) on the method onCreateView.
It's required in order to bind the views.
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_your_tasks, container, false);
Butterknife.bind(this,v);
return v;
}
I have a pagerAdapter like this :
public class AppPagerAdapter extends PagerAdapter {
Context context;
public AppPagerAdapter(Context appcon)
{
this.context = context;
}
#Override
public int getCount() {
return 10;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View viewItem = inflater.inflate(R.layout.pager_layout, container, false);
ListView listView = (ListView) viewItem.findViewById(R.id.list);
}
}
And in my XML is this : "pager_layout.xml"
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:wheel="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent">
<ListView
android:layout_width="wrap_content"
android:id="#+id/list"
android:divider="#color/activity_background"
android:layout_height="match_parent">
</ListView>
And, my main fragment page is this :
public class Apps extends Fragment {
public Apps() {}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRoot = inflater.inflate(R.layout.app_activity, container, false);
ViewPager pager = (ViewPager)mRoot.findViewById(R.id.view_pager);
AppPagerAdapter appadapter = new AppPagerAdapter(getActivity());
pager.setAdapter(appadapter);
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }
#Override
public void onPageSelected(int position) {
//Access to this position list view for add adapter
new Loading().execute; //async task to get data and add to list view from this pager
}
#Override
public void onPageScrollStateChanged(int state) {}
});
}
}
Now, How can I access this view on screen page for adding data to this page?
I want to add data to listview of page that is selected.
Please help me .
if your viewpager have 4 fragments: A,B,C,D. And you are open fragment A. Then Fragment B and D will be create automatically by Viewpager.
And if you want to add data to listView. Let see this method:
#Override
public Object instantiateItem(ViewGroup container, int position) {
View viewItem = inflater.inflate(R.layout.pager_layout, container, false);
ListView listView = (ListView) viewItem.findViewById(R.id.list);
}
What is
int position?
It is the Page that you selected - Openning.
Your above code will create 10 Page in ViewPager, each Page have the ListView. If you want to add data to this, only write more code in method
instantiateItem()