Android - TabLayout unclear behavior - android

I've created two tab layout via TabLayout & ViewPager, but when I transition between the tabs, it seems that I'm always viewing the layout of TAB1 instead of transitioning to TAB2. I can see this as TAB1 has a Spinner in it's layout, while TAB2 does not.
AS you can see I've added Log.w entry in onTabSelected but I never see the output, which strengths the assumption that I'm not really transitioning between tabs, the layout never changes.
What is incorrect in my configuration?
Here is the code:
Main activity onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
dbM = DBManager.getInstance(context);
TaskHashList.Initialize();
itemListAllTasks = dbM.getAllTasks();
TaskHashList.addTaskList(itemListAllTasks);
itemListWaitingTasks = dbM.getSortedTasks(Sorting.fromInteger(Sorting.WAITING.ordinal()));
TaskHashList.addTaskList(itemListWaitingTasks);
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("All Tasks"));
tabLayout.addTab(tabLayout.newTab().setText("Waiting"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PageAdapter adapter = new PageAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Log.w("changed tab", "");
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
adapter.notifyDataSetChanged();
}
My PageAdapter
public class PageAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PageAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
Fragment fragment;
switch (position) {
case 0:
fragment = new AllTasksTabFragment();
case 1:
fragment = new WaitingTasksTabFragment();
default:
fragment = new AllTasksTabFragment();
}
Bundle bundle = new Bundle();
bundle.putInt("position",position);
fragment.setArguments(bundle);
return fragment;
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
TAB1 layout - All Tasks
<?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:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:id="#+id/Main2ActivitylinearLayout3">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="right"
android:paddingRight="10dp"
android:text=""
android:id="#+id/allt_tab_totalTask"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:id="#+id/Main2ActivitylinearLayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:paddingLeft="5dp"
android:paddingRight="8dp"
android:text="Sort:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Spinner android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:entries="#array/sort_array"
android:id="#+id/all_tasks_sortSpinner"
android:gravity="center"
android:textAlignment="center"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:id="#+id/Main2ActivitylinearLayout2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="No Tasks to Display"
android:layout_marginTop="60dp"
android:layout_marginLeft="60dp"
android:id="#+id/alltab_emptylist"
android:gravity="center"
android:layout_centerHorizontal="true"
android:textStyle="bold" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/alltasks_listView"
android:layout_centerHorizontal="true" />
</LinearLayout>
TAB2 layout - Waiting Tasks
<?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:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:id="#+id/Main2ActivitylinearLayout1">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="right"
android:paddingRight="10dp"
android:text=""
android:id="#+id/waitt_tab_totalTask"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:id="#+id/Main2ActivitylinearLayout2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="No Tasks to Display"
android:gravity="center"
android:layout_marginTop="60dp"
android:layout_marginLeft="60dp"
android:id="#+id/wait_tabemptylist"
android:layout_centerHorizontal="true"
android:textStyle="bold" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/waitingtasks_listView"
android:layout_centerHorizontal="true" />
</LinearLayout>

Your switch case doesn't have breaks.
#Override
public Fragment getItem(int position) {
Fragment fragment;
switch (position) {
case 0:
fragment = new AllTasksTabFragment();
break; // Add this
case 1:
fragment = new WaitingTasksTabFragment();
break; // Add this
default:
fragment = new AllTasksTabFragment();
}
Bundle bundle = new Bundle();
bundle.putInt("position",position);
fragment.setArguments(bundle);
return fragment;
}
But i cannot assume why your Log.w doesn't work.
Maybe you're setting Log Filter to show errors only...

Related

Fragment does not create its corresponding view

I have a TabLayout with 2 tabs. For each tab, I created the corresponding fragments.
The activity class (extending AppCompatActivity) is this (ToolsActivity.java):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tools);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
mViewPager = findViewById(R.id.view_pager);
mViewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(mViewPager);
tabs.getTabAt(0).setIcon(R.drawable.ic_tab_reading);
tabs.getTabAt(1).setIcon(R.drawable.ic_tab_writing);
tabs.setTabMode(TabLayout.MODE_SCROLLABLE);
mCurrentSelectedListener = new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
// ...
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
// ...
}
};
tabs.addOnTabSelectedListener(mCurrentSelectedListener);
}
The corresponding layout is this (activity_tools.xml):
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ToolsActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:minHeight="?actionBarSize"
android:padding="#dimen/appbar_padding"
android:text="#string/title_activity_tools"
android:textAppearance="#style/TextAppearance.Widget.AppCompat.Toolbar.Title" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:tabInlineLabel="true" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
The pager adapter contains an array of Fragment object.
mLstFragments.add(new UHFReadFragment());
mLstFragments.add(new UHFWriteFragment());
that adapter also contains this piece of code:
#Override
public Fragment getItem(int position) {
if (mLstFragments.size() > 0) {
return mLstFragments.get(position);
}
throw new IllegalStateException("No fragment at position " + position);
}
First tab is UHFReadFragment. This is part of the code of it:
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mContext = (ToolsActivity) getActivity();
mSound = new Sound(mContext);
mTagList = new ArrayList<HashMap<String, String>>();
mAdapter = new SimpleAdapter(mContext, mTagList, R.layout.listtag_items,
new String[]{"tagUii", "tagLen", "tagCount", "tagRssi"},
new int[]{R.id.TvTagUii, R.id.TvTagLen, R.id.TvTagCount,
R.id.TvTagRssi});
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
String result = msg.obj + "";
String[] strs = result.split("#");
addEPCToList(strs[0], strs[1]);
mSound.playSound(1);
}
};
mUHF = new UHF(mContext, mHandler);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mTvCount = (TextView) getView().findViewById(R.id.tv_count);
mLvTags = (ListView) getView().findViewById(R.id.LvTags);
mLvTags.setAdapter(mAdapter);
}
And finally, this is the layout for the first fragment (uhf_read_fragment.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"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
tools:context=".ui.main.UHFReadFragment">
<LinearLayout
android:id="#+id/layout4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:background="#color/white"
android:paddingBottom="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp" >
<TextView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/tvTagUii"
android:textSize="15sp" />
<TextView
android:id="#+id/tv_count"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:text="0"
android:textColor="#color/red"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/tvTagLen"
android:visibility="gone" />
<TextView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="#string/tvTagCount"
android:textSize="15sp" />
<TextView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="RSSI"
android:textSize="15sp"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#color/gray" />
<ListView
android:id="#+id/LvTags"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
The problem is that the layout of the fragments does not appear, and in fact, onViewCreated is never called.
What else is missing? I thought that by using "tools:context=".ui.main.UHFReadFragment"" the layout will be associated to the class that controls the Fragment.
Only the layout of the activity is shown (when running the app, it shows only the title and the tabs header).
Regards
Jaime
You need to have the onCreateView method in the Fragment class(UHFReadFragment) to inflate the layout
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.uhf_read_fragment, container, false);
}
Hope this will solve your issue

