ViewPager no swipe issue - java

I'm tring to create a ViewPager non-swipable. I've wrote this code
MainActivity
public class MainActivity extends FragmentActivity {
ViewPagerAdattatore adattatoreViewPager;
DrawerLayout drawerLayout;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedIstanceState) {
super.onCreate(savedIstanceState);
setContentView(R.layout.activity_main);
viewPager=(ViewPager)findViewById(R.id.viewPager);
drawerLayout=(DrawerLayout)findViewById(R.id.navDrawer);
listaNavDrawer=(ListView)findViewById(R.id.listaDrawer);
adattatoreViewPager=new ViewPagerAdattatore(getSupportFragmentManager());
viewPager.setAdapter(adattatoreViewPager);
}
}
ViewPagerAdattatore
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class ViewPagerAdattatore extends FragmentPagerAdapter {
public final static int PAGINE=1;
Fragment fragment;
public ViewPagerAdattatore(FragmentManager fragmentManager) {
super(fragmentManager);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
switch (arg0) {
case 0: return new HomePage();
case 1: return new Informazioni();
// case 3: return new TerzaPagina();
}
fragment=new HomePage();
return fragment;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return PAGINE;
}
}
Informazioni
public class Informazioni extends Fragment {
TextView textView;
View view;
public View onCreateView(Bundle savedIstanceState, LayoutInflater inflater, ViewGroup parent) {
view=inflater.inflate(R.layout.home_page, parent, false);
textView=(TextView)view.findViewById(R.id.textView1);
textView.setText("welcome");
return view;
}
}
HomePage as the same code of informazioni
ViewPagerNoSwipe
public class ViewPagerNoSwipe extends ViewPager {
public ViewPagerNoSwipe(Context context) {
super(context);
}
public ViewPagerNoSwipe(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
return false;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return false;
}
}
activity_main
<?XML version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/navDrawer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.mypackage.name.utils.ViewPagerNoSwipe
android:id="#+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<ListView
android:id="#+id/listaDrawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#null"
android:dividerHeight="0dp"
android:background="#2F2F2F"/>
</android.support.v4.widget.DrawerLayout>
HomePage layout
<?XML version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textColor="#FFFFFF"
android:layout_marginTop="30dp"
android:fontFamily="sans-serif-light"/>
</RelativeLayout>
when I execute this code I don't see the TextView! why? where is the error(s) in my code?

Try this-
public class Informazioni extends Fragment {
TextView textView;
View view;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.home_page, container, false);
textView = (TextView) view.findViewById(R.id.textView1);
textView.setText("welcome");
return view;
}
}

Related

Problem with replace fragment in ViewPage

