I am using a ViewPager with a FragmentPagerAdapter. Each page is an instance of the same Fragment class, I am always using a fixed number of 7 pages (days of the week starting with today). Debugging shows that all Fragments are getting created and have the correct data at the time of creation. One interesting thing is although the adapter is creating the fragments in the order 0, 1, 2...6, the onCreateView of the fragments is called in the order 6, 0, 1, 2...5.
When run the app and open this activity, the first fragment page is blank, and then I can slide through the tabs and see that all of the pages are blank except the last one. But, the last page is not displaying the data from the last day, it is displaying one day eariler than it should, the next-to-last set of data.
I copied another ViewPager / FragmentPagerAdapter that I have that works, although that one has only 3 pages and uses a different Fragment for each page.
I am not seeing what I am doing wrong, I have been searching all day and have not found an answer yet. A lot of similar questions on here are resolved by using FragmentStatePagerAdapter instead of FragmentPagerAdapter. I already tried that and it behaves exactly the same as currently.
This is the activity hosting the ViewPager:
public class ForecastFaveRowClickedActivity extends AppCompatActivity {
String distName = "";
public List<ForecastEntry> forecastEntries = new ArrayList<>();
ForecastPagerAdapter adapterViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forecast_detail);
// get the districts from the main activity
Bundle bundle = getIntent().getExtras();
distName = bundle.getString("districtName");
if (bundle.containsKey("forecastData")) {
forecastEntries = bundle.getParcelableArrayList("forecastData");
}
Collections.sort(forecastEntries);
// set up viewpager and display the first tab
// ViewPager for tabs
ViewPager viewPager = (ViewPager) findViewById(R.id.forecast_pager);
adapterViewPager = new ForecastPagerAdapter(getSupportFragmentManager(), ForecastFaveRowClickedActivity.this);
viewPager.setOffscreenPageLimit(7);
// set the tab titles based on the forecast list for this district
String[] days = new String[7];
int count = 0;
for (ForecastEntry forecastEntry : forecastEntries) {
days[count] = forecastEntry.forecastDay.substring(0,3);
count++;
}
adapterViewPager.setTabTitles(days);
viewPager.setAdapter(adapterViewPager);
//viewPager.setCurrentItem(0); // set to today's tab to start with
// give the tab layout to the viewpager
TabLayout tabLayout = (TabLayout) findViewById(R.id.forecast_sliding_date_tabs);
tabLayout.setupWithViewPager(viewPager);
}
// class for view pager adapter
public class ForecastPagerAdapter extends FragmentPagerAdapter {
private int NUM_ITEMS = 7;
private String tabTitles[] = new String[7];
private Context context;
public ForecastPagerAdapter(FragmentManager fm) {
super(fm);
}
public ForecastPagerAdapter(FragmentManager fragmentManager, Context context) {
super(fragmentManager);
this.context = context;
}
// returns total # of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
Fragment frag = new Fragment();
ForecastEntry forecastEntry;
Log.v("Fragment.getItem", Integer.toString(position));
forecastEntry = ((ForecastFaveRowClickedActivity)context).forecastEntries.get(position);
frag = FragmentForecastDay.newInstance(position, forecastEntry);
return frag;
}
// returns the page title for the top indicator
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
public void setTabTitles(String[] days) {
tabTitles = Arrays.copyOf(days, days.length);
}
}
}
This is the layout for that activity:
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.districtoverview.ForecastFaveRowClickedActivity">
<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_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:titleTextColor="#color/colorWhite"
android:elevation="4dp"
android:theme="#style/AppTheme.AppBarOverlay"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<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:paddingBottom="6dp"
android:paddingTop="6dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.districtoverview.ForecastFaveRowClickedActivity"
tools:showIn="#layout/activity_forecast_detail"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/forecast_sliding_date_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingBottom="2dp"
android:paddingTop="2dp"
app:tabMode="scrollable"
app:tabGravity="fill"
style="#style/customForecastTabLayout" />
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/forecast_pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white"
tools:context="com.districtoverview.ForecastFaveRowClickedActivity">
</android.support.v4.view.ViewPager>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
This is the code for the Fragment class.
public class FragmentForecastDay extends Fragment {
String label;
int page;
ForecastEntry forecastEntry;
public static FragmentForecastDay newInstance(int page, ForecastEntry forecastEntry) {
FragmentForecastDay fragment = new FragmentForecastDay();
Bundle args = new Bundle();
args.putParcelable("forecastEntry", forecastEntry);
args.putInt("page", page);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_forecast_day, container, false);
page = getArguments().getInt("page", 0);
forecastEntry = getArguments().getParcelable("forecastEntry");
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView headerDistNameTV = (TextView) getActivity().findViewById(R.id.dist_name_header_text);
headerDistNameTV.setText(parentActivity.distName);
TextView headerForecastDateTV = (TextView) getActivity().findViewById(R.id.forecast_date_header_text);
headerForecastDateTV.setText(forecastEntry.forecastDate);
TextView headerTotalTechsTV = (TextView) getActivity().findViewById(R.id.total_techs_header_text); headerTotalTechsTV.setText(Double.toString(forecastEntry.totalTechs));
TextView headerDayShiftTV = (TextView) getActivity().findViewById(R.id.day_shift_header_text);
headerDayShiftTV.setText("Day Shift");
TextView dayExpectedTechsTV = (TextView) getActivity().findViewById(R.id.day_shift_expected_text);
String dayExpectedTechs = "Expected " + Double.toString(forecastEntry.expectedTechs);
dayExpectedTechsTV.setText(dayExpectedTechs);
TextView headerAfterHoursTV = (TextView) getActivity().findViewById(R.id.after_hours_header_text);
headerAfterHoursTV.setText("After Hours");
TextView afterHoursExpectedTechsTV = (TextView) getActivity().findViewById(R.id.day_shift_expected_text);
String afterHoursExpectedTechs = "Expected " + Double.toString(forecastEntry.afterHoursExpected);
afterHoursExpectedTechsTV.setText(afterHoursExpectedTechs);
}
}
This is the fragment layout:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/forecast_day_table_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.90"
android:paddingTop="4dp"
android:paddingBottom="4dp"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:weightSum="1">
<TableRow
android:id="#+id/row_dist_name_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.50">
<TextView
android:id="#+id/dist_name_header_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:textAppearance="?android:attr/textAppearanceLarge"
android:paddingBottom="5dp" />
</TableRow>
<TableRow
android:id="#+id/row_date_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.50">
<TextView
android:id="#+id/forecast_date_header_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:textAppearance="?android:attr/textAppearanceLarge"
android:paddingBottom="5dp" />
</TableRow>
<TableRow
android:id="#+id/row_total_techs_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.50">
<TextView
android:id="#+id/total_techs_header_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:textAppearance="?android:attr/textAppearanceLarge"
android:paddingBottom="5dp" />
</TableRow>
<TableRow
android:id="#+id/row_total_techs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.50">
<TextView
android:id="#+id/total_techs_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:textAppearance="?android:attr/textAppearanceLarge"
android:paddingBottom="5dp" />
</TableRow>
<TableRow
android:id="#+id/row_day_shift_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.50">
<TextView
android:id="#+id/day_shift_header_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:textAppearance="?android:attr/textAppearanceLarge"
android:paddingBottom="5dp" />
</TableRow>
<TableRow
android:id="#+id/row_day_shift_expected"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.50">
<TextView
android:id="#+id/day_shift_expected_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:textAppearance="?android:attr/textAppearanceLarge"
android:paddingBottom="5dp" />
</TableRow>
<TableRow
android:id="#+id/row_after_hours_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.50">
<TextView
android:id="#+id/after_hours_header_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:textAppearance="?android:attr/textAppearanceLarge"
android:paddingBottom="5dp" />
</TableRow>
<TableRow
android:id="#+id/row_after_hours_expected"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.50">
<TextView
android:id="#+id/after_hours_expected_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:textAppearance="?android:attr/textAppearanceLarge"
android:paddingBottom="5dp" />
</TableRow>
</TableLayout>
This was caused by my incorrect use of getActivity() rather than view. I had copied the code from another set of swipe tabs which was sitting on the main activity, but this set was inside of a fragment. I needed to refer to the view of the parent fragment.
So for example this:
(TextView) getActivity().findViewById(R.id.dist_name_header_text);
Should have been this:
(TextView) view.findViewById(R.id.dist_name_header_text);
Once I made this change all child fragments used in the view pager were displayed correctly.
one potential problem might be that all the seven fragments are not created properly at the time of viewpager creation.so your activity code would be as shown below
// set up viewpager and display the first tab
// ViewPager for tabs
ViewPager viewPager = (ViewPager) findViewById(R.id.forecast_pager);
adapterViewPager = new ForecastPagerAdapter(getSupportFragmentManager(), ForecastFaveRowClickedActivity.this);
viewPager.setOffscreenPageLimit(7);
Related
I've made Activity with ViewPager and I also have adapter for it and Fragment which is displayed by ViewPager. Whole Fragment (in XML) is inside ScrollView. When I'm scrolling page up and down the indicator doesn't scroll with whole layout.
I know the reason why this is happening (indicator is inside Activity layout and ScrollView is inside Fragment XML file). I need some help or advice how to make it scroll or any other solution how to avoid that because indicator at "start position" is looking good but when I scroll down it covers part of text.
I know it is possible because I've seen it on Instagram but I don't know how to achieve this.
Let me provide some code:
Activity with ViewPager:
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Album.AlbumPagerActivity">
<android.support.design.widget.FloatingActionButton
android:id="#+id/album_pager_fab_left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="10dp"
android:layout_marginStart="15dp"
android:alpha=".7"
android:backgroundTint="#color/CKBrownie"
android:elevation="2dp"
android:scaleType="center"
android:src="#drawable/back_ico"
android:tint="#color/CKGold"
android:translationZ="0dp"
app:backgroundTint="#color/CKBrownie" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/album_pager_fab_right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="10dp"
android:layout_marginEnd="15dp"
android:alpha=".7"
android:backgroundTint="#color/CKBrownie"
android:elevation="2dp"
android:scaleType="center"
android:src="#drawable/forward_ico"
android:tint="#color/CKGold"
android:translationZ="0dp"
app:backgroundTint="#color/CKBrownie" />
<android.support.v4.view.ViewPager
android:id="#+id/album_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
<me.relex.circleindicator.CircleIndicator
android:id="#+id/indicator"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_alignTop="#+id/album_view_pager"
android:layout_marginTop="#dimen/_360sdp" />
</RelativeLayout>
Fragment:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
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:background="#drawable/backgroudmck">
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Album.PhotoFragment">
<com.github.chrisbanes.photoview.PhotoView
android:id="#+id/photo_pager_image"
android:layout_width="#dimen/_240sdp"
android:layout_height="#dimen/_360sdp"
android:layout_marginTop="#dimen/_12sdp"
android:background="?android:attr/selectableItemBackground"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/photo_pager_image_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/_24sdp"
android:layout_marginTop="#dimen/_16sdp"
android:layout_marginEnd="#dimen/_24sdp"
android:gravity="left"
android:text="Image title"
android:textColor="#FFFFFF"
android:textSize="22sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/photo_pager_image" />
<LinearLayout
android:id="#+id/underline_photo_fragment"
android:layout_width="match_parent"
android:layout_height="#dimen/_2sdp"
android:layout_marginStart="#dimen/_22sdp"
android:layout_marginTop="#dimen/_20sdp"
android:layout_marginEnd="#dimen/_22sdp"
android:background="#color/CKGold"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/photo_pager_image_title" />
<TextView
android:id="#+id/photo_pager_image_technique"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/_24sdp"
android:layout_marginTop="#dimen/_8sdp"
android:layout_marginEnd="#dimen/_24sdp"
android:textSize="#dimen/_18sdp"
android:text="Additional info about image"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/underline_photo_fragment" />
<TextView
android:id="#+id/photo_pager_image_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/_24sdp"
android:layout_marginTop="#dimen/_16sdp"
android:layout_marginEnd="#dimen/_24sdp"
android:layout_marginBottom="#dimen/_2sdp"
android:textSize="#dimen/_18sdp"
android:text="Long image description (because of this TextView I had to make it scrollable)"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/photo_pager_image_technique" />
</android.support.constraint.ConstraintLayout>
</ScrollView>
Adapter:
public class AlbumViewPagerAdapter extends FragmentStatePagerAdapter {
private int number;
public AlbumViewPagerAdapter(FragmentManager fm, int number) {
super(fm);
this.number = number;
}
#Override
public Fragment getItem(int i) {
PhotoFragment pf;
Bundle bundle;
switch (i) {
case 0:
bundle = new Bundle();
bundle.putInt("num", i);
bundle.putInt(Constants.NUMBER, number);
pf = new PhotoFragment();
pf.setArguments(bundle);
return pf;
case 1:
bundle = new Bundle();
bundle.putInt("num", i);
bundle.putInt(Constants.NUMBER, number);
pf = new PhotoFragment();
pf.setArguments(bundle);
return pf;
case 2:
bundle = new Bundle();
bundle.putInt("num", i);
bundle.putInt(Constants.NUMBER, number);
pf = new PhotoFragment();
pf.setArguments(bundle);
return pf;
}
return null;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
Object obj = super.instantiateItem(container, position);
return obj;
}
#Override
public int getCount() {
return 3;
}
}
Instagram app has a ViewPager with indicator placed below a photo but above a text and when I navigate between "pages" the text and the photo are changing but when I scroll page up/down the indicator move with whole page up and down. Maybe it's a problem with my indicator placement? But when I try to put it inside the Fragment I won't be able to attach it to my ViewPager which is created inside Activity
I have this layout
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/header_cover_image"
android:layout_width="match_parent"
android:layout_height="150dp"
android:scaleType="centerCrop"
android:background="#color/com_facebook_button_background_color_pressed" />
<refractored.controls.CircleImageView
android:id="#+id/imageProfile"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_below="#+id/header_cover_image"
android:layout_centerHorizontal="true"
android:layout_marginTop="-60dp"
android:layout_gravity="center_horizontal"
android:elevation="5dp"
android:padding="20dp"
android:scaleType="centerCrop" />
<RelativeLayout
android:id="#+id/profile_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/header_cover_image"
android:background="#ebca0707"
android:elevation="4dp"
android:paddingBottom="24dp">
<ImageView
android:id="#+id/add_friend"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:src="#drawable/played" />
<ImageView
android:id="#+id/drop_down_option_menu"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:src="#drawable/wins"
android:layout_width="30dp"
android:layout_toLeftOf="#+id/drop_down_option_menu"
android:layout_marginRight="16dp"
android:layout_marginTop="16dp" />
<TextView
android:id="#+id/user_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="76dp"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="#+id/userStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/user_name"
android:text="Status"
android:textColor="#fff"
android:textSize="14sp"
android:layout_marginLeft="16dp"
android:layout_marginTop="15dp"
android:layout_centerHorizontal="true" />
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/profilePager"
>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/profile_layout"
android:elevation="6dp"
android:background="?android:attr/colorPrimary"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_below="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
</ScrollView>
The last LinearLayout shows the Tabs but when i switch them there is no viewpager data whatsoever . I tried creating another layout for the tablayout but it still wont work .. Im calling this from a fragment as follows :
public class ProfileFragment : Fragment
{
private static Context _context;
private static Xamarin.Facebook.Profile _profile;
private CircleImageView imgProfile;
private TextView userName;
private TabLayout tabLayout;
private ViewPager viewpager;
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your fragment here
}
public static Fragment NewInstance(Activity context , Xamarin.Facebook.Profile profile)
{
_context = context;
_profile = profile;
Fragment fragment = new ProfileFragment();
return fragment;
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.Inflate(Resource.Layout.fragmentProfile, container, false);
imgProfile = view.FindViewById<CircleImageView>(Resource.Id.imageProfile);
tabLayout =view.FindViewById<TabLayout>(Resource.Id.tab_layout);
viewpager = view.FindViewById<ViewPager>(Resource.Id.pager);
userName = view.FindViewById<TextView>(Resource.Id.user_name);
userName.Text = _profile.Name;
Picasso.With(_context).Load(_profile.GetProfilePictureUri(180, 180)).Into(imgProfile);
FnInitTabLayout();
return view;
}
void FnInitTabLayout()
{
tabLayout.SetTabTextColors(Android.Graphics.Color.Aqua, Android.Graphics.Color.AntiqueWhite);
//Fragment array
var fragments = new Fragment[]
{
new ActivityFragment(),
new SportsFragment(),
new AboutFragment()
};
//Tab title array
var titles = CharSequence.ArrayFromStringArray(new[] {
"Feed",
"Sports",
"About",
});
//viewpager holding fragment array and tab title text
viewpager.Adapter = new ProileTabsAdapter(FragmentManager, fragments, titles);
tabLayout.SetupWithViewPager(viewpager);
}
}
When i put it inside an activity and without the above layout only the tab and the viewpager they work perfectly but in this scenario not . Can anyone think of what am i doing wrong ?
EDIT :
Here is the pager adapter
public class ProileTabsAdapter : FragmentPagerAdapter
{
private readonly Fragment[] fragments;
private readonly ICharSequence[] titles;
public ProileTabsAdapter(FragmentManager fm, Fragment[] fragments, ICharSequence[] titles) : base(fm)
{
this.fragments = fragments;
this.titles = titles;
}
public override int Count
{
get
{
return fragments.Length;
}
}
public override Fragment GetItem(int position)
{
return fragments[position];
}
public override ICharSequence GetPageTitleFormatted(int position)
{
return titles[position];
}
}
Use android:fillViewport="true" into your ScrollView.
wrap_content of view pager won't work inside Scrollview.
ViewPager doesn't support width="wrap_content" or height="wrap_content" attrs.
Solutions here : I am unable to have ViewPager WRAP_CONTENT
You can also use this library : WCViewPager (Wrap Content ViewPager)
First of all my English is not too good. But i will try to understand my point to you people.
I am making app in which i used scroll view and inside it many other layout with API xml's and also view pager.You can see below
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:tools="http://schemas.android.com/tools"
xmlns:custom="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.iptikarpromotion.activity.LoaderActivity" >
<ScrollView
android:id="#+id/scrollview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#color/background_color" >
<LinearLayout
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.daimajia.slider.library.SliderLayout
android:id="#+id/slider"
android:layout_width="match_parent"
android:layout_height="155dp"
custom:auto_cycle="true"
custom:indicator_visibility="visible"
custom:pager_animation="Accordion"
custom:pager_animation_span="1100" />
<com.daimajia.slider.library.Indicators.PagerIndicator
android:id="#+id/custom_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:gravity="center"
custom:selected_color="#color/primary"
custom:selected_drawable="#drawable/ic_launcher"
custom:selected_height="6dp"
custom:selected_padding_left="6dp"
custom:selected_padding_right="6dp"
custom:selected_width="6dp"
custom:shape="oval"
custom:unselected_color="#55333333"
custom:unselected_height="6dp"
custom:unselected_padding_left="2dp"
custom:unselected_padding_right="2dp"
custom:unselected_width="6dp" />
<com.daimajia.slider.library.Indicators.PagerIndicator
android:id="#+id/custom_indicator2"
style="#style/AndroidImageSlider_Corner_Oval_Orange"
android:layout_marginBottom="20dp" />
<--! Many other Linear and RelativeLayout is used here-->
<!-- For Viewpager -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="15dp" >
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/quickly"
android:textColor="#color/current_deals_color"
android:textSize="15sp" >
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView3"
android:layout_marginTop="-3dp"
android:text="#string/sub_quickly" android:textColor="#color/all_categories_sub_title_color"
android:textSize="10sp"
android:textStyle="italic" />
</RelativeLayout>
<LinearLayout
android:id="#+id/rootContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
android:orientation="vertical" >
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/sliding_tabs"
style="#style/PagerTabStripText"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_below="#+id/my_awesome_toolbar"
android:background="#drawable/bg_quickly_pick"
android:paddingBottom="3sp"
android:textSize="10sp"
app:pstsDividerColor="#android:color/transparent"
app:pstsIndicatorColor="#color/indicator_color"
app:pstsIndicatorHeight="3dp"
app:pstsTabPaddingLeftRight="15dip"
app:pstsUnderlineColor="#android:color/transparent" />
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</android.support.v4.view.ViewPager>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</ScrollView>
</RelativeLayout>
And here id my code below
public class FragmentHome extends Fragment implements ViewPager.OnPageChangeListener {
private ViewPager viewPager;
private TabPagerAdapter PagerAdapter;
private static int pageIndexd;
private PagerSlidingTabStrip pagerSlidingTabStrip;
LinearLayout ll_jewellery = null;
private SliderLayout mDemoSlider;
ScrollView scrollView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home_layout, null);
scrollView = (ScrollView)rootView.findViewById(R.id.scrollview);
viewPager = (ViewPager) rootView.findViewById(R.id.pager);
rootView.findViewById(R.id.layout);
pagerSlidingTabStrip = (PagerSlidingTabStrip) rootView.findViewById(R.id.sliding_tabs);
mDemoSlider = (SliderLayout)rootView.findViewById(R.id.slider);
imageSlider();
ll_jewellery = (LinearLayout)rootView.findViewById(R.id.ll_jewellery);
CategoryLayoutClikListener categoryLayoutClikListener = new CategoryLayoutClikListener();
ll_jewellery.setOnClickListener(categoryLayoutClikListener);
viewPager.setOffscreenPageLimit(1);
pageIndexd = viewPager.getCurrentItem();
viewPager.setCurrentItem(pageIndexd);
FragmentManager fm = getFragmentManager();
PagerAdapter = new TabPagerAdapter(fm);
setAdapter();
return rootView;
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int position) {
}
private void imageSlider(){
HashMap<String,String> url_maps = new HashMap<String, String>();
url_maps.put("Hannibal", "http://static2.hypable.com/wp-content/uploads/2013/12/hannibal-season-2-release-date.jpg");
url_maps.put("Big Bang Theory", "http://tvfiles.alphacoders.com/100/hdclearart-10.png");
url_maps.put("House of Cards", "http://cdn3.nflximg.net/images/3093/2043093.jpg");
url_maps.put("Game of Thrones", "http://images.boomsbeat.com/data/images/full/19640/game-of-thrones-season-4-jpg.jpg");
for(String name : url_maps.keySet()){
TextSliderView textSliderView = new TextSliderView(getActivity());
// initialize a SliderLayout
textSliderView.description(name).image(url_maps.get(name)).setScaleType(BaseSliderView.ScaleType.Fit);
//.setOnSliderClickListener(this);
//add your extra information
textSliderView.getBundle().putString("extra",name);
mDemoSlider.addSlider(textSliderView);
}
mDemoSlider.setPresetTransformer(SliderLayout.Transformer.Default);
mDemoSlider.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
mDemoSlider.setCustomAnimation(new DescriptionAnimation());
mDemoSlider.setDuration(4000);
}
private void setAdapter() {
viewPager.setAdapter(PagerAdapter);
pagerSlidingTabStrip.setViewPager(viewPager);
}
private class CategoryLayoutClikListener implements OnClickListener {
#Override
public void onClick(View v) {
}
}
}
So i want to scroll my whole view, and on scroll below viewpager should be stick with toolbar. In xml you can see my viewpager stick below on end of scroll view. no movement up and down. i want to scroll up and stick with toolbar and than scroll down to its position. How can i achieve this.
I follow this below link too and make many many changes but it doesnt help me.At the end i clean my code to original position.
https://github.com/kmshack/Android-ParallaxHeaderViewPager
http://architects.dzone.com/articles/how-make-google-plus-profile
Thanks
Aim:
Create a activity that have two buttons, button 1 and button 2. When click, the fragment will alternate between the two fragments.
Background:
Fragmentone will take the edittext from the main activity and settext on the textview on the fragment.
Fragmenttwo will take display text to the tablelayout. (My ultimate goal is to use the input from the main activty and display it to one of the textview of the table, but it is not working, kindly advise on that)##issue 1
Problems:
The button1 that is supposed to display fragmentone is not working. After keying in the input into the edittext on the mainactivity, when i click the button, the fragmenttwo persist. FragmentOne did not come out. Place an toast in fragmentone and the toast display my input.
Special Thanks to:
Would like to extend a special thanks to helpful people in this community for guiding me this far. And will like to extend my thanks to Raghunandan who guide me through fragment advance I, II. Thanks you very much for assisting me through my learning journey. Hope my questions and raghunandan advice would help reduce the learning curve for those embraking on this journey.
Fragment Intermediate (I)
Fragment Intermediate(I):Getting input from edittext, set text in textview of a fragment
Fragment Intermediate (II)
Fragment Intermediate (II):Dynmically adding row in a fragment, Android
MainActivity.java
import android.os.Bundle;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void selectFrag(View view) {
Fragment fr;
if(view == findViewById(R.id.button2)) {
fr = new FragmentTwo();
}
else {
fr = new FragmentOne();
}
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TableLayout
android:id="#+id/TableLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/dis_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Input" />
<EditText
android:id="#+id/input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
</TableRow>
<TableRow
android:id="#+id/tableRow9"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="selectFrag"
android:text="Button2" />
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="selectFrag"
android:text="Calculate" />
</TableRow>
</TableLayout>
</FrameLayout>
<fragment
android:name="com.example.sample.FragmentTwo"
android:id="#+id/fragment_place"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
FragmentOne.java
public class FragmentOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_one, container, false);
TextView warcraft= (TextView) view.findViewById(R.id.moargold);
EditText moargold = (EditText) getActivity().findViewById(R.id.input);
Double vespenegas = Double.parseDouble(moargold.getText().toString());
warcraft.setText(new Double(vespenegas).toString());
Toast toast = Toast.makeText(getActivity(),new Double(vespenegas).toString() , Toast.LENGTH_SHORT);
toast.show();
return view;
}
}
fragment_one.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TableLayout
android:id="#+id/TableLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1" >
<TableRow
android:id="#+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/dis_moargold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gold Count:" />
<TextView
android:id="#+id/moargold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</TableRow>
</TableLayout>
</LinearLayout>
FragmentTwo.java
public class FragmentTwo extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_two, container, false);
EditText input = (EditText) getActivity().findViewById(R.id.input);
TableLayout tl=(TableLayout) view.findViewById(R.id.mainLayout);
TableRow tr = new TableRow(getActivity());
tr.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
TextView textview1 = new TextView(getActivity());
textview1.setText("happy");
tr.addView(textview1);
TextView textview2 = new TextView(getActivity());
textview2.setText("unhappy");
//###############To insert text from editview to table
// Double buygas = Double.parseDouble(input.getText().toString());
// textview2.setText(new Double(buygas).toString());
tr.addView(textview2);
tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
return view;
}
}
fragment_two.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ffff00">
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/mainLayout">
<TableRow
android:id="#+id/infoRow"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:text="First"
android:id="#+id/column1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<TextView
android:text="Second"
android:id="#+id/column2"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
</TableRow>
</TableLayout>
</LinearLayout>
Just have the FrameLayout and EditText in activity_main.xml. FrameLayout is a container (ViewGroup) to which you add or replace fragments. Your TableLayout can be in fragment layout.
You are adding/replacing fragment programatically so what is the need to have the same in xml.
Have this in activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<EditText
android:id="#+id/input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:ems="10" >
<requestFocus />
</EditText>
<FrameLayout
android:id="#+id/container" // id is container
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/button1"
android:layout_below="#+id/input"
>
</FrameLayout>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/input"
android:onClick="selectFrag"
android:text="Button1" />
<Button
android:id="#+id/button2"
android:onClick="selectFrag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/input"
android:layout_alignParentBottom="true"
android:text="Button2" />
</RelativeLayout>
Then in MainActivity
public class MainActivity extends Activity {
Fragment fr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void selectFrag(View view) {
if(view == findViewById(R.id.button2)) {
fr = new FragmentTwo();
}
else {
fr = new FragmentOne();
}
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container, fr);
fragmentTransaction.commit();
}
}
FragmentOne
public class FragmentOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.frag1, container, false);
TextView warcraft= (TextView) view.findViewById(R.id.moargold);
EditText moargold = (EditText) getActivity().findViewById(R.id.input);
Double vespenegas = Double.parseDouble(moargold.getText().toString());
warcraft.setText(String.valueOf(vespenegas));
Toast toast = Toast.makeText(getActivity(),String.valueOf(vespenegas) , Toast.LENGTH_SHORT);
toast.show();
return view;
}
}
frag1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TableLayout
android:id="#+id/TableLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1" >
<TableRow
android:id="#+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/dis_moargold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gold Count:" />
<TextView
android:id="#+id/moargold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</TableRow>
</TableLayout>
</LinearLayout>
FragmentTwo
public class FragmentTwo extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.frag2, container, false);
EditText input = (EditText) getActivity().findViewById(R.id.input);
TableLayout tl=(TableLayout) view.findViewById(R.id.TableLayout01);
TableRow tr = new TableRow(getActivity());
tr.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
TextView textview1 = new TextView(getActivity());
textview1.setText("happy");
tr.addView(textview1);
TextView textview2 = new TextView(getActivity());
textview2.setText("unhappy");
//###############To insert text from editview to table
// Double buygas = Double.parseDouble(input.getText().toString());
// textview2.setText(new Double(buygas).toString());
tr.addView(textview2);
tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
return view;
}
}
frag2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TableLayout
android:id="#+id/TableLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1" >
<TableRow
android:id="#+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/dis_moargold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gold Count:" />
<TextView
android:id="#+id/moargold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</TableRow>
</TableLayout>
</LinearLayout>
Snap
While you add your Fragments dynamically, you keep your FragmentTwo inside your layout. Try to remove this in your layout:
<fragment
android:name="com.example.sample.FragmentTwo"
android:id="#+id/fragment_place"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Also, in your code, you add dynamically a Fragment and with replace method, you set the container as id fragment_place:
fragmentTransaction.replace(R.id.fragment_place, fr);
However, this id is using by your fragment (FragmentTwo, the first piece of code above) and you cannot replace a fragment which is not added dynamically. You need to host your fragment inside a FrameLayout but yours has no id, try to add this:
<FrameLayout
android:id="#+id/fragment_place" /// this line to create and id
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
Then, you will be able to host, add and replace your fragments into your framelayout as you want.
New android developer here. I am trying to create a dynamic UI that loads based on the users selection of a RadioGroup. Based on their selection, one of 3 possible fragments will be loaded into a LinearLayout section. This is my first attempt at my own sample problem that is not just a walk-through tutorial. Here is the main activity:
public class BaseConverter extends Activity {
RadioGroup convert;
Fragment toFragment;
RadioGroup toRadioGroup = null;
TextView inputDisplay = null;
TextView outputDisplay = null;
TextView resultTitle = null;
#Override
public void onCreate(Bundle sIS) {
super.onCreate(sIS);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(R.layout.base_converter);
convert = (RadioGroup) this.findViewById(R.id.bc_convert_group);
convert.setOnCheckedChangeListener(new ConvertListener());
FragmentManager fm = getFragmentManager();
FragmentTransaction converterFragment = fm.beginTransaction();
ConvertEmptyFragment emptyTo = new ConvertEmptyFragment();
converterFragment.replace(R.id.bc_converter_fragment, emptyTo);
converterFragment.commit();
FragmentTransaction toFragment = fm.beginTransaction();
ConvertEmptyFragment emptyConverter = new ConvertEmptyFragment();
toFragment.replace(R.id.bc_to_fragment, emptyConverter);
toFragment.commit();
}
#Override
public void onResume() {
convert.clearCheck();
super.onResume();
}
#Override
public void onPause() {
convert.clearCheck();
super.onPause();
}
// I put a little null check so you can see how I'm trying to access the TextViews and what results
public void updateUIComponents(){
View converterView = this.findViewById(R.id.bc_converter_fragment);
inputDisplay = (TextView)converterView.findViewById(R.id.bc_display_input);
outputDisplay = (TextView)converterView.findViewById(R.id.bc_display_output);
if (inputDisplay == null){
Log.d("BaseConverter", "inputDisplay == null");
} else {
Log.d("BaseConverter", "inputDisplay != null");
}
}
class ConvertListener implements OnCheckedChangeListener {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Fragment toFragment;
Fragment converterFragment;
switch (checkedId) {
case R.id.bc_convert_binary:
toFragment = new ConvertRBFragmentBinary();
converterFragment = new ConverterFragmentBinary();
break;
case R.id.bc_convert_decimal:
toFragment = new ConvertRBFragmentDecimal();
converterFragment = new ConverterFragmentDecimal();
break;
case R.id.bc_convert_hex:
toFragment = new ConvertRBFragmentHex();
converterFragment = new ConverterFragmentHex();
break;
default:
toFragment = new ConvertEmptyFragment();
converterFragment = new ConvertEmptyFragment();
break;
}
FragmentManager fm = getFragmentManager();
FragmentTransaction converterTransaction = fm.beginTransaction();
converterTransaction.replace(R.id.bc_converter_fragment, converterFragment);
converterTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
converterTransaction.commit();
FragmentTransaction toTransaction = fm.beginTransaction();
toTransaction.replace(R.id.bc_to_fragment, toFragment);
toTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
toTransaction.commit();
updateUIComponents();
}
}
So, based on what a user chooses, the proper fragments will be loaded into the respective LinearLayout sections. However, now I want to implement the business logic of the fragments (which is just integer base conversion; i.e. binary number to decimal...) but when I try to access the TextViews, as seen in the updateUIComponents method, I get null pointers. What am I missing?
Here's the ConverterFragmentBinary class for reference:
public class ConverterFragmentBinary extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sIS){
View v = inflater.inflate(R.layout.converter_fragment_binary, container, false);
return v;
}
}
and its respective xml layout for reference:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF000000"
android:gravity="center_horizontal"
android:orientation="vertical" >
<ImageView
android:id="#+id/bc_binary_converter_logo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="15dip"
android:maxHeight="30dip"
android:src="#drawable/binary_converter" />
<TextView
android:id="#+id/bc_display_input"
style="#style/input_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dip"
android:layout_marginLeft="15dip"
android:layout_marginRight="15dip"
android:layout_marginTop="5dip"
android:gravity="center_vertical|right"
android:lines="1"
android:minHeight="30sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FF000000"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<Button
android:id="#+id/button_num_0"
style="#style/op_button_land"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dip"
android:gravity="center"
android:onClick="num0"
android:text="#string/num_0" />
<Button
android:id="#+id/button_num_1"
style="#style/op_button_land"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dip"
android:gravity="center"
android:onClick="num1"
android:text="#string/num_1" />
</LinearLayout>
<TextView
android:id="#+id/bc_result_title"
style="#style/radio_button_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dip"
android:layout_marginRight="5dip"
android:layout_marginTop="10dip"
android:gravity="left"
android:text="#string/choose_convert" />
<TextView
android:id="#+id/bc_display_output"
style="#style/display_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15dip"
android:layout_marginRight="15dip"
android:layout_marginTop="5dip"
android:gravity="center_vertical|right"
android:lines="1"
android:minHeight="30sp" />
</LinearLayout>
and then heres the main activity it gets loaded into:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/base_conversion_layout"
style="#style/layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="5"
android:baselineAligned="false"
android:gravity="center_vertical|left"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="2"
android:orientation="vertical" >
<TextView
style="#style/radio_button_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/convert" />
<RadioGroup
android:id="#+id/bc_convert_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="5dip" >
<RadioButton
android:id="#+id/bc_convert_binary"
style="#style/radio_button"
android:text="#string/binary" />
<RadioButton
android:id="#+id/bc_convert_decimal"
style="#style/radio_button"
android:text="#string/decimal" />
<RadioButton
android:id="#+id/bc_convert_hex"
style="#style/radio_button"
android:text="#string/hex" />
</RadioGroup>
</LinearLayout>
<LinearLayout
android:id="#+id/bc_to_fragment"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="3"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/bc_converter_fragment"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="13"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
Thanks in advance and sorry for the long code blocks but I figured it was better to include more than less.
Also, you should inflate your Fragments layout to bring it from your XML to your Java code instead of simply referring it using findViewById() method.
So instead of doing this,
View converterView = this.findViewById(R.id.bc_converter_fragment);
Do this inside your onCreateView method of the fragment,
View converterView = infalter.inflate(R.id.bc_converter_fragment,null);
updateUIComponents(converterView);//call this methid and pass your view
new method looks like this,
public void updateUIComponents(View converterView){
inputDisplay = (TextView)converterView.findViewById(R.id.bc_display_input);
outputDisplay = (TextView)converterView.findViewById(R.id.bc_display_output);
if (inputDisplay == null){
Log.d("BaseConverter", "inputDisplay == null");
} else {
Log.d("BaseConverter", "inputDisplay != null");
}
}