How to program FragmentB inside FragmentA?

I'm making an application as a school project and I'm having trouble in programming a certain FragmentB inside FragmentA. Trouble, more so, I don't know how to even if I had an extensive search done.
FragmentA to MainActivity works properly (or so, because doesn't give out any errors). I used SwitchCase in the MainActivity.java and it works.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNavigationView = findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener
(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
selectedFragment = HomeScreenFragment.newInstance();
break;
case R.id.navigation_profile:
selectedFragment = ProfileScreenFragment.newInstance();
break;
case R.id.navigation_notifications:
selectedFragment = NotifScreenFragment.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, selectedFragment);
transaction.commit();
return true;
}
});
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, HomeScreenFragment.newInstance());
transaction.commit();
}
}
ProfileScreenFragment.java (this is what I want to have a FragmentB)
public class ProfileScreenFragment extends Fragment {
public static ProfileScreenFragment newInstance() {
ProfileScreenFragment fragment = new ProfileScreenFragment ();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_profile_screen2, container, false);
}
}
fragment_profile_screen2.xml (the frame_layout is where I want to put the FragmentB)
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.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_marginRight="15dp"
android:background="#color/colorPrimary"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView"
android:layout_width="50dp"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:layout_weight="1"
android:padding="7dp"
app:srcCompat="#drawable/logo_mdpi" />
<TextView
android:id="#+id/textView"
android:layout_width="313dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:fontFamily="sans-serif-black"
android:gravity="center"
android:text="Profile"
android:textColor="#android:color/white"
android:textSize="25sp" />
<ImageView
android:layout_width="50dp"
android:layout_height="match_parent"
android:layout_weight="1"
app:srcCompat="#drawable/icon_more2" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
app:tabMode="fixed"
app:tabTextColor="#android:color/white">
<android.support.design.widget.TabItem
android:id="#+id/profile_profile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Profile" />
<android.support.design.widget.TabItem
android:id="#+id/profile_posts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Posts" />
<android.support.design.widget.TabItem
android:id="#+id/profile_uploads"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Uploads" />
<android.support.design.widget.TabItem
android:id="#+id/profile_likes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Likes" />
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/frame_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.FloatingActionButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="#android:drawable/ic_input_add"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:clickable="true" />
</android.support.design.widget.CoordinatorLayout>
How or what code should I be writing for FragmentB be put inside the ProfileScreenFragment.java?
Is it also possible to use SwitchCase in ProfileScreenFragment.java for the Tabs?
Thank you so much. If ever there are clarifications needed in the codes I used, please don't hesitate to ask. I'm still learning the basics of it all so I'm 50/50 on the codes.
Add this snippet in ProfileScreenFragment.
#Override
protected void onViewCreated(View view, Bundle savedInstanceState) {
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, FragmentB.newInstance());
transaction.commit();
}
For the tab layout, you can add a tab change listener
TabLayout tabLayout = view.findViewById(R.id.tabs);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0: // Handle 1st tab item
break;
case 1: // Handle 2nd tab item
break;
case 2: // Handle 3rd tab item
break;
case 3: // Handle 4th tab item
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});