I am trying replace fragment first on second in ViewPager. And I have small problem becouse after replace still i see in background fragment first and they are working listner from fragment first. What am i doing wrong ? I replace first_fragment view but it doesn't work. In other project i were done somthing simular and it's working well !
public class FirstFragment extends BaseFragment {
private RecyclerView pathwaysRecyclerView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_pathways, container, false);
initializeViews(view);
initRecyclerView();
return view;
}
private void initializeViews(View view) {
pathwaysRecyclerView = view.findViewById(R.id.pathways_recyclerview);
}
private void initRecyclerView(){
pathwaysRecyclerView.setLayoutManager(new GridLayoutManager(requireContext(), 2));
PathwaysAdapter adapter = new PathwaysAdapter(new OnPathwayClickListner(),requireContext());
pathwaysRecyclerView.setAdapter(adapter);
}
private class OnPathwayClickListner implements View.OnClickListener {
#Override
public void onClick(View view) {
navigateToSecondFragment();
}
}
private void navigateToSecondFragment(){
Fragment fragment = new SecondFragment();
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_pathways_view, fragment)
.addToBackStack(null)
.commit();
}
#Override
public void updateView() {
}
}
fragment_first.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment_pathways_view">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/greyAccent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/ebpHeader"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/greyAccent"
android:orientation="vertical" >
<TextView
android:id="#+id/pathways_name_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/list_of_all_paths"
android:layout_margin="15sp"
app:fontFamily="sans-serif-light"
android:textSize="25sp"
android:textStyle="bold"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/vertical_margin"
android:layout_marginStart="#dimen/vertical_margin"
android:layout_marginEnd="#dimen/vertical_margin"
android:layout_marginBottom="#dimen/beetwen_content_line_margin"
android:textSize="#dimen/textSizeMedium"
android:text="#string/list_of_all_paths_description"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/evaluation_background">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/pathways_recyclerview"
android:layout_marginTop="#dimen/beetwen_content_line_margin"
android:layout_marginStart="#dimen/vertical_margin"
android:layout_marginEnd="#dimen/vertical_margin"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
second fragment
public class SecondFragment extends BaseFragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_path, container, false);
return view;
}
}
fragment_second.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/mainAppBackgroundColor">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/mainAppBackgroundColor"
android:orientation="vertical">
<TextView
android:id="#+id/path_name_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="15sp"
app:fontFamily="sans-serif-light"
android:textSize="25sp"
android:textStyle="bold"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/list_of_skills"
android:layout_marginTop="15sp"
android:layout_marginStart="15sp"
android:layout_marginEnd="15sp"
app:fontFamily="sans-serif-light"
android:textSize="18sp"
android:textStyle="bold"
/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="#dimen/vertical_margin"
android:layout_marginTop="5sp"
android:layout_marginEnd="#dimen/vertical_margin" />
</LinearLayout>
</RelativeLayout>
ViewPager:
<com.habitcoach.android.activity.util.NonSwipeableViewPager
android:id="#+id/hsFragmentsContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:orientation="vertical"
android:paddingBottom="50dp"
android:layout_alignParentLeft="true" />
PageAdapter:
class MainViewViewPageAdapter extends FragmentStatePagerAdapter {
MainViewViewPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getItemPosition(Object object) {
BaseFragment f = (BaseFragment) object;
if (f != null) {
f.updateView();
}
return super.getItemPosition(object);
}
#Override
public Fragment getItem(int position) {
Fragment f = null;
switch (position) {
case 0:
f = new OneFragment();
break;
case 1:
f = new TwoFragment();
break;
case 2:
f = new ThreeeFragment();
break;
case 3:
f = new FourFragment();
break;
}
return f;
}
#Override
public int getCount() {
return 4;
}
}
I modified your code.check below solution.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.hsFragmentsContainer);
viewPager.setAdapter(new MainViewViewPageAdapter(getSupportFragmentManager()));
}}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<android.support.v4.view.ViewPager
android:id="#+id/hsFragmentsContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
MainViewViewPageAdapter.java
public class MainViewViewPageAdapter extends FragmentStatePagerAdapter {
public MainViewViewPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getItemPosition(#NonNull Object object) {
return super.getItemPosition(object);
}
#Override
public Fragment getItem(int position) {
Fragment f = null;
switch (position) {
case 0:
f = new FirstFragment();
break;
case 1:
f = new SecondFragment();
break;
}
return f;
}
#Override
public int getCount() {
return 2;
}}
FirstFragment.java
public class FirstFragment extends Fragment {
private RecyclerView pathwaysRecyclerView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
initializeViews(view);
initRecyclerView();
return view;
}
private void initializeViews(View view) {
pathwaysRecyclerView = view.findViewById(R.id.pathways_recyclerview);
}
private void initRecyclerView(){
pathwaysRecyclerView.setLayoutManager(new GridLayoutManager(requireContext(), 2));
PathwaysAdapter adapter = new PathwaysAdapter(new OnPathwayClickListner(),requireContext());
pathwaysRecyclerView.setAdapter(adapter);
}
public class OnPathwayClickListner implements View.OnClickListener {
#Override
public void onClick(View view) {
navigateToSecondFragment();
}
}
private void navigateToSecondFragment(){
Fragment fragment = new SecondFragment();
getFragmentManager().beginTransaction().replace(R.id.fragment_pathways_view, fragment).addToBackStack(null).commit();
}}
SecondFragment.java
public class SecondFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_second, container, false);
return view;
}
}
PathwaysAdapter.java
class PathwaysAdapter extends RecyclerView.Adapter<PathwaysAdapter.MyViewHolder>{
FirstFragment.OnPathwayClickListner onPathwayClickListner;
Context requireContext;
ArrayList<String> list;
public PathwaysAdapter(FirstFragment.OnPathwayClickListner onPathwayClickListner, Context requireContext) {
this.onPathwayClickListner=onPathwayClickListner;
this.requireContext=requireContext;
list=new ArrayList<>();
for (int i=1;i<=20;i++){
list.add("Pathway "+i);
}
}
#NonNull
#Override
public PathwaysAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row, viewGroup, false);
return new PathwaysAdapter.MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PathwaysAdapter.MyViewHolder myViewHolder, int i) {
myViewHolder.textview.setText(list.get(i));
}
#Override
public int getItemCount() {
return list.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
RelativeLayout layout;
TextView textview;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
textview = itemView.findViewById(R.id.textview);
layout = itemView.findViewById(R.id.layout);
layout.setOnClickListener(onPathwayClickListner);
}}}
row.xml
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardBackgroundColor="#FF9800"
card_view:cardCornerRadius="5dp"
card_view:cardElevation="5dp"
card_view:cardUseCompatPadding="true">
<RelativeLayout
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="100dp">
<TextView
android:id="#+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="#ffffff" />
</RelativeLayout>

