Update fragment from activity - android

I do not understand how can I transfer data from fragmentactivity to fragment, i have:
MainScreen.class
public class MainScreen extends FragmentActivity {
CollectionPagerAdapter mCollectionPagerAdapter;
ViewPager mViewPager;
public static String currentCityId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabs_collection);
mCollectionPagerAdapter = new CollectionPagerAdapter(getSupportFragmentManager());
final ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setTitle(getString(R.string.app_name));
actionBar.setIcon(R.drawable.device_access_brightness_high);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCollectionPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
Log.w("Refresh", "refresh");
break;
case R.id.action_options:
break;
case R.id.submenu_about:
break;
case R.id.submenu_help:
break;
case R.id.submenu_buy:
break;
case R.id.submenu_settings:
break;
case R.id.submenu_share:
break;
default:
break;
}
return true;
}
public class CollectionPagerAdapter extends FragmentStatePagerAdapter {
FragmentManager fm;
public CollectionPagerAdapter(FragmentManager fm) {
super(fm);
this.fm = fm;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FragmentDay();
case 1:
return new FragmentHour();
case 2:
return new FragmentDaily();
default:
return new FragmentDay();
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.tab_day);
case 1:
return getString(R.string.tab_hour);
case 2:
return getString(R.string.tab_daily);
default:
return getString(R.string.tab_day);
}
}
}
FragmentDay.class
public class FragmentDay extends Fragment {
TextView currentTemp;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.hour_screen, container, false);
Bundle args = getArguments();
currentTemp = (TextView)rootView.findViewById(R.id.day_current_temp);
return rootView;
}
}
main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:background="#drawable/bk_new">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.PagerTitleStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33b5e5"
android:textColor="#fff"
android:paddingTop="4dp"
android:paddingBottom="4dp"/>
</android.support.v4.view.ViewPager>
and fragment.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/dayScreen"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bk_new">
<TextView
android:id="#+id/day_current_temp"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_centerHorizontal="true"
android:text="22 C"
android:textColor="#FFFFFF"
android:textSize="38dp"
android:layout_marginTop="270dp"/>
Read these articles (ViewPager Activity to notify a Fragment of a specific event, Updating fragments from Activity in a ViewPager, ViewPager - Update fragment from activity) and do not understand what to do!
I will be very grateful for the help!

When you say "transfer data" I'm assuming you mean variables so you can tweak your fragment in whichever way.
You can access the activity object at any time within the fragment using getActivity() method and cast it to your Activity implementation...
// Code in the fragment
((MainScreen) getActivity()).getSomeDataFromActivity()
There is an article here also by Google which describes patterns of communication between Fragment and Activity.

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

Select Tab and run code in its fragment

I have a tab setup with a VeiwPager and a MainActivity. When one particular tab, "B" is selected I want to Show Fragment B user interface and start doing something.
The method I have found to do this is to use a LocalBroadcastReceiver in Fragment "B" and have it call a method. The broadcast is sent from Main Activity inside the onTabSelected method.
Is this a good approach?
Activity.xml
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
app:tabGravity="fill"
app:tabMode="fixed" />
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Activity.class
TabLayout tabLayout;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab);
tabLayout = findViewById(R.id.tabLayout);
viewPager = findViewById(R.id.viewPager);
setUpviewPager();
tabLayout.setupWithViewPager(viewPager);
}
private void setUpviewPager() {
ViewPagerAdpater viewPagerAdapter = new ViewPagerAdpater(getSupportFragmentManager());
viewPager.setAdapter(viewPagerAdapter);
}
private class ViewPagerAdpater extends FragmentPagerAdapter {
ViewPagerAdpater(FragmentManager supportFragmentManager) {
super(supportFragmentManager);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FirsFrag();
case 1:
return new FirsFrag();
case 2:
return new FirsFrag();
default:
return null;
}
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "First Tab";
case 1:
return "Second Tab";
case 2:
return "Third Tab";
default:
return "";
}
}
#Override
public int getCount() {
return 3;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
}
Thanks, just run this code, this adapter is FragmentPagerAdpater

Accessing fragment views from parent Activity simple explanation

