Replace fragment in fragment itself in TabActivity - android

I am sorry on the duplicate question but I didn't get answer for my problem.
I create app with TabActivity and also trying to replace one fragment from fragment itself, I read in https://developer.android.com/training/basics/fragments/fragment-ui.html how to do it and i created interface in my fragment that i want to be replace with another,
I implement the interface in my MainActivity and still when running my app it show me container itself.
here is my code:
Main Activity:
public class MainActivity extends FragmentActivity implements New2.OnReplaceFragment {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
public static MainActivity instance = null;
public static MainActivity getInstance(){
return instance;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.frame_container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.icon_info);
tabLayout.getTabAt(1).setIcon(R.drawable.icon_heart_rate_sensor_jpg);
tabLayout.getTabAt(2).setIcon(R.drawable.icon_graph_jpg);
instance = this;
}
#Override
public void onReplaceFragment(Class fragmentClass) {
Fragment fragment = null;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container,fragment);
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position) {
case 0:
// New1 tab1 = new New1();
return New1.newInstance();
case 1:
return New2.newInstance();
case 2:
return New3.newInstance();
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
}
my fragment that I want to replace
Fragment:
public class New2 extends Fragment {
TextView name;
Button change;
ImageView image1;
Animation anime;
private OnReplaceFragment dataPasser;
public static New2 newInstance(){
New2 fragment = new New2();
return fragment;
}
public New2(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_new2, container, false);
name = (TextView) rootView.findViewById(R.id.nameTt);
change = (Button) rootView.findViewById(R.id.changeBtn);
image1 = (ImageView) rootView.findViewById(R.id.image1);
anime = AnimationUtils.loadAnimation(getActivity().getApplicationContext(),R.anim.zoom);
change.setOnClickListener(changeName);
return rootView;
}
View.OnClickListener changeName = new View.OnClickListener() {
#Override
public void onClick(View view) {
image1.startAnimation(anime);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run(){
dataPasser.onReplaceFragment(Result.class);
}
},1000);
}
};
public interface OnReplaceFragment {
public void onReplaceFragment(Class fragmentClass);
}
#Override
public void onAttach(Activity a) {
super.onAttach(a);
try {
dataPasser = (OnReplaceFragment) a;
} catch (ClassCastException e) {
throw new ClassCastException(a.toString() + " must implement onDataPass");
}
}
}
the fragment that i want to display
public class Result extends Fragment {
TextView textView;
Button btnBack;
public static Result instance = null;
public static Result getInstance(){
return instance;
}
public Result() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_result, container, false);
textView = (TextView) v.findViewById(R.id.text11);
btnBack = (Button) v.findViewById(R.id.btnBack);
textView.setText("working!!");
Toast.makeText(getActivity().getApplicationContext(),"working",Toast.LENGTH_LONG).show();
return v;
}
}
Main Activity XML:
<?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="com.example.hercules.tadhosttutrial.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:background="#color/red"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
New2 XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.hercules.tadhosttutrial.New2"
android:background="#color/yellow">
<!-- TODO: Update blank fragment layout -->
<Button
android:id="#+id/changeBtn"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_gravity="center_horizontal"
android:text="change"/>
<ImageView
android:id="#+id/image1"
android:background="#drawable/icon_complete"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
Result 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:background="#color/colorAccent"
tools:context="com.example.hercules.tadhosttutrial.Result">
<!-- TODO: Update blank fragment layout -->
<Button
android:id="#+id/btnBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="back"/>
<TextView
android:id="#+id/text11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="WORKING"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textSize="70dp"
/>
</RelativeLayout>

What i mean, is making MainActivity as a main container for all fragments, either with tabs or just a regular fragment,
1- Main Activity XML: remove ViewPager, add a FrameLayout instead (use same id)
2- Create new fragment TabsFragment with this XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.hercules.tadhosttutrial.New2"
android:background="#color/yellow">
<android.support.v4.view.ViewPager
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</RelativeLayout>
3- Move initializing SectionsPagerAdapter and ViewPager from main activity to TabsFragment:
this part:
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
and this:
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.frame_container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.icon_info);
tabLayout.getTabAt(1).setIcon(R.drawable.icon_heart_rate_sensor_jpg);
tabLayout.getTabAt(2).setIcon(R.drawable.icon_graph_jpg);
4- I think moving SectionsPagerAdapter class in a new file is better too.
now if you want default view for app to be the tabs, then in MainActivity at onCreate() show TabsFragment by calling your method:
onReplaceFragment(TabsFragment.class);
now every thing should work fine, because the idea here is to replace the fragment displayed in main activity with another one
in this case TabsFragment, Result, and New2
not to replace viewpager fragments (because as i told you this is managed via the adapter) not by calling replace()
you may need to play around this, it's not a final code, just something to give you idea about it.