TabbedActivity randomly shows fragments but is most of the time blank

I created a TabbedActivity with some fragments, these fragments sometimes load and sometimes they dont, i've searched everywhere but couldn't find the issue.
Example gif
This is my main activity:
public class TwitterActivity extends AppCompatActivity implements MessagesFragment.OnFragmentInteractionListener, NotificationFragment.OnFragmentInteractionListener,
ProfileFragment.OnFragmentInteractionListener, TimeLineFragment.OnFragmentInteractionListener {
private static final String APP_TAG = "Twitter";
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(null);
setContentView(R.layout.activity_twitter);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
final TextView toolbarTitle = toolbar.findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOffscreenPageLimit(3);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
if(position == 0){
toolbarTitle.setText(R.string.tab_timeline);
}else if(position == 1){
toolbarTitle.setText(R.string.tab_messages);
}else if(position == 2){
toolbarTitle.setText(R.string.tab_notifications);
}else if(position == 3){
toolbarTitle.setText(R.string.tab_profile);
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) { }
#Override
public void onTabReselected(TabLayout.Tab tab) { }
});
tabLayout.setupWithViewPager(mViewPager, false);
}
#Override
public void onFragmentInteraction(Uri uri) { }
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Log.d(APP_TAG, String.valueOf(position));
if(position == 0){
return TimeLineFragment.newInstance();
}else if(position == 1){
return MessagesFragment.newInstance();
}else if(position == 2){
return NotificationFragment.newInstance();
}else if(position == 3){
return ProfileFragment.newInstance();
}
return null;
}
#Override
public int getCount() {
return 4;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return getString(R.string.tab_timeline);
case 1:
return getString(R.string.tab_messages);
case 2:
return getString(R.string.tab_notifications);
case 3:
return getString(R.string.tab_profile);
default:
return getString(R.string.tab_timeline);
}
}
}
}
This is one of my fragments (They are all the same):
public class TimeLineFragment extends Fragment {
private OnFragmentInteractionListener mListener;
public TimeLineFragment() {
}
public static TimeLineFragment newInstance() {
TimeLineFragment fragment = new TimeLineFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_time_line, container, false);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
This is my main activity's layout file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".activities.TwitterActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:src="#mipmap/ic_launcher"
/>
<TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="#string/tab_timeline"
android:textSize="18sp"
android:textStyle="bold" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:elevation="80dp"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="56dp"
app:tabGravity="fill"
app:tabIndicatorColor="#android:color/holo_orange_dark"
app:tabIndicatorHeight="0dp"
app:tabMode="fixed">
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_above="#+id/tabs"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
Please help me
EDIT: removed the useless TabItems.
You may have to use getChildFragmentManager() instead of getSupportFragmentManager() as parameter to create you adapter.

How can I add a ViewPager to a Navigation Drawer Item in Android application?

I want to add a viewPager for main fragment in my android app.
This is the xml file for main fragment
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
This is the Java code for Main Fragment
public class MainFragment extends ListFragment {
private static final String TAG = MainFragment.class.getSimpleName();
private StudentsDBHandler studentsDBHandler;
public MainFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
studentsDBHandler = new StudentsDBHandler(getActivity());
View rootView = inflater.inflate(R.layout.main_fragment, container, false);
displayStudents();
return rootView;
}
private void displayStudents() {
List<Student> studentList = studentsDBHandler.getAll();
ArrayAdapter<Student> list = new ArrayAdapter<>(getActivity(), R.layout.item_student, studentList);
setListAdapter(list);
}
}
You have a DrawerLayout page. It's about your drawer contains.
İn the DrawerLayout XML
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
add this code below
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
write this code and setup your View pager like example
viewPager=(ViewPager)findViewById(R.id.viewPager);
FragmentManager fm=getSupportFragmentManager();
viewPager.setAdapter(new MyAdapter(fm));
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if(position==0)
fragment= new Home1();
if(position==1)
fragment=new Home2();
return fragment;
}
#Override
public int getCount() {
return 2;
}
}
}
I hope Help you