I have one activity with 4 fragments. Every fragment got its separate class and layout. This is the parent activity class:
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new MainFragment();
case 1:
return new CatalogFragment();
case 2:
return new FolderFragment();
case 3:
return new SettingsFragment();
default:
return null;
}
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "PLAYER";
case 1:
return "CATALOG";
case 2:
return "FOLDERS";
case 3:
return "SETTINGS";
}
return null;
}
}
Fragment classes are only with:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main,container,false);
return view;
}
and a default constructor.
In FragmentMain i have 2 TextViews. I want to change them dynamically depending on info within MainActivity. I am using ViewPager.
This is my MainActivity XML file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="250dp"
android:id="#+id/imageView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="false" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textView"
android:layout_below="#+id/imageView"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/textView2"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true" />
if i am doing this all wrong please correct me!
I can findViewById() but i cannot set the text(NullPointer).
From the fragment i cannot even findViewById() even thou they are in the MainFragment XML. I've searched a lot and i cannot find easy to understand solution or explanation how this works. Thanks in advance!

Android: PagerTabStrip - set colours etc. in java

I have created a PagerTabStrip for my ViewPager and it is all working fine. Using a switch and case, I have the titles set up for each page. However I can't find how to set the background colour or or text colour within the java. I can change the colour in the xml, but I want the colour to change with my switch and case.
Here is my code:
EDIT: Added more code
public class RemViewPagerActivity extends FragmentActivity {
private static final int NUM_PAGES = 3;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_pager_activity);
mPager = (ViewPager) findViewById(R.id.viewpager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter); /
}
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 1) {
super.onBackPressed();
} else if (mPager.getCurrentItem() == 0){
mPager.setCurrentItem(mPager.getCurrentItem() + 1);
}
else if (mPager.getCurrentItem() == 2){
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter { // Sets the content of the adapter
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) { // Sets the fragment for each position
switch (position) {
case 0: return new Fragment1();
case 1: return new Fragment2();
case 2: return new Fragment3();
}
return null;
}
public CharSequence getPageTitle(int position) {
switch (position) {
case 0: return "1";
case 1: return "2";
case 2: return "3";
}
return null;
}
#Override
public int getCount() { // Sets the number of pages
return NUM_PAGES;
}
}
}
Code of view_pager_activity.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:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<android.support.v4.view.PagerTabStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33b5e5"
android:textColor="#fff"
android:paddingTop="4dp"
android:paddingBottom="4dp" />
</android.support.v4.view.ViewPager>
</RelativeLayout>
Thank you

TabPageIndicator not style properly inside Fragment

I'm trying to put com.viewpagerindicator.TabPageIndicator in the SherlockFragment. While the scrolling of content in ViewPager works very well, the styling of TabPageIndicator is not working properly. This pager hold five fragments and their titles would not fit the width of the screen. I have this working fine in Activity but when I try using this in Fragment, all five titles got cut off to fit the width of the screen.
I tried using both LayoutInflater provided in Fragment#onCreateView and getSystemService both result in the same result.
Not sure if related but I also have com.actionbarsherlock.widget.SearchView in this layout and all the attributes weren't applied.
my_search_layout.xml
<com.viewpagerindicator.TabPageIndicator
android:id="#+id/indicator"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_below="#id/indicator"
/>
</RelativeLayout>
MySearchFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
LayoutInflater themedInflater = (LayoutInflater) getSherlockActivity()
.getSupportActionBar()
.getThemedContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View root = themedInflater.inflate(R.layout.my_search_layout, container, false);
FragmentManager fm = ((Fragment)this).getChildFragmentManager();
mSectionsPagerAdapter = new SectionsPagerAdapter(fm);
mViewPager = (ViewPager) root.findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabPageIndicator indicator = (TabPageIndicator) root.findViewById(R.id.indicator);
indicator.setViewPager(mViewPager);
return root;
}
SectionsPagerAdapter
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = null;
Log.d(TAG, "SectionsPagerAdapter: " + i);
fragment = new HelloFragment();
return fragment;
}
#Override
public int getCount() {
return 5;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.section_title_page_1);
case 1:
return getString(R.string.section_title_page_2);
case 2:
return getString(R.string.section_title_page_3);
case 3:
return getString(R.string.section_title_page_4);
case 4:
return getString(R.string.section_title_page_5);
}
return null;
}
}

Categories

Resources