How to place PagerTabStrip in single page

I am trying to design this page
but I have design like this ( both fragment are there but the pagertabstrip of unseen page only see when I moved to this page )
Issue Facing
How would I set the width of the PagerTabStrip so that both login and register( highlighted in the first image) is visible in the same page.
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:weightSum="2"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
android:layout_weight="1.6"
android:gravity="center"
android:id="#+id/logo"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:textSize="25dp"
android:gravity="center"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold"
android:text=""
android:visibility="visible"
android:src="#drawable/logo_new"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView8" />
</LinearLayout>
<LinearLayout
android:layout_weight="0.4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v4.view.ViewPager
app:tabMode="fixed"
android:id="#+id/vpPager"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.PagerTabStrip
app:tabMode="fixed"
android:id="#+id/pager_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingBottom="4dp"
android:paddingTop="4dp" />
</android.support.v4.view.ViewPager>
</LinearLayout>
</LinearLayout>
Java File
public class Authentication extends AppCompatActivity {
FragmentPagerAdapter adapterViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.authentication);
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Boolean login_already=app_preferences.getBoolean("login",false);
if (login_already)
{
startActivity(new Intent(Authentication.this,MainActivity.class));
finish();
}
ViewPager vpPager = (ViewPager) findViewById(R.id.vpPager);
adapterViewPager = new MyPagerAdapter(getSupportFragmentManager());
vpPager.setAdapter(adapterViewPager);
// Attach the page change listener inside the activity
vpPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
// This method will be invoked when a new page becomes selected.
#Override
public void onPageSelected(int position) {
Toast.makeText(Authentication.this,
"Selected page position: " + position, Toast.LENGTH_SHORT).show();
}
// This method will be invoked when the current page is scrolled
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// Code goes here
}
// Called when the scroll state changes:
// SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
#Override
public void onPageScrollStateChanged(int state) {
// Code goes here
}
});
}
public static class MyPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 2;
public MyPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show FirstFragment
return Login.newInstance(0, "Login");
case 1: // Fragment # 0 - This will show FirstFragment different title
return Registration.newInstance(1, "Register");
default:
return null;
}
}
// Returns the page title for the top indicator
#Override
public CharSequence getPageTitle(int position) {
if (position==0)
return "Login";
else
return "Register";
//return "Page " + position;
}
}
}
That layout xml worked for me...
EDIT: Oh sry i'm using another lib:
https://github.com/jpardogo/PagerSlidingTabStrip
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.astuetz.PagerSlidingTabStrip
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip"
android:textColor="#FFFFFFFF"
app:pstsDividerColor="#FFFFFFFF"
app:pstsDividerPadding="10dp"
app:pstsDividerWidth="1dp"
app:pstsIndicatorColor="#FF33B5E6"
app:pstsIndicatorHeight="5dp"
app:pstsTabPaddingLeftRight="20dip"
app:pstsUnderlineColor="#FF33B5E6">
</com.astuetz.PagerSlidingTabStrip>
<FrameLayout
android:id="#+id/movie_framelayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="#+id/movie_pager"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v4.view.ViewPager>
</FrameLayout>
</LinearLayout>
</FrameLayout>
When you want to display only selected tab and other will hide then set your PagerTabStrip as bellow.
<android.support.v4.view.PagerTabStrip
android:id="#+id/pager_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingBottom="4dp"
android:paddingTop="4dp"
app:tabMode="scrollable"
app:tabTextColor="#000000"
app:tabSelectedTextColor="#ff0000"
app:tabIndicatorColor="#ff0000"/>
app:tabTextColor="" is your normal tab text color.
app:tabSelectedTextColor="" is color of your selected tab.
app:tabIndicatorColor="" is your selected tab indicatore color.
So use as per your requirement. For detail that how to use tab layout then check this tutorial.

