Why is my TextView not centerInParent in my ViewPager fragment? - android

My TextView has layout_centerInParent="true" and looks good in the layout preview in Android Studio, but when I compile and run the "Let's Get Started" text ends up near the bottom as shown below. Why is this happening?
Fragment 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:id="#+id/intro_background"
android:background="#color/primary">
<TextView
android:id="#+id/tv_welcome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:maxWidth="240sp"
android:gravity="center"
android:textSize="45sp"
android:textStyle="bold"
android:textColor="#color/white"
android:text="Let\'s Get Started!"
/>
<Button
android:id="#+id/btn_add_course"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/tv_not_now"
android:layout_centerHorizontal="true"
android:layout_marginBottom="15dp"
android:background="#drawable/btn_primary_with_white"
android:paddingBottom="10dp"
android:paddingLeft="40dp"
android:paddingRight="40dp"
android:paddingTop="10dp"
android:text="Add My First Course"
android:textColor="#color/white"
android:textSize="20sp" />
<TextView
android:id="#+id/tv_not_now"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp"
android:maxWidth="280sp"
android:layout_gravity="center_horizontal"
android:gravity="left"
android:textStyle="italic"
android:textSize="16sp"
android:textColor="#color/white"
android:text="#string/intro_not_now"
/>
</RelativeLayout>
Activity XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:adjustViewBounds="true"
android:src="#drawable/nav_header1" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:elevation="3dp"
android:layout_marginTop="-25dp"
>
</android.support.v4.view.ViewPager>
</LinearLayout>
Activity:
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intro);
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new Adapter_Intro(getSupportFragmentManager()));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
}
}
Fragment:
public class IntroFragment extends Fragment {
private static final String BACKGROUND_COLOR = "backgroundColor";
private static final String PAGE = "page";
private int mBackgroundColor, mPage;
public static IntroFragment newInstance(int backgroundColor, int page) {
IntroFragment frag = new IntroFragment();
Bundle b = new Bundle();
b.putInt(BACKGROUND_COLOR, backgroundColor);
b.putInt(PAGE, page);
frag.setArguments(b);
return frag;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!getArguments().containsKey(BACKGROUND_COLOR))
throw new RuntimeException("Fragment must contain a \"" + BACKGROUND_COLOR + "\" argument!");
mBackgroundColor = getArguments().getInt(BACKGROUND_COLOR);
if (!getArguments().containsKey(PAGE))
throw new RuntimeException("Fragment must contain a \"" + PAGE + "\" argument!");
mPage = getArguments().getInt(PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Select a layout based on the current page
int layoutResId;
switch (mPage) {
case 0:
layoutResId = R.layout.fragment_intro_welcome;
break;
default:
layoutResId = R.layout.fragment_intro_start;
}
// Inflate the layout resource file
View view = getActivity().getLayoutInflater().inflate(layoutResId, container, false);
// Set the current page index as the View's tag (useful in the PageTransformer)
view.setTag(mPage);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Set the background color of the root view to the color specified in newInstance()
View background = view.findViewById(R.id.intro_background);
background.setBackgroundColor(mBackgroundColor);
}
}

It seems that Android Studio is not accurate while rendering your layout.
I "measured" your screenshot using Gimp - as you can see, TextView is positioned exactly to the center of it parent, between top picture and bottom:

Your TextView is well centered inside the fragment, but not inside the activity.
Because in your activity, there is the ImageView that takes some height in the top.

Related

How to use CircleImageView library ( this : 'de.hdodenhof:circleimageview:3.1.0' ) inside fragment?