Related

Replacement fragments in in pagerView

`Facing one problem in android that I created a pager View and two fragments lets say fragment A and fragment B are attached...
My question is: There is a button in fragment A after clicking on that button I want to load fragment C which will be the replacement of fragment A in the same pager view how can it be done? But when I try below code content of Fragment C is shown over the fragment A ... can u help me with this please. I searched everywhere but didn't get the proper solution.
here is my code...
public class MainActivity extends AppCompatActivity implements Top_Fragment.OnFragmentInteractionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar=findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
MyPagerAdapter myPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.pagerView);
viewPager.setAdapter(myPagerAdapter);
TabLayout tabLayout=findViewById(R.id.tab_bar);
tabLayout.setupWithViewPager(viewPager);
}
class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(#NonNull FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Top_Fragment();
case 1:
return new FavoriteFrag();
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getResources().getString(R.string.Items);
case 1:
return getResources().getString(R.string.favoriteItems);
}
return null;
}
}
#Override
public void onFragmentInteraction(int position) {
Fragment fragment=null;
switch (position){
case 0:
fragment=new DrikCategaryFrag();
}
FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frameContainer,fragment);
ft.commit();
}
}
Main activity layout
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<androidx.appcompat.widget.Toolbar
android:id="#+id/tool_bar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tab_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</com.google.android.material.appbar.AppBarLayout>
<FrameLayout
android:id="#+id/frameContainer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.viewpager.widget.ViewPager
android:id="#+id/pagerView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.viewpager.widget.ViewPager>
</FrameLayout>
</LinearLayout>
Try this:
Viewpager with multiple fragments:
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
default: return FirstFragment.newInstance("FirstFragment, Default");
}
}
#Override
public int getCount() {
return 2;
}
}
}
activity_main.xml
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
FirstFragment.java
public class FirstFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag, container, false);
TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
tv.setText(getArguments().getString("msg"));
return v;
}
public static FirstFragment newInstance(String text) {
FirstFragment f = new FirstFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
SecondFragment.java
public class SecondFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.second_frag, container, false);
TextView tv = (TextView) v.findViewById(R.id.tvFragSecond);
tv.setText(getArguments().getString("msg"));
return v;
}
public static SecondFragment newInstance(String text) {
SecondFragment f = new SecondFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}

How to implement the avatar selection screen like this in android without using any library?

this is my first question here. I am trying implement similar avatar selection screen for my college project. I searched almost everywhere and it seems like it can be done using viewpager. I tried but cant achieve similar effect. I have problem is showing all child in at the same time. and also i cant able to achieve the select avatar scaled in high and rest in low. Please help me out, i want to implement quickly as possible without using any library because i want to understand how it can be implemented without it as of now. Thanks in advance.
I have tried to create a viewpager with 3 images. This is my implementation.
MainActivity.java with MyPagerAdapter
public class MainActivity extends AppCompatActivity {
FragmentPagerAdapter pagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.myViewPager);
pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
}
public static class MyPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 3;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return FirstFragment.newInstance(R.drawable.a);
case 1:
return SecondFragment.newInstance(R.drawable.b);
case 2:
return ThirdFragment.newInstance(R.drawable.c);
default:
return null;
}
}
#Override
public int getCount() {
return NUM_ITEMS;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
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">
<android.support.v4.view.ViewPager
android:id="#+id/myViewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v4.view.ViewPager>
</RelativeLayout>
I have 3 Fragements. This is one of the fragement.
FirstFragment.java
public class FirstFragment extends Fragment {
private int image;
public FirstFragment() {
}
public static FirstFragment newInstance(int resImage) {
FirstFragment fragment = new FirstFragment();
Bundle args = new Bundle();
args.putInt("image", resImage);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
image = getArguments().getInt("image", 0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.firstImg);
imageView.setImageResource(image);
return view;
}
}
This is fragment_first.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<!-- TODO: Update blank fragment layout -->
<ImageView
android:id="#+id/firstImg"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>

How to communicate from Mainactivity to Fragment using callback interface?

I'm having navigation drawer with four menu's and each menu has own fragments
, Inside first fragment has view pager sliding tab with 2 fragments,
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.CoordinatorLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="#color/white"
app:tabIndicatorHeight="4dp" />
</android.support.design.widget.AppBarLayout>
////////////// Here I'm replacing each fragments ////////////////
<FrameLayout
android:id="#+id/main_content_framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="#dimen/fab_margin"
android:src="#drawable/ic_done"
android:visibility="gone"/>
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_view"/>
</android.support.v4.widget.DrawerLayout>
ManinActivity- DrawerSelection
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass = null;
switch (menuItem.getItemId()) {
case R.id.nav_home:
fragmentClass = Home_Tab_Fragment.class;
break;
case R.id.nav_myorders:
fragmentClass = SecondFragment.class;
break;
case R.id.nav_myoffers:
fragmentClass = ThirdFragment.class;
break;
case R.id.nav_notification:
fragmentClass = FourthFragment.class;
break;
}
fragment = (Fragment) fragmentClass.newInstance();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.main_content_framelayout, fragment).commit();
mDrawerLayout.closeDrawers();
}
HomeTabFragment
public class Home_Tab_Fragment extends Fragment {
private FragmentActivity myContext;
ViewPager viewPager;
TabLayout tabLayout;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.layout_viewpager, container, false);
viewPager = (ViewPager) rootView.findViewById(R.id.view_pager);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SlidingTabAdapter adapter = new SlidingTabAdapter(getChildFragmentManager());
adapter.addFragment(new FirstTabFragment(), "First TAB");
adapter.addFragment(new SecondTabFragment(), "Second Tab");
viewPager.setAdapter(adapter);
tabLayout = (TabLayout) getActivity().findViewById(R.id.tabs);
tabLayout.setVisibility(View.VISIBLE);
tabLayout.setupWithViewPager(viewPager);
}
}
SlidingTabAdapter
public class SlidingTabAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public SlidingTabAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
layout_viewpager.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/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
FirstFragment
public class FirstTabFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_first, container, false);
getActivity().setTitle("Foodies");
return rootView ;
}
public void updateFirstFragmentValues(){
//Doing some operations
}
}
Inside MainActivity , I want to call FirstTabFragment method [updateFirstFragmentValues()]
I tried adding TAG in FirstTabFragment ,
public static final String TAG ="FirstTabFragment.TAG";
Then I invoked in MainActivity like below , but Fragment always null.
public void invokeMethodFromFirstTabFragment() {
FragmentManager fm = this.getSupportFragmentManager();
FirstTabFragment fb=(FirstTabFragment)fm.findFragmentByTag(FirstTabFragment.TAG);
if (null != fb) {
fb.updateFirstFragmentValues();
}else{
L.m("Fragment is null===========");
}
}
Kindly advise , How to call "FirstTabFragment" method from inside "MainActivity"
Please note FirstTabFragment is not added directly to MainActivity ,
its added through "Home_Tab_Fragment".
Alright, reading all of the responses of yours, I get that you just simply need to pass data to a fragment upon creation and be able to execute some of Fragment's methods. Ok, simple enough:
IMessageFragment interface
public interface IMessageFragment {
/**
* Method to receive new message text
* #param text Message text to receive
*/
void updateMessageText(String text);
}
MessageFragment
public class MessageFragment extends Fragment implements IMessageFragment {
/**
* Bind views using ButterKnife
*/
#BindView(R.id.textView) TextView mTextView;
/**
* Bundle data
*/
private String mMessageText;
/**
* Unique id of bundle data
*/
private static final String MESSAGE_EXTRA_KEY = "f_message";
/**
* New fragment pattern. This is pretty much all the magic PLUS this
* looks by far better than `new Fragment()` upon instatiation
*/
public static MessageFragment newFragment(String message) {
// 1. Create new fragment
MessageFragment auctionFragment = new MessageFragment();
// 2. Create bundle for fragment params
Bundle args = new Bundle();
// 3. Put position
args.putString(MESSAGE_EXTRA_KEY, message);
// 4. Set arguments
auctionFragment.setArguments(args);
return auctionFragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tutorial_fragment, container, false);
/**
* Bind views
*/
ButterKnife.bind(this, view);
// Update UI
updateUI();
return view;
}
/**
* Method to update value of mTextView
*/
private void updateUI() {
if(!mMessageText.equals("")) {
mTextView.setText(mMessageText);
}
}
#Override
public void updateMessageText(String text) {
mMessageText = text;
updateUI();
}
}
Stuff is pretty simple and the interface exists only for good code style and to support design patterns.
Edit:
You cannot directly access FirstTabFragment method from your MainActivity. Firstly you have to call Home_Tab_Fragment method from activity. Then from that method you can call FirstTabFragment method.
Here is strategy:
Step 1: Home_Tab_Fragment to FirstTabFragment communication
define an interface like this
public interface IHomeToFirstFragmentController{
void firstFragmentMethod();
}
Now implements the IHomeToFirstFragmentController in your FirstTabFragment. then you have to implements the firstFragmentMethod().
#overrride
void firstFragmentMethod(){
}
Call this firstFragmentMethod method from Home_Tab_Fragment using this way
YOUR_fragmentInstance.firstFragmentMethod();
Step 2: Activity to Home_Tab_Fragment:
define an interface like this
public interface IActivityToHomeTabController{
void callFirstFragment();
}
Now implements the IFragmentController in your Home_Tab_Fragment. then you have to implements the callFirstFragment().
#overrride
void callFirstFragment(){
YOUR_fragmentInstance.firstFragmentMethod();
}
Edit 2:
Call fragment using this way
((IFragmentController)YOUR_fragmentInstance).firstFragmentMethod();
Hope this will give you an idea about this topics. For more info visit this answer
First for all, you create interface :
public interface CallBackListener{
void onCallBack();
}
In Fragment
public MyFragment extends Fragment{
private CallBackListener mCallBack;
#Override
public void onAttach(Context context) {
AppCompatActivity activity;
if (context instanceof AppCompatActivity) {
activity = (AppCompatActivity) context;
try {
mCallBack= (CallBackListener ) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " class must be implement" +
" OnBackFragmentListener");
}
}
super.onAttach(context);
}
}
Use :
mCallBack.onCallBack();
And in Activity, you must implements interface :
public MyActivity extends AppCompatActivity implements CallBackListener{
#Override
public void onCallBack(){
// Do somethings here...
}
}

Edittext automatically gets focus when move between pages in a view pager

I have an activity which hosts two fragments inside a view pager. I used the same layout to inflate those fragments. The layout has two edit texts placed inside a linear layout which is inside a relative layout. The problem is when I switch from fragment A to fragment B, he first edit text has focus in fragment A and when I return back from fragment B to fragment A, instead of the first edit text having focus, the second edit text gets the focus. How to solve it. I provide the layouts and source code below. I have not return any code inside the fragment classes.
Activity:
public class LoginActivity extends BaseActivity {
public static final String selectedTabPosition = "selectedTabPosition";
//Tab tag name
private static String TAB_1_TAG = "Email";
private static String TAB_2_TAG = "Mobile";
private TabLayout mTabLayout;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
TAB_1_TAG = getResources().getString(R.string.tab_email);
TAB_2_TAG = getResources().getString(R.string.tab_mobile);
//Initialise views
mViewPager = (ViewPager) findViewById(R.id.viewpager);
mTabLayout = (TabLayout) findViewById(R.id.tabs);
//set tab with view pager
setupViewPager(mViewPager);
mTabLayout.setupWithViewPager(mViewPager);
setupTabIcons();
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
dismissKeyboard(mViewPager);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
/**
* Adding custom view to tab
*/
private void setupTabIcons() {
LinearLayout tabOne = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.tab_custom, null);
TextView tvIconOne = (TextView) tabOne.findViewById(R.id.tv_tab_title);
tvIconOne.setText(TAB_1_TAG);
mTabLayout.getTabAt(0).setCustomView(tabOne);
setTypeface(tvIconOne, CustomFonts.Prime_regular);
mTabLayout.getTabAt(0).getCustomView().setSelected(true);
LinearLayout tabTwo = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.tab_custom, null);
TextView tvIconTwo = (TextView) tabTwo.findViewById(R.id.tv_tab_title);
tvIconTwo.setText(TAB_2_TAG);
setTypeface(tvIconTwo, CustomFonts.Prime_regular);
mTabLayout.getTabAt(1).setCustomView(tabTwo);
}
/**
* Adding fragments to ViewPager
*
* #param viewPager The view pager
*/
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
LoginFragment loginFragmentEmail = new LoginFragment();
Bundle emailBundle = new Bundle();
emailBundle.putInt(selectedTabPosition, 0);
loginFragmentEmail.setArguments(emailBundle);
LoginFragment loginFragmentMobile = new LoginFragment();
Bundle phoneBundle = new Bundle();
phoneBundle.putInt(selectedTabPosition, 1);
loginFragmentMobile.setArguments(phoneBundle);
adapter.addFrag(loginFragmentEmail, TAB_1_TAG);
adapter.addFrag(loginFragmentMobile, TAB_2_TAG);
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
Fragment:
public class LoginFragment extends BaseFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_login, container, false);
return rootView;
}
activity_login.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="#android:color/white"
android:orientation="vertical">
<ImageView
android:id="#+id/iv_title"
android:layout_width="200dp"
android:layout_height="45dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
/>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="#dimen/custom_tab_layout_height"
android:layout_below="#+id/iv_title"
android:layout_marginTop="#dimen/spacing_10"
app:tabGravity="fill"
app:tabIndicatorColor="#color/app_color_dark"
app:tabMode="fixed"/>
<View
android:id="#+id/view"
android:layout_width="match_parent"
android:layout_height="#dimen/divider_height_small"
android:layout_below="#+id/tabs"
android:background="#color/gray_medium"/>
<com.helper.CustomNonSwipeableViewpager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/view"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
</RelativeLayout>
fragment_login.xml:
<?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"
android:background="#android:color/white"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/spacing_50"
android:orientation="vertical">
<EditText
android:id="#+id/et_email"
android:layout_width="match_parent"
android:layout_height="#dimen/spacing_48"
/>
<EditText
android:id="#+id/et_password"
android:layout_width="match_parent"
android:layout_height="#dimen/spacing_48"
android:layout_marginTop="#dimen/spacing_15"/>
</LinearLayout>
</RelativeLayout>
AndroidManifest.xml:
<activity
android:name=".activities.LoginActivity"
android:screenOrientation="portrait"
/>
In the AndrodManifest file, tried the
android:windowSoftInputMode = stateHidden and android:windowSoftInputMode = adjustPan
CustomNonSwipeableViewpager.java:
public class CustomNonSwipeableViewpager extends ViewPager {
public CustomNonSwipeableViewpager(Context context) {
super(context);
}
public CustomNonSwipeableViewpager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
}
ScreenShots:
Before moving to FragmentB:
In Fragment B:
Return back to Fragment A from Fragment B:
You can disable the focus on the EditText during runtime of the fragment:
EditText et_email_view = (EditText) rootView.findViewById(R.id.et_email);
et_email_view.setFocusable(false);
Use requestFocus attribute to your first editText which will always cause that editText to gain focus.
Make following changes in your fragment_login.xml file,
<EditText
android:id="#+id/et_email"
android:layout_width="match_parent"
android:layout_height="#dimen/spacing_48">
<requestFocus />
</EditText>
For example in my case viewPager is covering editText. I set translationZ at editText(translationZ="2") and viewPage(translationZ="1") and it helped me.

move from a fragment to another in an activity

From what I understand from this thread, fragments can be easily replaced with another.
However in my case, I have 2 fragments combined in scrollable Activity, so when I say "move", I mean going from the fragment left to the right or right to the left without replacing any fragment with another. Is this somehow possible?
you could use ViewPager for that. And on your adapter class you will have to switch between the fragments via getItem(). Eclipse/new AndroidProject/ swipe with/out tabs. And check the example code generated by Android.
edit:
create xml file call it main_activity.xml
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main" >
<android.support.v4.view.PagerTitleStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="#FAFAFA"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#36466E" />
create a class call it Main
public class Main extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
Context ctx;
static MySQLiteHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
mSectionsPagerAdapter.notifyDataSetChanged();
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch(position){
case 0:
fragment = new GridApp();
break;
case 1:
fragment = new ListApp();
break;
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Select App";
case 1:
return "Selected Apps";
}
return null;
}
}
}
now create a class called GridApp and ListApp
GridApp class.
public class GridApp extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.gridpp,
container, false);
}
}
ListApp class
public class GridApp extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.listapp,
container, false);
}
}
and you are done.

Categories

Resources