Displaying imageslider within a fragment - java

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!

Related

My navigation drawer wont open profile fragment with (recyclerview, tablayout and viewpager inside fragment)

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!!

Does anyone have any idea why I can't press my menu button after entering the login screen?

I have a problem with Java. I am trying to create a simple android app and I get a problem with the navigation menu button. I think the problem is the way that the function is set up and I have looked into threads and synchronize but that doesn't work either this is the code that has the problem.
loginScreen.java
package com.example.myapplication;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.fragment.app.Fragment;
import static android.content.Context.INPUT_METHOD_SERVICE;
import static androidx.core.content.ContextCompat.getSystemService;
public class loginScreen extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.login_screen, container, false);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hideKeyboardFrom(getContext(), getView());
}
});
return view;
}
public static void hideKeyboardFrom(Context context, View view) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
MainActivity.java
package com.example.myapplication;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import com.google.android.material.navigation.NavigationView;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
Toolbar toolbar;
NavigationView navigationView;
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.navigationView);
navigationView.setNavigationItemSelectedListener(this);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
actionBarDrawerToggle.syncState();
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.container_fragment, new MainFragment());
fragmentTransaction.commit();
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
drawerLayout.closeDrawer(GravityCompat.START);
if(item.getItemId() == R.id.login){
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_fragment, new loginScreen());
fragmentTransaction.commit();
hideKeyboard(this);
}
if(item.getItemId() == R.id.register){
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_fragment, new registerScreen());
fragmentTransaction.commit();
}
return false;
}
public static void hideKeyboard(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
//Find the currently focused view, so we can grab the correct window token from it.
View view = activity.getCurrentFocus();
//If no view currently has focus, create a new one, just so we can grab a window token from it
if (view == null) {
view = new View(activity);
}
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
On the actual build once I go to the login screen, I can no longer just press the menu button I have to click and drag for it to open. If the information I have provided is a bit vague I'm sorry I wasn't sure what to include.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout 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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<include
android:layout_height="match_parent"
android:layout_width="match_parent"
layout="#layout/drawer_toolbar"/>
<include
layout="#layout/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.navigation.NavigationView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/navigationView"
app:menu="#menu/drawer_menu"
app:headerLayout="#layout/drawyer_header"
android:layout_gravity="start"
android:fitsSystemWindows="true"/>
</androidx.drawerlayout.widget.DrawerLayout>

Fragment holding a RecyclerView not showing in the MainActivity

I'm trying to show a RecyclerView, in a fragment, in my main activity.
I'm not getting any errors, but the fragment remains empty, and I can't find the solution for this problem.
I simply have a fragment that has a recyclerview in it, I configure the recyclerview in HomeFragment.java, then in the MainParkActivity, I have a FrameLayout, which is replaced with the HomeFragment.
MainParkActivity
package com.example.ipark;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;;
public class MainParkActivity extends AppCompatActivity {
private static final String TAG = "MainParkActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: started.");
Toolbar toolbar = findViewById(R.id.toolbar);
Fragment homeFragment = new HomeFragment();
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("iParc");
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, homeFragment).commit();
}
}
HomeFragment
package com.example.ipark;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
public class HomeFragment extends Fragment {
private static final String TAG = "HomeFragment";
private ArrayList<String> mNames = new ArrayList<>();
private ArrayList<String> mImageUrls = new ArrayList<>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
RecyclerView recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
giveInformation();
RecyclerViewAdapter adapter = new RecyclerViewAdapter(getContext(), mNames, mImageUrls);
recyclerView.setAdapter(adapter);
}
private void giveInformation() {
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("BMW");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Audi");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Hyundai");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Mercedes");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("BMW");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Audi");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Hyundai");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Mercedes");
}
}
RecyclerViewAdapter
package com.example.ipark;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
private static final String TAG = "RecyclerViewAdapter";
private ArrayList<String> mImageNames;
private ArrayList<String> mImages;
private Context mContext;
public RecyclerViewAdapter(Context mContext, ArrayList<String> mImageNames, ArrayList<String> mImages) {
this.mImageNames = mImageNames;
this.mImages = mImages;
this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_listitem, parent, false);
ViewHolder holder;
holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Log.d(TAG, "onBindViewHolder: called.");
Glide.with(mContext)
.asBitmap()
.load(mImages.get(position))
.into(holder.image);
holder.imageName.setText(mImageNames.get(position));
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: clicked on: " + mImageNames.get(position));
Toast.makeText(mContext, mImageNames.get(position), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return mImageNames.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView image;
TextView imageName;
RelativeLayout parentLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image);
imageName = itemView.findViewById(R.id.image_name);
parentLayout = itemView.findViewById(R.id.parent_layout);
}
}
}
}
XML for activity_main
<?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=".MainParkActivity"
android:clipToPadding="false">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/toolbar">
</FrameLayout>
</android.support.constraint.ConstraintLayout>
XML for fragment_home
<?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">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
In your fragment_home.xml, your Recyclerview has layout_height and layout_width 0dp. Change it to match_parent. Everything else in your code is correct. I'd have commented it, but I currently do not have commenting privileges! Accept it if you found it helpful!
In your activity_main layout, you have app:layout_constraintBottom_toTopOf="parent"
It should be app:layout_constraintBottom_toBottomOf="parent"
Your layout is currently displaying above the screen in your fragment.
use
adapter.notifyDataSetChanged();
after setting the adapter for RecycleView.

Fragments with TabLayout and ViewPager

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

How to add dynamically several fragments

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

Categories

Resources