At the moment I have MainActivity with 2 tabs(with two fragments) and Navigation View with 3 items of menu.
I have only one activity with tabs for now. In MainActivity I have initialization of a Toolbar, NavigationView, ViewPager, TabLayout. Also I have one instance of adapter here, which create fragments for tabs.
When I select one of menu's item, I want it to open a new fragment with two other tabs (with two other fragments).
How can realize it with fragments?
Or better use additional Activity?
NavigationView
MainActivity with two tabs
activity_main_xml:
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
/>
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="#android:color/white"
app:tabIndicatorHeight = "6dp"
app:tabSelectedTextColor="#android:color/white"
app:tabTextColor="#android:color/white"
/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/navigationView"
android:layout_gravity="start"
app:headerLayout="#layout/navigation_header"
app:menu="#menu/menu_navigation"
/>
MainActivity:
package ru.alexbykov.sailesstat;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import ru.alexbykov.sailesstat.statistic.adapter.TheSalesTabsFragmentAdapter;
public class MainActivity extends AppCompatActivity {
private static final int LAYOUT = R.layout.activity_main;
DrawerLayout drawerLayout;
Toolbar toolbar;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.AppDefault);
super.onCreate(savedInstanceState);
setContentView(LAYOUT);
setupToolBar();
setupNavigationView();
setupTabs();
}
private void setupToolBar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(R.string.app_name);
}
private void setupNavigationView() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
ActionBarDrawerToggle togle =
new ActionBarDrawerToggle(
this,
drawerLayout,
toolbar,
R.string.view_navigation_open,
R.string.view_navigation_close);
// drawerLayout.setDrawerListener(togle);
togle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
drawerLayout.closeDrawers();
switch (item.getItemId())
{
}
return true;
}
});
}
/* private void startTendersFragment() {
fTrans = getSupportFragmentManager().beginTransaction();;
TendersFragment tendersFragment = new TendersFragment();
fTrans
.add(R.id.frameLayout, tendersFragment)
.addToBackStack(null)
.commit();
}*/
private void setupTabs() {
viewPager = (ViewPager) findViewById(R.id.viewPager);
TheSalesTabsFragmentAdapter adapter = new TheSalesTabsFragmentAdapter(this, getSupportFragmentManager());
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
}
}
TheSalesTabsFragmentAdapter
package ru.alexbykov.sailesstat.statistic.adapter;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.HashMap;
import java.util.Map;
import ru.alexbykov.sailesstat.statistic.fragments.AbstractTabFragment;
import ru.alexbykov.sailesstat.statistic.fragments.fragmentsTheSale.ManagersFragment;
import ru.alexbykov.sailesstat.statistic.fragments.fragmentsTheSale.PlanFragment;
/**
* Created by Alexey on 09.06.2016.
*/
public class TheSalesTabsFragmentAdapter extends FragmentPagerAdapter {
//for use strings
private Context context;
private Map<Integer, AbstractTabFragment> tabs;
public TheSalesTabsFragmentAdapter(Context context, FragmentManager fm) {
super(fm);
this.context = context;
initTabs();
}
#Override
public Fragment getItem(int position) {
return tabs.get(position);
}
#Override
public int getCount() {
return tabs.size();
}
#Override
public CharSequence getPageTitle(int position) {
return tabs.get(position).getTitle();
}
private void initTabs() {
tabs = new HashMap<>();
tabs.put(0, PlanFragment.getInstance(context));
tabs.put(1, ManagersFragment.getInstance(context));
}
}
ManagersFragment
package ru.alexbykov.sailesstat.statistic.fragments;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.view.View;
public class AbstractTabFragment extends Fragment {
private String title;
protected Context context;
protected View view;
public void setTitle(String title) {
this.title = title;
}
public void setContext(Context context) {
this.context=context;
}
public String getTitle() {
return title;
}
}
PlanFragment
package ru.alexbykov.sailesstat.statistic.fragments.fragmentsTheSale;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import ru.alexbykov.sailesstat.R;
import ru.alexbykov.sailesstat.statistic.fragments.AbstractTabFragment;
/**
* A simple {#link Fragment} subclass.
*/
public class PlanFragment extends AbstractTabFragment {
private static final int LAYOUT = R.layout.fragment_plan;
public static PlanFragment getInstance(Context context) {
/* Bundle bundle = new Bundle();
fragment.setArguments(bundle);*/
PlanFragment fragment = new PlanFragment();
fragment.setContext(context);
fragment.setTitle(context.getString(R.string.tab_plan_stat_fragment));
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(LAYOUT, container, false);
return view;
}
}
AbstractTabFragment
package ru.alexbykov.sailesstat.statistic.fragments;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.view.View;
public class AbstractTabFragment extends Fragment {
private String title;
protected Context context;
protected View view;
public void setTitle(String title) {
this.title = title;
}
public void setContext(Context context) {
this.context=context;
}
public String getTitle() {
return title;
}
}
First off fragments are not the best practice ever as are NavigationViews. I would recommend buttons to switch activities with no use of fragments at all. If I understand you right you have your main page with content, in which I would add three buttons, each with an intent to start another activity in leiu of a NavigationView. Each of these activities would have their own buttons which would lead you to whatever activity you want to go to from there.
You can add new fragment and inside that add viewpager2. May be this will help you.
http://logicrider.com/blogs/viewpager2_with_fragments_and_tablayout_android_studio.php
Related
I am facing a problem with my custom appbar in my fragment where nothing happens when I click any item in my appbar. I have followed this document to create an appbar in my fragment but still so success.
I have one activity that contains only a fragment container which I switch between fragments from. In one of fragments I want to add a custom fragment owned appbar. I first created a menu like this:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/settings"
android:title="Settings"
android:icon="#drawable/ic_settings"
app:showAsAction="never">
</item>
<item
android:id="#+id/about"
android:title="About"
android:icon="#drawable/ic_about"
app:showAsAction="never">
</item>
<item
android:id="#+id/logout"
android:title="Logout"
android:icon="#drawable/ic_logout"
app:showAsAction="never">
</item>
</menu>
then in my profile.xml I added a toolbar like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
tools:context=".MainFragments.AddFragment">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/Bar_profile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="#color/darkBlue"
app:layout_scrollFlags="scroll|snap|exitUntilCollapsed">
//alot of code in between....
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar_prof"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="#style/ThemeOverlay.AppCompat.Dark" />
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
//more stuff implemented
</RelativeLayout>
however, my menu does not get inflated and if i inflate it via xml nothing happens when I click on any item, what is wrong? Thanks!
here is how my profile fragment looks like:
Edit
here is full profilefragment.java:
package se.umu.moad0012.myservice.MainFragments;
import se.umu.moad0012.myservice.Adapters.FragmentPagerAdapter;
import se.umu.moad0012.myservice.MainActivity;
import se.umu.moad0012.myservice.Models.User;
import se.umu.moad0012.myservice.ProfileFragments.AboutFragment;
import se.umu.moad0012.myservice.ProfileFragments.SettingsFragment;
import se.umu.moad0012.myservice.R;
import se.umu.moad0012.myservice.StartFragments.LoginFragment;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupMenu;
import android.widget.TextView;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.makeramen.roundedimageview.RoundedImageView;
public class ProfileFragment extends Fragment {
private RoundedImageView mProfileRoundedImageView;
private TextView mPosts, mFollowers, mFollowing, mUserName;
private TabLayout mTabLayout;
private String profileId;
private FirebaseDatabase mFirebaseDatabase;
private ViewPager2 mViewPager2;
private final String[] titles = new String[]{"Posts", "Reviews"};
private final int[] icons = new int[]{R.drawable.ic_grid, R.drawable.feedback};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_profile, container, false);
//declare variables
declareVariables(v);
//adapter for viewpager2
mViewPager2.setAdapter(new FragmentPagerAdapter(this));
//configure tabs here
tabMediator();
//FirebaseAuth.getInstance().signOut();
//set profile info
setProfileInfo();
return v;
}
private void tabMediator() {
new TabLayoutMediator(mTabLayout, mViewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
tab.setText(titles[position]);
tab.setIcon(icons[position]);
}
}).attach();
}
private void setProfileInfo() {
mFirebaseDatabase.getReference().child("Users").child(profileId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
mUserName.setText(user.getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void declareVariables(View v) {
mViewPager2 = v.findViewById(R.id.viewpager_profile);
mTabLayout = v.findViewById(R.id.tabLayout_profile);
mFirebaseDatabase = FirebaseDatabase.getInstance();
mUserName = v.findViewById(R.id.userNameProfileFragment);
mFollowers = v.findViewById(R.id.followers);
mPosts = v.findViewById(R.id.posts);
mFollowing = v.findViewById(R.id.following);
//mProfileRoundedImageView = v.findViewById(R.id.profileImage);
FirebaseUser fUser = FirebaseAuth.getInstance().getCurrentUser();
profileId = fUser.getUid();
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar_prof);
toolbar.inflateMenu(R.menu.popup_menu_profile);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.settings:
Log.d("TAG", "onOptionsItemSelected: settings");
return true;
case R.id.about:
Log.d("TAG", "onOptionsItemSelected: about");
return true;
case R.id.logout:
Log.d("TAG", "onOptionsItemSelected: logout");
return true;
}
return false;
}
});
}
}
Edit2
I have noticed just now that it works, just that my text is white and thus does not show up. Sorry for any inconvenience.
Put this in your fragment
public class ProfileFragment extends Fragment {
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Toolbar toolbar = view.findViewById(R.id.my_toolbar);
toolbar.inflateMenu(R.menu.your_menu);
toolbar.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
//handle click
return true;
case R.id.new_pic:
// handle here
return true;
default:
return false;
}
}
});
}
}
all. I'm having a problem.
I am trying to make an application, wherein a navigation-drawer is the source of navigation. In this application, I have some fragments with activities. The problem is, that if I run my profile fragment (which have uses tablayout and recyclerview) in an application for itself, it works. The application when it runs in it's own application.
However, when I attempt to add it to an application, wherein it should be a fragment in a navigation drawer, the application can compile, but when I click on the menuitem in the emulator, it crashes.
I will add the code I have at the moment:
Main Activity
import android.view.MenuItem;
import android.view.View;
import android.view.Menu;
import android.content.Intent;
import com.example.sustainably.ui.myprofile.MainActivityProfile;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.core.view.GravityCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_friends, R.id.nav_messages, R.id.nav_bookmarks, R.id.nav_myprofile, R.id.nav_discoverforums, R.id.nav_settings, R.id.nav_logout)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
public boolean onNavigationItemSelected(MenuItem item) {
NavigationView navigationView = (NavigationView)findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id = menuItem.getItemId();
switch (menuItem.getItemId()) {
case R.id.nav_home:
// code here
break;
case R.id.nav_friends:
// code here
break;
case R.id.nav_messages:
// code here
break;
case R.id.nav_bookmarks:
// code here
break;
case R.id.nav_myprofile:
Intent intent=new Intent(MainActivity.this, MainActivityProfile.class);
startActivity(intent);
break;
case R.id.nav_discoverforums:
//code here
break;
case R.id.nav_settings:
//code here
break;
case R.id.nav_logout:
//code here
break;
}
DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
return false;
}
}
and in the profile fragment package i have 6 java classes:
BookmarkModel.java
private String Title;
private int Photo;
public BookmarkModel() {
}
public BookmarkModel(String title, int photo) {
Title = title;
Photo = photo;
}
// Getter
public String getTitle() {
return Title;
}
public int getPhoto() {
return Photo;
}
// Setter
public void setTitle(String title) {
Title = title;
}
public void setPhoto(int photo) {
Photo = photo;
}
}
MainActivityProfile.java
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import com.example.sustainably.R;
import com.google.android.material.tabs.TabLayout;
public class MainActivityProfile extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_myprofile);
tabLayout = (TabLayout) findViewById(R.id.tablayout_id);
viewPager = (ViewPager) findViewById(R.id.viewpager_id);
adapter = new ViewPagerAdapter(getSupportFragmentManager());
// Add Fragment Here
adapter.AddFragment(new PublicBookmarkFragment(), "Public Bookmarks");
adapter.AddFragment(new LatestPostsFragment(), "Latest Posts");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_outline_bookmarks_24);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_outline_textsms_24);
}
}
PublicBookmarkFragment
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.sustainably.R;
import java.util.ArrayList;
import java.util.List;
public class PublicBookmarkFragment extends Fragment {
View v;
private RecyclerView myrecyclerview;
private List<BookmarkModel> lstBookmarkModel;
public PublicBookmarkFragment() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.public_bookmarks_fragment, container, false);
myrecyclerview = (RecyclerView) v.findViewById(R.id.bookmarks_recyclerview);
RecyclerViewAdapter recyclerAdapter = new RecyclerViewAdapter(getContext(), lstBookmarkModel);
myrecyclerview.setLayoutManager(new GridLayoutManager(getContext(), 2));
myrecyclerview.setAdapter(recyclerAdapter);
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lstBookmarkModel = new ArrayList<>();
lstBookmarkModel.add(new BookmarkModel("Salad", R.drawable.annapelzer));
lstBookmarkModel.add(new BookmarkModel("Pasta", R.drawable.brookelark_1));
lstBookmarkModel.add(new BookmarkModel("Fruit Salad", R.drawable.brookelark_2));
lstBookmarkModel.add(new BookmarkModel("Smoothies with fruit", R.drawable.brookelark_3));
lstBookmarkModel.add(new BookmarkModel("Soup", R.drawable.cala));
lstBookmarkModel.add(new BookmarkModel("Lobster Salad", R.drawable.davide_cantelli));
lstBookmarkModel.add(new BookmarkModel("Breakfast Toast with Berries", R.drawable.joseph_gonzales));
}
}
RecyclerViewAdapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.sustainably.R;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
Context mContext;
List<BookmarkModel> mData;
public RecyclerViewAdapter(Context mContext, List<BookmarkModel> mData) {
this.mContext = mContext;
this.mData = mData;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(mContext).inflate(R.layout.item_bookmarks, parent, false);
MyViewHolder vHolder = new MyViewHolder(v);
return vHolder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.tv_title.setText(mData.get(position).getTitle());
holder.img.setImageResource(mData.get(position).getPhoto());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private TextView tv_title;
private ImageView img;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
tv_title = (TextView) itemView.findViewById(R.id.title_bookmarks);
img = (ImageView) itemView.findViewById(R.id.img_bookmarks);
}
}
}
ViewPagerAdapter
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> lstFragment = new ArrayList<>();
private final List<String> lstTitles = new ArrayList<>();
public ViewPagerAdapter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
return lstFragment.get(position);
}
#Override
public int getCount() {
return lstTitles.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return lstTitles.get(position);
}
public void AddFragment (Fragment fragment, String title) {
lstFragment.add(fragment);
lstTitles.add(title);
}
}
fragment_myprofile.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/myprofile"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<include
layout="#layout/profile_header"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/TabContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tablayout_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabIconTint="#color/dark_green"
app:tabIndicatorColor="#color/dark_green"
app:tabInlineLabel="true"
app:tabMode="fixed"
app:tabRippleColor="#color/light_green"
app:tabSelectedTextColor="#color/dark_green"
app:tabTextAppearance="#style/TextAppearance.AppCompat.Small"></com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewpager_id"></androidx.viewpager.widget.ViewPager>
</LinearLayout>
</LinearLayout>
public_bookmarks_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="wrap_content"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/bookmarks_recyclerview">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
item_bookmarks.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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardUseCompatPadding="true"
app:cardCornerRadius="8dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/img_bookmarks"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="#mipmap/ic_launcher"
android:scaleType="centerCrop" />
<TextView
android:id="#+id/title_bookmarks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#color/dark_green"
android:padding="5dp"
android:text="#string/title"
android:textSize="16sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
I'm new at asking questions in here, so if I missed some information you need, or messed something up, please tell me what you need, and I will provide that aswell. Hope you can help.
For clarification as requested:
Logcat errormessages when I click on the menu
2021-05-06 15:28:54.971 18053-18053/com.example.sustainably E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sustainably, PID: 18053
java.lang.ClassCastException: com.example.sustainably.ui.myprofile.MainActivityProfile cannot be cast to androidx.fragment.app.Fragment
at androidx.fragment.app.Fragment.instantiate(Fragment.java:548)
at androidx.fragment.app.FragmentContainer.instantiate(FragmentContainer.java:57)
at androidx.fragment.app.FragmentManager$3.instantiate(FragmentManager.java:390)
at androidx.navigation.fragment.FragmentNavigator.instantiateFragment(FragmentNavigator.java:132)
at androidx.navigation.fragment.FragmentNavigator.navigate(FragmentNavigator.java:162)
at androidx.navigation.fragment.FragmentNavigator.navigate(FragmentNavigator.java:58)
at androidx.navigation.NavController.navigate(NavController.java:1066)
at androidx.navigation.NavController.navigate(NavController.java:944)
at androidx.navigation.NavController.navigate(NavController.java:877)
at androidx.navigation.ui.NavigationUI.onNavDestinationSelected(NavigationUI.java:97)
at androidx.navigation.ui.NavigationUI$3.onNavigationItemSelected(NavigationUI.java:453)
at com.google.android.material.navigation.NavigationView$1.onMenuItemSelected(NavigationView.java:217)
at androidx.appcompat.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:834)
at androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:985)
at com.google.android.material.internal.NavigationMenuPresenter$1.onClick(NavigationMenuPresenter.java:416)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
mobile_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/mobile_navigation"
app:startDestination="#+id/nav_home">
<fragment
android:id="#+id/nav_home"
android:name="com.example.sustainably.ui.home.HomeFragment"
android:label="#string/menu_home"
tools:layout="#layout/fragment_home" />
<fragment
android:id="#+id/nav_friends"
android:name="com.example.sustainably.ui.friends.FriendsFragment"
android:label="#string/menu_friends"
tools:layout="#layout/fragment_friends" />
<fragment
android:id="#+id/nav_bookmarks"
android:name="com.example.sustainably.ui.bookmarks.BookmarksFragment"
android:label="#string/menu_bookmarks"
tools:layout="#layout/fragment_bookmarks" />
<fragment
android:id="#+id/nav_myprofile"
android:name="com.example.sustainably.ui.myprofile.profileRecycle.MyProfileFragment"
android:label="#string/menu_myprofile"
tools:layout="#layout/fragment_myprofile" />
<fragment
android:id="#+id/nav_discoverforums"
android:name="com.example.sustainably.ui.discoverforums.DiscoverForumsFragment"
android:label="#string/menu_discoverforums"
tools:layout="#layout/fragment_discoverforums" />
<fragment
android:id="#+id/nav_messages"
android:name="com.example.sustainably.ui.messages.MessagesFragment"
android:label="#string/menu_messages"
tools:layout="#layout/fragment_messages" />
</navigation>
The code in it's entirety: https://github.com/CabCabz/SustainablyProblem.git
suggestion:
I analyzed your code, you should not used default navigation drawer setup with mobile_navigation.xml.
Setup drawer menu without mobile_navigation.xml: https://stackoverflow.com/a/67389269/12660050
Solution:
1) As you are using default drawer with mobile_navigation.xml you do not need to
use onNavigationItemSelected() method. So, before doing anything remove it from
your Main Activity.
2) Go to the mobile_navigation.xml file and change tag name fragment to activity in which you are using as a MainActivityProfile.java.
Before:
<fragment
android:id="#+id/nav_myprofile"
android:name="com.example.sustainably.ui.myprofile.profileRecycle.MyProfileFragment"
android:label="#string/menu_myprofile"
tools:layout="#layout/fragment_myprofile" />
After:
<activity
android:id="#+id/nav_myprofile"
android:name="com.example.sustainably.ui.myprofile.profileRecycle.MyProfileFragment"
android:label="#string/menu_myprofile"
tools:layout="#layout/fragment_myprofile" />
By changing only this you can solve your problem!!
I have created an ImageSlider as a new activity seperate to my main project in order to see if it worked. Well guess what, it does! The problem is it is activity based, and when I try and implement it into my other project which has fragments I get so many errors within my MainActivity. Could someone help me please? I believe the issue might be related to my main project also having a navigation drawer & a fragment within the MainActivity main page of the app.
MainActivity test project code which works:
package com.example.user1.imageslidertest;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
LinearLayout sliderDotspanel;
private int dotscount;
private ImageView[] dots;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.ViewPager);
sliderDotspanel = (LinearLayout) findViewById(R.id.SliderDots);
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(this);
viewPager.setAdapter(viewPagerAdapter);
dotscount = viewPagerAdapter.getCount();
dots = new ImageView[dotscount];
for(int i = 0; i < dotscount; i++){
dots[i] = new ImageView(this);
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.nonactive_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
sliderDotspanel.addView(dots[i], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for(int i = 0; i< dotscount; i++){
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.nonactive_dot));
}
dots[position].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
ViewPagerAdapter code:
package com.example.user1.imageslidertest;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ViewPagerAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
private Integer [] images = {R.drawable.a45large, R.drawable.a45largeintior, R.drawable.a45largerear};
public ViewPagerAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return images.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.custom_layout, null);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
imageView.setImageResource(images[position]);
ViewPager vp = (ViewPager) container;
vp.addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
activity_main.xml code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.user1.imageslidertest.MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/ViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
<LinearLayout
android:id="#+id/SliderDots"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/ViewPager"
android:gravity="center_vertical|center_horizontal"
android:orientation="horizontal"
android:paddingTop="300dp">
</LinearLayout>
</android.support.constraint.ConstraintLayout>
custom_layout.xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="292dp"
app:srcCompat="#drawable/a45large" />
</LinearLayout>
My MainActivity from my main project with fragments and navigation drawer (where the issues are when I put the test MainActivity code in):
package com.example.user1.mainproject;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// Code to display Home Fragment on App Launch Page
HomeFragment homeFragment = new HomeFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(
R.id.relativelayout_for_fragment,
homeFragment,
homeFragment.getTag()
).commit();
}
This is the biggest issue I've faced within my project so would really apreciate some help, thanks!
Sorry for the code dump, I'm new to android and don't know where the problem is. I'm trying to implement swipe views in my android app and I'm having some trouble. I tried following this tutorial and this video but I'm getting some errors. I want the tabbed interface in my MainActivity
Here is my MainActivity.java
package com.loomius.loomius;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
PagerAdapter pagerAdapter = new FixedTabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
}
}
I'm getting this error for getSupporFragmentManager()
'FixedTabsPagerAdapter(android.app.FragmentManager)' in 'com.loomius.loomius.FixedTabsPagerAdapter' cannot be applied to '(android.support.v4.app.FragmentManager)'
and here is my FixedTabsPagerAdapter.java
package com.loomius.loomius;
import android.app.FragmentManager;
import android.content.Context;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.app.Fragment;
import values.MatchesFragment;
import values.SuggestedSongsFragment;
import values.UserFragment;
public class FixedTabsPagerAdapter extends FragmentPagerAdapter{
public FixedTabsPagerAdapter (FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 4;
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
return new SearchFragment();
case 1:
return new UserFragment();
case 2:
return new MatchesFragment();
case 3:
return new SuggestedSongsFragment();
default:
return null;
}
}
Context context;
#Override
public CharSequence getPageTitle (int position) {
switch(position) {
case 0:
return context.getResources().getString(R.string.search_frag_title);
case 1:
return context.getResources().getString(R.string.user_frag_title);
case 2:
return context.getResources().getString(R.string.matches_frag_title);
case 3:
return context.getResources().getString(R.string.sugg_frag_title);
default:
return null;
}
}
}
I'm getting this error for the return type Fragment in the overridden method getItem
'getItem(int)' in 'com.loomius.loomius.FixedTabsPagerAdapter' clashes with 'getItem(int)' in 'android.support.v13.app.FragmentPagerAdapter'; attempting to use incompatible return type
I put the android.support.v4.view.ViewPager widget in my activity_main.xml right below the android.support.v7.widget.Toolbar widget.
Look at your FixedTabPagerAdapter constructor, you are trying to catch the reference of android.app.FragmentManager instance while passing the fragment manager of type android.support.v4.app.FragmentManagerwhich are two different classes.
Change the type of FragmentManager in your FixedTabPageAdapter to android.support.v4.app.FragmentManager and it should fix the issue.
For sliding pages with tabs do following.
Download or copy following two files on github and paste your project.
this is same as on developers.google.com except setDistributeEvenly method.
https://github.com/google/iosched/blob/master/android/src/main/java/com/google/samples/apps/iosched/ui/widget/SlidingTabLayout.java
https://github.com/google/iosched/blob/master/android/src/main/java/com/google/samples/apps/iosched/ui/widget/SlidingTabStrip.java
activity_main.xml
<your.package.name.SlidingTabLayout
android:clickable="true"
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</your.package.name.SlidingTabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
MyAdapter.java (Here i used two pages only)
class MyPagerAdapter extends FragmentPagerAdapter
{
String[] title = {"All","Favourites"};
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment=null;
if (position==0)
fragment= new All();
if (position==1)
fragment= new Favourites();
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return title[position];
}
}
tab_view.xml (view of tab only , if you want u can also use ImageView here)
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/tab_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text=""
android:padding="15dp"
android:textStyle="bold"
android:textSize="25dp"
/>
</FrameLayout>
MainActivity.java
private SlidingTabLayout tabLayout;
private ViewPager pager;
tabLayout= (SlidingTabLayout) findViewById(R.id.tabs);
pager = (ViewPager) findViewById(R.id.pager);
tabLayout.setCustomTabView(R.layout.tab_view,R.id.tab_title);
MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
tabLayout.setDistributeEvenly(true);
tabLayout.setViewPager(pager);
I create a little app with 3 static fragments and a view pager adapter. But what I want is to create Only one kind of fragment and with a button "add" , add other fragment which will be adapted by the view pager.. here is what i have done
FragmentTab1.java ; FragmentTab2 ; FragmentTab3 have the same code
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentTab2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab2.xml
View view = inflater.inflate(R.layout.fragmenttab2, container, false);
return view;
}
}
here is my MainActivity.java
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends FragmentActivity {
//Button adfg = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
setContentView(R.layout.activity_main);
// Locate the viewpager in activity_main.xml
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
// Set the ViewPagerAdapter into ViewPager
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
}
}
ViewPagerAdapter.java
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class ViewPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3;
// Tab Titles
private String tabtitles[] = new String[] { "Tab1", "Tab2", "Tab3" };
Context context;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
switch (position) {
// Open FragmentTab1.java
case 0:
FragmentTab1 fragmenttab1 = new FragmentTab1();
return fragmenttab1;
// Open FragmentTab2.java
case 1:
FragmentTab2 fragmenttab2 = new FragmentTab2();
return fragmenttab2;
// Open FragmentTab3.java
case 2:
FragmentTab3 fragmenttab3 = new FragmentTab3();
return fragmenttab3;
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabtitles[position];
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.PagerTabStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:textColor="#000000" />
</android.support.v4.view.ViewPager>
fragmenttab1.xml ; fragmenttab2.xml ; fragmenttab3.xml has the same code
<?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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment 1" />
<Button
android:id="#+id/bajou"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ajouter fragment" />
</LinearLayout>
You need to create a method to add the fragment on the subclass of FragmentPagerAdapter, more or less like this :
//use those lists
private List<Fragment> listFragment = new ArrayList<Fragment>();
private List<String> listFragmentTitle = new ArrayList<String>();
private List<Integer> listFragmentIcon = new ArrayList<Integer>();
public void addTab(Fragment fragment,String title, int icon) {
listFragment.add(fragment);
listFragmentTitle.add(title);
listFragmentIcon.add(icon);
}
#Override
public Fragment getItem(int position) {
// TODO Auto-generated method stub
return listFragment.get(position);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listFragment.size();
}
Then you just need to use it on the subclass of Activity, example :
//create a private method to set a new - dynamic fragment in the ACTIVITY
private Fragment setFragment(int pos)
{
MyFragment myFragment = new MyFragment();
Bundle data = new Bundle();
data.putString("test", "test");
myFragment.setArguments(data);
return myFragment;
}
Finally, add the fragment (for example, inside an onClickListener) :
//INSIDE an onClickListener
pagerAdapter.addTab(setFragment(position), getItem(position).getName(), R.drawable.ic_launcher);
this is my MainActivity.java class #BlazeTama
package com.light.frag;
import com.light.frag.R;
import com.light.frag.ViewPagerAdapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends FragmentActivity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Locate the viewpager in activity_main.xml
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
// Set the ViewPagerAdapter into ViewPager
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
Button ajou = (Button) findViewById(R.id.bajou);
ajou.setOnClickListener(this);
}
private Fragment setFragment(int pos)
{
MyFragment myFragment = new MyFragment();
Bundle data = new Bundle();
data.putString("test", "test");
myFragment.setArguments(data);
return myFragment;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bajou:
ViewPagerAdapter.addTab(setFragment(position), getItem(position).getName(), R.drawable.ic_launcher);
break;
}
}
}