accessing fragment's view from activity with function

I am trying to dynamically change a text from a fragment textview inside de activity but I keep getting 'cannot obtain root' error. I tried to instantiate the textview inside onCreateView and inside onActivityCreated as well but it doesnt work. How can I change the text from a fragment textview inside the activity?
Fragment xml:
<RelativeLayout 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/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Tab 1"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</RelativeLayout>
Fragment Code:
public class TabFragment1 extends Fragment {
private TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_fragment_1, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tv = (TextView) getView().findViewById(R.id.textView);
}
public void setText(String text){
tv.setText(text);
}
}
Main xml:
<RelativeLayout
android:id="#+id/main_layout"
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=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
</RelativeLayout>
Main code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
TabFragment1 t1 = new TabFragment1();
TabFragment2 t2 = new TabFragment2();
TabFragment3 t3 = new TabFragment3();
adapter.newFrag(t1);
adapter.newFrag(t2);
adapter.newFrag(t3);
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
t1.setText("HELLO WORLD");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
PagerAdapter:
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
List<Fragment> aFrag;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
aFrag = new ArrayList<Fragment>();
}
public void newFrag(Fragment f){
aFrag.add(f);
}
#Override
public Fragment getItem(int position) {
return aFrag.get(position);
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
You try to set text on view, but this view wasn't created, this fragment wasn't created. If You want to set text from activity you can pass bundle to fragment arguments with that text, and in fragment chceck bundle and set text. Later if you want to change text in this fragment then you can use your function.
public class TabFragment1 extends Fragment {
private TextView tv;
public static TabFragment1 create(String text){
Bundle b = new Bundle();
b.putString("textdata",text);
TabFragment1 f = new TabFragment1();
f.setArguments(b);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_fragment_1, container, false);
tv = (TextView) view.findViewById(R.id.textView);
if(getArguments()!=null){
tv.setText(getArguments().getString("textdata"));
}
return view;
}
public void setText(String text){
tv.setText(text);
}
}
In your activity create this fragment using static method:
TabFragment1 t1 =TabFragment1.create("HELLO WORLD");
Hardcore execution of your base code is:
new Handler().postDelayed(new Runnable(){t1.setText("HELLO WORLD");},300);

Unable to Replace Fragment A with Fragment B in same Activity