This is the error I'm gettingI'm trying to use this library in fragment inside onViewCreated() method, but i'm getting this casting error: - java.lang.ClassCastException:androidx.appcompat.widget.AppCompatTextView cannot be cast to de.hdodenhof.circleimageview.CircleImageView. I don't know how to solve this error. can anybody please help me?
FragmentProfile.java :
public class FragmentProfile extends Fragment implements View.OnClickListener {
Button sign_out;
TextView user_number;
private CircleImageView userImage;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_profile, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
sign_out = getActivity().findViewById(R.id.user_logout);
userImage = getActivity().findViewById(R.id.user_display_name);
user_number = getActivity().findViewById(R.id.phone_number);
sign_out.setOnClickListener(this);
}
#Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getActivity(), Login.class));
getActivity().finish();
}
}
fragment_profile.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">
<ImageView
android:layout_width="match_parent"
android:layout_height="#dimen/dp_180"
android:scaleType="fitXY"
android:src="#drawable/money" />
<de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/profile_image"
android:layout_width="#dimen/dp_95"
android:layout_height="#dimen/dp_95"
android:layout_centerHorizontal="true"
android:layout_marginTop="#dimen/dp_140"
android:scaleType="centerCrop"
android:src="#mipmap/ic_launcher"
app:civ_border_color="#color/textColor"
app:civ_border_width="#dimen/dp_2" />
<TextView
android:id="#+id/user_display_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/profile_image"
android:layout_centerHorizontal="true"
android:layout_marginTop="#dimen/dp_4"
android:fontFamily="#font/balsamiq_sans_bold"
android:text="#string/username"
android:textColor="#color/border"
android:textSize="#dimen/sp_22" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/user_logout"
android:layout_below="#id/user_display_name"
android:layout_margin="#dimen/dp_12"
android:orientation="vertical">
<TextView
android:id="#+id/phone_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/dp_12"
android:layout_marginTop="#dimen/dp_30"
android:fontFamily="#font/balsamiq_sans_bold"
android:text="+91-987654321"
android:textColor="#android:color/black"
android:textSize="#dimen/dp_18" />
</LinearLayout>
<Button
android:id="#+id/user_logout"
android:layout_width="#dimen/dp_200"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="#dimen/dp_30"
android:background="#drawable/button_shape"
android:text="#string/sign_out"
android:textAllCaps="false"
android:textColor="#android:color/white"
android:textStyle="bold" />
</RelativeLayout>
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// ... rest of the codes.
// Comment out code below.
// userImage = getActivity().findViewById(R.id.user_display_name);
// Replace it with code below.
userImage = getActivity().findViewById(R.id.profile_image);
// ... rest of the codes.
}
Here you are parsing a textview id to the CircleImageView. You should change your userImage = getActivity().findViewById(R.id.user_display_name); to userImage = getActivity().findViewById(R.id.profile_image);. That's why you are getting java.lang.ClassCastException:androidx.appcompat.widget.AppCompatTextView exception.
You issue is here:
private CircleImageView userImage;
userImage = getActivity().findViewById(R.id.user_display_name);
and in your layout:
<TextView
android:id="#+id/user_display_name"
You can not cast a TextView into a CircleImageView.

setOnClickListener in RelativeLayout not working

I have a structure in my android application
LinearLayout > FrameLayout >ImageView(used as a FrameLayout
Background) & RelativeLayout > TextView & ImageView.
I need that when I click in the FrameLayout or RelativeLayout or FirstImageView ( because it is the Bigger Zone , the textView or 2nd Image view are small ) do an action.
I tried to add setOnClickListener to this item but didn't work.
This is my Code:
public class HomeFragment extends Fragment {
View rootView;
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.home_fragment, container, false);
RelativeLayout paleoFoodBackGround = (RelativeLayout) rootView.findViewById(R.id.relativeLytPaleoFoodHome);
paleoFoodBackGround.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("1FOOD_LIST", "onClick: ");
}
});
return rootView;
}
public void clickFood(){
Log.d("2FOOD_LIST", "onClick: ");
}
}
This is my Layout structure:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="50"
android:orientation="vertical"
android:paddingLeft="2.5dp"
android:paddingRight="5dp"
android:weightSum="100">
<FrameLayout
android:id="#+id/framePaleoFoodHome"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="50"
android:paddingBottom="2.5dp">
<ImageView
android:id="#+id/imgViewPaleoFoodBackGround"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:scaleType="center"
app:srcCompat="#drawable/recipes" />
<RelativeLayout
android:id="#+id/relativeLytPaleoFoodHome"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
>
<ImageView
android:id="#+id/imgViewRecipesIconHome"
style="#style/iconHome"
app:srcCompat="#drawable/cooking"
/>
<TextView
android:id="#+id/txtViewRecipesTxtHome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/textViewHomeSquare"
android:text="#string/RecipesHome"
android:layout_below="#id/imgViewRecipesIconHome"/>
</RelativeLayout>
</FrameLayout>
<Framelayout> .... </Framelayout>
</LinearLayout>
I recommend using ImageButton instead of image. Also set your RelativeLayout to have android:clickable="true". Also set all children views that are not clickable with android:clickable="false"

Android ViewPager with FragmentPageAdapter - only last fragment page is visible

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

Android - Call Method With A Button From XML