Displaying TabLayout and fragments with ViewPager inside card view

I want to display two fragments in a cardview, i was able to display tablayout but not the fragments, tried everything, help me as this might be simple I guess. I uploaded screenshot as well, as seen from the screenshot tablayout is displayed correctly but not the fragment below it
Code in the Activity.
....
//Creating our pager adapter
Pager adapter = new Pager(getSupportFragmentManager(), Titles, 2);
...
viewPager = (ViewPager) findViewById(R.id.srviewpager);
//Adding adapter to pager
viewPager.setAdapter(adapter);
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(viewPager);
..
public class Pager extends FragmentStatePagerAdapter {
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
private static final String TAG = "ViewPagerAdapter";
// Build a Constructor and assign the passed Values to appropriate values in the class
public Pager(FragmentManager fm, CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
//Overriding method getItem
#Override
public Fragment getItem(int position) {
//Returning the current tabs
switch (position) {
case 0:
return new ShippingFragment();
case 1:
return new ReturnsFragment();
}
return null;
}
// Overriden method getCount to get the number of tabs
#Override
public int getCount() {
return NumbOfTabs;
}
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
}
this is my layout file, contains 3 cardview, the last cardview has to display two fragments, shipping and returns. So far I am able to display only tablayout with two tabs but not the fragments.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cardview="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:id="#+id/description_cd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="8dp"
cardview:cardCornerRadius="8dp"
cardview:cardElevation="15dp"
cardview:cardBackgroundColor="#color/cardview_light_background"
cardview:contentPadding="2dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/features_cd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
cardview:cardCornerRadius="8dp"
cardview:cardElevation="15dp"
cardview:cardBackgroundColor="#color/cardview_light_background"
cardview:contentPadding="2dp"
android:layout_below="#+id/description_cd"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="false"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="false"
android:layout_margin="8dp">
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/sp_cd"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
cardview:cardCornerRadius="8dp"
cardview:cardElevation="15dp"
cardview:cardBackgroundColor="#color/cardview_light_background"
cardview:contentPadding="2dp"
android:layout_below="#+id/features_cd"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="false"
android:layout_margin="8dp">
<com.spoorthy.apsaratrendz.thirdpartyviews.RippleView
android:id="#+id/shipping_payment_rpv"
android:layout_width="match_parent"
android:layout_height="match_parent"
cardview:rv_color="#color/green"
cardview:rv_type="rectangle"
cardview:rv_rippleDuration="#integer/ripduration_rpv">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/shippingandreturns"
android:id="#+id/textViewsp"
android:layout_alignParentTop="true"
android:singleLine="true"
android:textSize="25sp"
android:textStyle="bold"
android:background="#FFFFFF"
android:textColor="#d52e9e"
android:inputType="text"
android:padding="1dp"
android:paddingEnd="1dp"
android:paddingStart="1dp" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
android:layout_below="#+id/textViewsp"/>
<android.support.v4.view.ViewPager
android:id="#+id/srviewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/tabs"/>
</com.spoorthy.apsaratrendz.thirdpartyviews.RippleView>
</android.support.v7.widget.CardView>
</RelativeLayout>
Here are my two fragment layouts
shippingfragment.xml
<?xml version="1.0" encoding="utf-8"?>
<com.spoorthy.apsaratrendz.thirdpartyviews.ReadMoreTextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragmentText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="25sp"
android:textStyle="bold"
android:text="#string/returns"
android:layout_margin="4dp"
android:padding="4dp" />
returnsfragment.xml
<?xml version="1.0" encoding="utf-8"?>
<com.spoorthy.apsaratrendz.thirdpartyviews.ReadMoreTextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragmentText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="25sp"
android:textStyle="bold"
android:text="#string/returns"
android:layout_margin="4dp"
android:padding="4dp" />
And my two fragment java files..
public class ReturnsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.returnsfragment, null);
return v;
}
}
public class ShippingFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.shippingfragment, null);
return v;
}
}
Solved the problem by changing the CardView layout height to 350dp, instead of match_parent.
<android.support.v7.widget.CardView
android:id="#+id/sp_cd"
android:layout_width="match_parent"
android:layout_height="350dp".../>