My App have one Main Activity which has a Linear Layout and Linear layout is showing one Fragment A having list containing Button and Text View. I want click on a Button of List view of Fragment A then It should Replace fragment A with Fragment B.
Now I am able to Click on the Button of list view of Fragment A but(it is not showing Fragment B) it is showing Android not responding. I have done Debug and I am Getting error at committing of transaction for Fragment B. other piece of Code is Working Fine.
Please help me out why I am getting this error
Full code is below
Main Activity Code
public class MainActivity extends Activity {
FrameLayout frameLayout = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Async","On Create");
frameLayout = (FrameLayout) findViewById(R.id.fragment_Container);
InstallFragmetA();
}
protected void InstallFragmetA()
{
FragmentA fragmentA = new FragmentA();
FragmentManager manager= getFragmentManager();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.fragment_Container,fragmentA,"A");
transaction.commit();
}
protected void InstallFragmetB()
{
FragmentB fragmentB = new FragmentB();
FragmentManager manager= getFragmentManager();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.fragment_Container,fragmentB,"B");
transaction.commit();
}
protected void RemoveFragmetA()
{
Log.d("Async","In Remove Fragment A");
FragmentB fragmentB = new FragmentB();
Log.d("Async","Fragment b initializeed");
// FragmentManager manager= getFragmentManager();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
Log.d("Async","Begin fragment transaction");
FragmentA fragmentA = (FragmentA) getFragmentManager().findFragmentByTag("A");
// fragmentA.onDestroy();
// fragmentA.onDestroyView();
transaction.replace(R.id.fragment_Container, fragmentB, "B");
Log.d("Async", "Fragment A replaced");
// transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
Log.d("Async","Fragment Failed");
// transaction.addToBackStack(null);
transaction.commit();
Log.d("Async","Transaction Commit");
}
Fragment A Code
public class FragmentA extends Fragment {
MainActivity mainActivity= null;
TextView textView=null;
String[] friendList= null;
public FragmentA()
{
mainActivity = new MainActivity();
}
//Activity activity= null;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// this.activity = activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("Async","On Create");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d("Async","On Create view");
return inflater.inflate(R.layout.fragmenta,container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
textView = (TextView) getActivity().findViewById(R.id.textView);
ListView list = (ListView) getActivity().findViewById(R.id.listView);
Log.d("Async","Array is "+getResources().getStringArray(R.array.FriendsList));
friendList = getResources().getStringArray(R.array.FriendsList);
Log.d("Async","Array is "+friendList[0]);
textView.setText(friendList[0]);
// ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),R.array.FriendsList,R.layout.text);
AdapterClass adapterClass = new AdapterClass(getActivity(),friendList,mainActivity);
list.setAdapter(adapterClass);
list.setItemsCanFocus(true);
list.setFocusable(true);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("Async","A");
Toast.makeText(getActivity(),"Hello "+position,Toast.LENGTH_LONG).show();
}
});
Log.d("Async","On Activity Created");
}
}
Adapter Class Which I am Using for Fragment A
public class AdapterClass extends ArrayAdapter {
Button btn;
int counter=0;
Context c=null;
String[] friendList= null;
LayoutInflater l;
MainActivity mainActivity = null;
public AdapterClass(Context c, String[] friendList, MainActivity mainActivity) {
super(c,R.layout.a,R.id.textView3,friendList);
l = (LayoutInflater) c.getSystemService(c.LAYOUT_INFLATER_SERVICE);
Log.d("Async","counter is ");
this.c=c;
this.friendList = friendList;
this.mainActivity = mainActivity;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Log.d("Async","getView is "+position);
Log.d("Async","counter is "+counter);
View row = convertView;
Myholder holder = null;
if(row == null)
{
Log.d("Async","Row is Null");
row = l.inflate(R.layout.a, parent,false);
holder = new Myholder(row);
row.setTag(holder);
Log.d("Async","Row Set tag");
}
else
{
Log.d("Async","Row is not null");
holder = (Myholder) row.getTag();
Log.d("Async","Holder not tag");
}
holder.btn.setText(friendList[position]);
holder.text.setText(friendList[position]);
holder.btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Async","Button Clicked "+friendList[position]);
Toast.makeText(c,"Button clicked "+friendList[position],Toast.LENGTH_LONG).show();
mainActivity.RemoveFragmetA();
}
});
return row;
}
}
Fragment B Code
public class FragmentB extends Fragment {
public void onAttach(Activity activity) {
super.onAttach(activity);
// this.activity = activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("Async", " Fragment B On Create");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d("Async"," Fragment B On Create view");
return inflater.inflate(R.layout.fragmentb,container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:id="#+id/mainActivity"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<FrameLayout
android:layout_width="fill_parent"
android:id="#+id/fragment_Container"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"></FrameLayout>
fragmenta.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:id="#+id/linearLayouts"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#2233"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Small Text"
android:id="#+id/textView" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView" />
fragmentb.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#2233"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Small Text"
android:id="#+id/textView" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView1" />
I am getting bellow Error.
E/AndroidRuntime(1021): java.lang.IllegalStateException: Activity has been destroyed
E/AndroidRuntime(1021): at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1333)
E/AndroidRuntime(1021): at android.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
E/AndroidRuntime(1021): at android.app.BackStackRecord.commit(BackStackRecord.java:574)
E/AndroidRuntime(1021): at com.example.bathla.lab5_asynctasklabtest.MainActivity.InstallFragmetB(MainActivity.java:38)
E/AndroidRuntime(1021): at com.example.bathla.lab5_asynctasklabtest.AdapterClass$1.onClick(AdapterClass.java:64)
E/AndroidRuntime(1021): at android.view.View.performClick(View.java:4240)
E/AndroidRuntime(1021): at android.view.View$PerformClick.run(View.java:17721)
E/AndroidRuntime(1021): at android.os.Handler.handleCallback(Handler.java:730)
E/AndroidRuntime(1021): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(1021): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(1021): at android.app.ActivityThread.main(ActivityThread.java:5103)
E/AndroidRuntime(1021): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1021): at java.lang.reflect.Method.invoke(Method.java:525)
E/AndroidRuntime(1021): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
E/AndroidRuntime(1021): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime(1021): at dalvik.system.NativeStart.main(Native Method)
MainActivity
public class MainActivity extends Activity implements FragmentAListener
{
private FragmentA fragmentA;
private FragmentB fragmentB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentA = (FragmentA) getFragmentManager().findFragmentByTag(FragmentA.class.getSimpleName());
if (savedInstanceState == null) {
fragmentA = new FragmentA();
replaceToFragment(fragmentA, false);
}
}
#Override
public void onListItemButtonClicked(String itemName) {
fragmentB = new FragmentB();
Bundle bundle = new Bundle();
bundle.putString(FragmentB.ITEM_NAME_KEY, itemName);
fragmentB.setArguments(bundle);
replaceToFragment(fragmentB, true);
}
public void replaceToFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment, fragment.getClass().getSimpleName());
if (addToBackStack) {
transaction.addToBackStack(fragment.getClass().getSimpleName());
}
transaction.commit();
}
}
FragmentA
public class FragmentA extends Fragment
{
private String[] friendList;
private FragmentAListener listener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof FragmentAListener)) {
throw new RuntimeException("Activity must implements FragmentAListener");
}
listener = (FragmentAListener) activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragmenta, container, false);
TextView textView = (TextView) view.findViewById(R.id.textView);
ListView listView = (ListView) view.findViewById(R.id.listView);
friendList = getResources().getStringArray(R.array.FriendsList);
textView.setText(friendList[0]);
AdapterClass adapterClass = new AdapterClass(inflater.getContext(), friendList, listener);
listView.setAdapter(adapterClass);
listView.setOnItemClickListener(itemClickListener);
return view;
}
private AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//TODO your code
}
};
public interface FragmentAListener
{
void onListItemButtonClicked(String itemName);
}
}
FragmentB
public class FragmentB extends Fragment
{
public static final String ITEM_NAME_KEY = "item_name";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragmentb, container, false);
//TODO find your views here
TextView textView = (TextView) view.findViewById(R.id.textView);
textView.setText("Its FragmentB. Selected item: " + getArguments().getString(ITEM_NAME_KEY));
return view;
}
}
Adapter
public class AdapterClass extends ArrayAdapter<String>
{
private LayoutInflater inflater;
private FragmentAListener listener;
public AdapterClass(Context context, String[] friendList, FragmentAListener listener) {
super(context, 0, friendList);
inflater = LayoutInflater.from(context);
this.listener = listener;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
Holder holder;
if (view == null) {
view = inflater.inflate(R.layout.list_item, parent, false);
holder = new Holder(view);
view.setTag(holder);
} else {
holder = (Holder) view.getTag();
}
String itemName = getItem(position);
holder.textView.setText(itemName);
holder.button.setText(itemName);
holder.button.setTag(itemName);
return view;
}
private class Holder
{
private TextView textView;
private Button button;
public Holder(View row) {
textView = (TextView) row.findViewById(R.id.textView);
button = (Button) row.findViewById(R.id.button);
button.setOnClickListener(onClickListener);
}
}
private OnClickListener onClickListener = new OnClickListener()
{
#Override
public void onClick(View v) {
listener.onListItemButtonClicked(v.getTag().toString());
}
};
}
Activity layout
<LinearLayout
android:id="#+id/mainActivity"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
FragmentA layout
<LinearLayout android:id="#+id/linearLayouts"
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/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#2233"
android:text="This is Fragment A"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
FragmentB Layout
<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/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#2233"
android:text="This is Fragment B"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
List Item Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="#+id/fancy_item_fragment"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
android:orientation="horizontal"
android:padding="15dp">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Text"/>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"/>
</LinearLayout>
Add this on your activity.xml, container for Fragment
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragmentcontainer">
</FrameLayout>
and this for attach Fragment
Fragment fr;
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fr = new YourFragmentToShow();
fragmentTransaction.replace(R.id.fragmentcontainer, fr)
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentTransaction.commit();

Categories

Resources