I've got an app based on Sliding Tabs layout. I want to call the addMedicine method in the PageFragment class from an XML layout with a Button. The issue is that i cannot assign the method to the Button onClick event.
Here's the PageFragment class:
public class PageFragment extends Fragment {
public static final String ARG_PAGE = "ARG_PAGE";
private int mPage;
// TEMP VARIABLES //
ListView ItemsLst;
String[] Items = {"Medicine 1", "Medicine 2", "Medicine 3"};
TextView output;
EditText nameFld;
EditText formatFld;
EditText amountFld;
EditText exp_dateFld;
EditText timeFld;
DBManager dbAdapt = new DBManager(getActivity());
public static PageFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = null;
switch(mPage)
{
case 1:
view = inflater.inflate(R.layout.layout_sqltest, container, false);
nameFld = (EditText) view.findViewById(R.id.nameFld);
formatFld = (EditText) view.findViewById(R.id.formatFld);
amountFld = (EditText) view.findViewById(R.id.amountFld);
exp_dateFld = (EditText) view.findViewById(R.id.exp_dateFld);
timeFld = (EditText) view.findViewById(R.id.timeFld);
return view;
case 2:
view = inflater.inflate(R.layout.layout_settings, container, false);
return view;
case 3:
view = inflater.inflate(R.layout.layout_info, container, false);
return view;
}
return view;
}
public void addMedicine() // The method i want to call
{
String name = nameFld.getText().toString();
String format = formatFld.getText().toString();
int amount = Integer.parseInt(amountFld.getText().toString());
String exp_date = exp_dateFld.getText().toString();
String time = timeFld.getText().toString();
long id = dbAdapt.addMedicine(name, format, amount, exp_date, time);
}
}
And here is the layout_sqltest XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Name"
android:id="#+id/nameLbl"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/nameFld"
android:layout_gravity="center_horizontal"
android:inputType="text" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Format"
android:id="#+id/formatLbl"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/formatFld"
android:layout_gravity="center_horizontal"
android:inputType="text" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Amount"
android:id="#+id/amountLbl"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/amountFld"
android:layout_gravity="center_horizontal"
android:inputType="text" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Expiration Date"
android:id="#+id/exp_dateLbl"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/exp_dateFld"
android:layout_gravity="center_horizontal"
android:inputType="text" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Time"
android:id="#+id/timeLbl"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/timeFld"
android:layout_gravity="center_horizontal"
android:inputType="text" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Medicine"
android:id="#+id/addMedicineBtn"
android:layout_gravity="center_horizontal" />
</LinearLayout>
The addMedicineBtn is the button i want to call the method with.
Someone can help me? I really need that!
Thank you in advance!
EDIT: I tried giving to addMedicine method the View param, but it still doesn't appear in the available methods for the addMedicineBtn in the onClick properties (I'm using Android Studio).
Try to use onClickListener
view.findViewById(R.id.addMedicineBtn).setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
addMedicine();
}
});
You must add tools:context="PageFragment" line to the container (LinearLayout) of PagerFragment's layout file (layout_sqltest). Then onClick() method will find methods in PagerFragment class.

Access fragment controls from FragmentActivity

I have a FragmentActivity that should hold 2 Fragments. Each fragment has it's own layout with a table in it. I need to access the tables from the fragments' layouts from within the FragmentActivity to put some data that I read from an XML file. My problem is that when I use
tableOrders = (TableLayout)findViewById(R.id.tabel1);
it returns null. Now, I know that items from layouts can only be accessed before they have been inflated, and I've done that in the FragmentActivity before trying to call findViewById(). Here is the code for what I've tried:
The onCreate of the FragmentHolder.java that is derived from FragmentActivity:
private TableLayout tableOrders = null;
private TableLayout tableExecutions = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_holder);
initialisePaging();
//View orderFragment = (View)findViewById(R.layout.fragment_orders);
tableOrders = (TableLayout)/*orderFragment.*/findViewById(R.id.tabel1);
//View execFragment = (View)findViewById(R.layout.executions_fragment);
tableExecutions = (TableLayout)/*execFragment.*/findViewById(R.id.tabel2);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if(bundle != null)
logedUser = (User) bundle.getSerializable("user");
AssetManager am = getApplicationContext().getAssets();
String xmlContentOrders = XMLfunctions.getXml(am, "ordersData.xml");
populateOrdersTable(xmlContentOrders);
String xmlContentExecutions = XMLfunctions.getXml(am, "executionsData.xml");
populateExecutionsTable(xmlContentExecutions);
}
The fragment class (don't know if it helps):
public class OrdersFragment extends Fragment {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_orders, container, false);
return view;
}
}
The fragment class (don't know if it helps):
public class OrdersFragment extends Fragment {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_orders, container, false);
return view;
}
}
And the .xml file for the fragment:
<?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" >
<TableLayout
android:id="#+id/tabel1header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/tablebgcolor" >
<TableRow >
<TextView
android:id="#+id/ordersHeader"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_weight="1"
android:text="#string/orders"
android:textStyle="bold" />
</TableRow>
<TableRow
android:id="#+id/ordersTable"
style="#style/HeaderRow" >
<TextView
android:id="#+id/textSymbol"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/symbol"
style="#style/HeaderText" />
<TextView
android:id="#+id/textSide"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/side"
style="#style/HeaderText" />
<TextView
android:id="#+id/textPrice"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/price"
style="#style/HeaderText" />
<TextView
android:id="#+id/textQuantity"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/quantity"
style="#style/HeaderText"/>
<TextView
android:id="#+id/textRemaining"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/remanent"
style="#style/HeaderText" />
</TableRow>
</TableLayout>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" >
<TableLayout
android:id="#+id/tabel1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/tablebgcolor">
</TableLayout>
</ScrollView>
</LinearLayout>
With that said hope someone has a solution for this (probably it's something easy that I missed).
Edit: The code I use to put the Fragments on the FragmentActivity:
private void initialisePaging() {
OrdersFragment fragmentOne = new OrdersFragment();
ExecutionsFragment fragmentTwo= new ExecutionsFragment();
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragment(fragmentOne);
pagerAdapter.addFragment(fragmentTwo);
ViewPager viewPager = (ViewPager) super.findViewById(R.id.viewPager);
viewPager.setAdapter(pagerAdapter);
viewPager.setOffscreenPageLimit(2);
viewPager.setCurrentItem(0);
}

Categories

Resources