Get button from a fragment in Android

I was working with and slider tab, insaid the main view I have 2 tabs and insaid them, I have a XML to set the UI. Everything is perfect, I get my slide tabs and I can run the app. The problem is when I try to get a button from my fragments. I was reading about LayoutInflater, but I couldn´t solved.
Please, I think I don´t undestand very well how the fragment works and I would like a little of help about this.
This is my main activity (onCreate):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
facebookLogin = new FacebookLogin(getApplicationContext());
setContentView(R.layout.register_tabs);
toolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolBar);
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.colorPrimary);
}
});
tabs.setViewPager(pager);
}
I my main XML:
<LinearLayout
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:orientation="vertical"
tools:context=".MainActivity">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar"
/>
<com.cheescake.clasi.all.SlidingTabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="2dp"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1"
/>
</LinearLayout>
And the XML and class where I have my button:
<?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">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="6">
<Space
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="3" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<Space
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="3" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Inicia sesión para comprar y vender los mejores productos "
android:id="#+id/textView"
android:gravity="center" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="#string/user_name"
android:ems="10"
android:id="#+id/editText"
android:layout_weight="2"
android:gravity="bottom" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="#string/user_pass"
android:ems="10"
android:id="#+id/editText2"
android:layout_weight="2"
android:gravity="bottom" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textSize="10dp"
android:text="¿has olvidado tu contraseña?"
android:textColor="#color/colorPrimaryDark"
android:id="#+id/text_loggin"
android:layout_weight="1.3"
android:layout_marginLeft="5dp"
android:gravity="right" />
<Space
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
<com.google.android.gms.common.SignInButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_weight="1" />
<com.facebook.login.widget.LoginButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/login_button"
android:layout_weight="1" />
<Space
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="3" />
</LinearLayout>
<Space
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="3" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.8"
android:background="#color/bottomBackground">
<Space
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="5" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/finish"
android:id="#+id/txtNextButton"
android:layout_weight="1"
android:gravity="center" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
The class of the fragment:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.facebook.login.widget.LoginButton;
public class RegisterTabLogin extends Fragment {
private LoginButton loginButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.register_tab_login,container,false);
return v;
}
}
As I say, I just want to get a View from the fragment and work with it in the Main Activity, I was reading about LayoutInflater but I could´t solved, Also I read some questions here, (Using button from a fragment in main activity) but I couldn´t solved.
Any help will be gratefull, a link o something.
have you tried this?
public class RegisterTabLogin extends Fragment {
private LoginButton loginButton;
private LoginCallback mCallback;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.register_tab_login,container,false);
loginButton = (LoginButton) v.findViewById(R.id.login_button);
showData.setOnClickListener(onClickListener);
return v;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (LoginCallback) activity;
} catch (ClassCastException e) {
throw new ClassCastException(
"Activity must implement LoginCallback.");
}
}
private final OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (mCallback != null) {
mCallback.onLogin();
}
}
};
public static interface LoginCallback{
void onLogin();
}
}
then on MainActivity
public class MainActivity extends Activity implements
RegisterTabLogin.LoginCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
facebookLogin = new FacebookLogin(getApplicationContext());
setContentView(R.layout.register_tabs);
toolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolBar);
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.colorPrimary);
}
});
tabs.setViewPager(pager);
}
#Override
public void onLogin() {
//DO SOMETHING
}
}
In your Main Activity, access this view in the OnStart() method like this:
#Override
protected void onStart() {
Button yourButton = (Button)findViewById(R.id.yourButton);
super.onStart();
}
EDIT:
Your fragment should be present in your Main Activity.
You can add RegisterTabLogin in a certain containerView present in your Main Activity layout in the OnCreate() method like this:
RegisterTabLogin registerTabLogin= new RegisterTabLogin();
getFragmentManager().beginTransaction().add(R.id.a_certain_layout, registerTabLogin).commit();

Categories

Resources