I'm trying to fill a tab with a view. For more information about the exact thing I try to achieve with the view please read my previous question : How to customize individual tabs? (changing background color, indicator color and text color)
The result I got now is this :
As you can see the tab is not completely filled with the view in its width.
my layout 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:orientation="vertical"
android:background ="#color/black"
>
<TextView
android:id="#+id/nieuws_tab_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="#string/nieuws"
android:textColor="#android:color/white"
android:textStyle="bold"/>
</RelativeLayout>
My MainActivity :
package com.example.android.effectivenavigation;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener
{
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
//The viewpager displays on of the section at a time
ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three primary sections
// of the app.
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
// Set up the action bar.
final ActionBar actionBar = getActionBar();
//set custom actionbar
actionBar.setCustomView(R.layout.titlebar);
//Displays the custom design in the actionbar
actionBar.setDisplayShowCustomEnabled(true);
//Turns the homeIcon a View
View homeIcon = findViewById(android.R.id.home);
//Hides the View (and so the icon)
((View)homeIcon.getParent()).setVisibility(View.GONE);
// Specify that we will be displaying tabs in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener()
{
#Override
public void onPageSelected(int position)
{
// When swiping between different app sections, select the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if we have a reference to the Tab.
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++)
{
if(i == 0)
{
//final View firstCustomView = new CustomView(this);
//firstCustomView.setBackgroundColor(Color.BLUE);
Tab tab = actionBar.newTab().setTabListener(this).setCustomView(R.layout.nieuws_tab_layout);
actionBar.addTab(tab);
}
else
{
// Create a tab with text corresponding to the page title defined by the adapter.
// Also specify this Activity object, which implements the TabListener interface, as the
// listener for when this tab is selected.
Tab tab = actionBar.newTab().setText(mAppSectionsPagerAdapter.getPageTitle(i)).setTabListener(this);
actionBar.addTab(tab);
}
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
{
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
{
//CustomView ctv;
//ctv = new CustomView(context, R.attr.tabStyleAttr);
// When the given tab is selected, switch to the corresponding page in the ViewPager.
//LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
//View tabView = inflater.inflate(R.layout.nieuws_tab_layout, null);
//tabView.setBackgroundColor(0xFF00FF00);
//tab.setCustomView(tabView);
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
{
}
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter
{
public AppSectionsPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int i)
{
switch (i)
{
case 0:
// The first section of the app is the most interesting -- it offers
// a launchpad into the other demonstrations in this example application.
return new LaunchpadSectionFragment();
default:
// The other sections of the app are dummy placeholders.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
fragment.setArguments(args);
return fragment;
}
}
#Override
public int getCount()
{
return 3;
}
#Override
public CharSequence getPageTitle(int position)
{
switch(position)
{
case 0:
{
return "Tab1";
}
case 1:
{
return "Tab2";
}
case 2:
{
return "Tab3";
}
default:
{
return "Section " + (position + 1);
}
}
}
}
public static class LaunchpadSectionFragment extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_section_launchpad, container, false);
// Demonstration of a collection-browsing activity.
rootView.findViewById(R.id.demo_collection_button).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent intent = new Intent(getActivity(), CollectionDemoActivity.class);
startActivity(intent);
}
});
// Demonstration of navigating to external activities.
rootView.findViewById(R.id.demo_external_activity).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
// Create an intent that asks the user to pick a photo, but using
// FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET, ensures that relaunching
// the application from the device home screen does not return
// to the external activity.
Intent externalActivityIntent = new Intent(Intent.ACTION_PICK);
externalActivityIntent.setType("image/*");
externalActivityIntent.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(externalActivityIntent);
}
});
return rootView;
}
}
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class DummySectionFragment extends Fragment
{
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_section_dummy, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(getString(R.string.dummy_section_text, args.getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
public class CustomView extends View
{
public CustomView(Context context)
{
super(context, null);
}
}
}
Those are paddings. Use the style below with your TabHost to get rid of them, or set android:paddingStart and android:paddingEnd to 0dp in your layout directly.
Android 4.0 and higher
<style name="TabStyle" parent="#android:style/Widget.Holo.Light.ActionBar.TabView">
<item name="android:paddingStart">0dip</item>
<item name="android:paddingEnd">0dip</item>
</style>
Older Android
<style name="TabStyle" parent="#android:style/Widget.ActionBar.TabView">
<item name="android:paddingStart">0dip</item>
<item name="android:paddingEnd">0dip</item>
</style>
Make sure you are using the proper dpi (hdpi, mdpi, et.) folder for your background resources to match the device/emulator you are working on.
I was having the same problem as you, even if I was using a custom tab through setCustomView() method, overriding styles (w/support library as well) and even removing paddings from parent layouts.
Now works as I expected, hope it helps!
Related
Hi guys, I have a very big problem and I really don't know where I were wrong.
my app contains Navigation Drawer menu and i need to create swipe tabs in fragments_accounts.xml
Navigation Drawer Menu contains "Accounts" when it's clicked fragments_accounts.xml will show and i wanna create 2 swipe tabs in it.
I changed import android.support.v4.app.Fragment; to import android.app.Fragment; in both of the AccountsFtagmets.java and MainActivity.java
This error will show:
Error:(88, 28) error: incompatible types: AccountsFragment cannot be
converted to Fragment
How can i rescue from this error??
it's killing me!!!
activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
</LinearLayout>
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="com.rastari.salar.mymetarialbank.adapter.FragmentDrawer"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
fragments_accounts.xml
<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="match_parent">
</android.support.v4.view.ViewPager>
there is AccountsFtagmets.java:
import com.rastari.salar.mymetarialbank.R;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Salar on 24/4/2015.
*/
public class AccountsFragment extends FragmentActivity implements ActionBar.TabListener {
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
public static AccountsFragment newInstance() {
return new AccountsFragment();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_accounts, container, false);
// Create the adapter that will return a fragment for each of the three primary sections
// of the app.
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
// Set up the action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home/Up button should not be enabled, since there is no hierarchical
// parent.
actionBar.setHomeButtonEnabled(false);
// Specify that we will be displaying tabs in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between different app sections, select the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if we have a reference to the
// Tab.
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by the adapter.
// Also specify this Activity object, which implements the TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
// Inflate the layout for this fragment
return rootView;
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link android.support.v4.app.FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
* sections of the app.
*/
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
// The first section of the app is the most interesting -- it offers
// a launchpad into the other demonstrations in this example application.
return new LaunchpadSectionFragment();
default:
// The other sections of the app are dummy placeholders.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
fragment.setArguments(args);
return fragment;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return "Section " + (position + 1);
}
}
/**
* A fragment that launches other parts of the demo application.
*/
public static class LaunchpadSectionFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_accounts_activity, container, false);
return rootView;
}
}
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_chart_activity, container, false);
Bundle args = getArguments();
return rootView;
}
}
public AccountsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
MainActivity.java:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DateFormat;
import java.util.Date;
public class MainActivity extends ActionBarActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
TextView date= (TextView) findViewById(R.id.dateAndTime);
date.setText(currentDateTimeString);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if(id == R.id.action_search){
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new AccountsFragment();
title = getString(R.string.title_accounts);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
}
Thank You.
Your AccountsFragment needs to extend Fragment not FragmentActivity.
am following the Android Developers website to add sliding tabs to my Android app for my project, I am stuck with this one error and do not understand the problem, I know it has something to do with calling the correct Fragment layout, I am doing exactly what the tutorial tells me too, have any of you guys got any information to solve this, thank you.
package com.test.finalproject;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends FragmentActivity implements View.OnClickListener {
DemoCollectionPagerAdapter mCollectionPagerAdapter;
ViewPager mViewPager;
Button buttonLogin;
Button buttonRegister;
Button buttonTheme;
Button buttonMaps;
#Override
protected void onCreate(Bundle savedInstanceState) {
Utils.setThemeToActivity(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final android.app.ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create a tab listener that is called when the user changes tabs.
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
// show the given tab
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
// hide the given tab
}
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
// probably ignore this event
}
};
// Add 3 tabs, specifying the tab's text and TabListener
for (int i = 0; i < 3; i++) {
actionBar.addTab(
actionBar.newTab()
.setText("Tab " + (i + 1))
.setTabListener(tabListener));
}
buttonLogin = (Button)findViewById(R.id.buttonLogin);
buttonLogin.setOnClickListener(this);
buttonRegister = (Button)findViewById(R.id.buttonRegister);
buttonRegister.setOnClickListener(this);
buttonTheme = (Button)findViewById(R.id.buttonTheme);
buttonTheme.setOnClickListener(this);
buttonMaps = (Button)findViewById(R.id.buttonMaps);
buttonMaps.setOnClickListener(this);
mCollectionPagerAdapter =
new DemoCollectionPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCollectionPagerAdapter);
}
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
// Our object is just an integer :-P
args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 100;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
Integer.toString(args.getInt(ARG_OBJECT)));
return rootView;
}
}
public void onCreate1(Bundle savedInstanceState) {
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between pages, select the
// corresponding tab.
getActionBar().setSelectedNavigationItem(position);
}
});
}
private void buttonLoginClick()
{
startActivity (new Intent("MainApp"));
}
private void buttonRegisterClick()
{
startActivity (new Intent("TextToo"));
}
private void buttonThemeClick()
{
startActivity (new Intent("SettingsTheme"));
}
private void buttonMapsClick()
{
startActivity (new Intent("GoogleMaps"));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.buttonLogin:
buttonLoginClick();
break;
}
switch (v.getId())
{
case R.id.buttonRegister:
buttonRegisterClick();
break;
}
switch (v.getId())
{
case R.id.buttonTheme:
buttonThemeClick();
break;
}
switch (v.getId())
{
case R.id.buttonMaps:
buttonMapsClick();
break;
}
}
}
The Error is on line 126.
The Error is: Description Resource Path Location Type
fragment_collection_object cannot be resolved or is not a field MainActivity.java /Login/src/com/test/finalproject line 126 Java Problem
The problem you are facing is because of the missing xml file in the layout folder of project/res
Go to http://developer.android.com/training/implementing-navigation/lateral.html
Click on "download the sample app" and unzip it. Add the EffectiveNavigation\res\layout\fragment_collection_object.xml to you project\res\layout. This,I guess will solve the problem.
I need to use tabs on my app ,
I may need 4 to 7 tabs on my fragmentActivity .
I heard swipe tabs are best suited for displaying 3 or fewer tabs . I've already use them in another app but the number of tabs was 3 . I don't know if it's true or not but they worked perfect on that app .
I need to make something like Google Play Store app , as you can see there are lots of tabs , what are those tabs ?
I don't need to have any communication between these tabs .
What is the best tab to use when I have 4 to 7 tabs ?
I need to run the app on older devices like 2.3+
thanks you
Google Play store app uses Scrolling Tabs. Here's an example:
MainActivity.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends ActionBarActivity {
// used ActionBarActivity from v7 support library,
// for backward compatibility
private ViewPager viewPager;
private MyPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.viewPager);
adapter = new MyPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
}
private static class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
// each page corresponds to a new fragment
// I'll return the same fragment for now
return new MyFragment();
}
#Override
public int getCount() {
// return no of pages
return 5;
}
#Override
public CharSequence getPageTitle(int position) {
// return the page title
return "Tab " + position;
}
}
public static class MyFragment extends Fragment {
public MyFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="MergeRootFrame" >
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.PagerTitleStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33b5e5"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#fff" />
</android.support.v4.view.ViewPager>
</FrameLayout>
fragment_main.xml is just the hello world fragment. You will need to customize the PagerTitleStrip to make it look like a tab. For that I really love this library.
Hope this helps :)
It is better to use scroll tabs in your case.
Use fragment class from support.v4.app lib,this will enable you to use scroll tabs with devices older than API level 11.
For using support lib,include it in dependencies in builf.gradle file.
Also extend adapter with FragmentStatePagerAdapter instead of FragmentPagerAdapter to store the instance before it getting destroyed.
Here is an example code snippet
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends FragmentActivity {
ViewPager pager = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pager = (ViewPager) findViewById(R.id.pager);
android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
pager.setAdapter(new MyAdapter(manager));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class MyAdapter extends FragmentStatePagerAdapter{
public MyAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment frag = null;
if(i==0){
frag = new FragmentA();
}
if(i==1){
frag = new FragmentB();
}
if(i==2){
frag = new FragmentC();
}
return frag;
}
#Override
public int getCount() {
return 3;
}
public CharSequence getPageTitle(int i){
String title = new String();
if(i==0){
title = "FRAG1";
}
if(i==1){
title = "FRAG2";
}
if(i==2){
title = "FRAG3";
}
return title;
}
}
}
I'm quite new to Android. I'm stuck with this issue for a few days now.
I'm using the new google's Template of Action bar Tab with swipe (ViewPager).
Inside each fragment, I want to display a dynamic list of cards (with cardslib : https://github.com/gabrielemariotti/cardslib). The data for the cards come from an asyncTask which is fetching data from an url.
This is my problem : When I launch the app, the first View is display, but the ViewPager prepare the view for the second page, so the async task for the second screen is launch too. And the cards of the second screen are added to the first one.
Then if i swipe to the second screen, nothing is displayed, and the async task for the third screen is launch. So if swipe to the thrid screen, nothing... And then if i switch again to the second screen, the cards with data of the first screen are displayed... A real mess !
I think I have a probleme with the onCreate, onCreateView, or something like that. Maybe the code is sometimes not at the right place.. I don't know. I tried a lot of small modofication, but nothing worked. (but it worked like this with just action bar tab and without the ViewPager).
Thanks
Here is my code :
import java.util.Locale;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a {#link FragmentPagerAdapter}
* derivative, which will keep every loaded fragment in memory. If this
* becomes too memory intensive, it may be best to switch to a
* {#link android.support.v13.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mSectionsPagerAdapter.notifyDataSetChanged();
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
//mSectionsPagerAdapter.notifyDataSetChanged();
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
mSectionsPagerAdapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
if(tab.getPosition() != mViewPager.getCurrentItem()) {
mViewPager.setCurrentItem(tab.getPosition());
}
// mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
mSectionsPagerAdapter.notifyDataSetChanged();
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
mSectionsPagerAdapter.notifyDataSetChanged();
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
}
And here is the Fragment
import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardArrayAdapter;
import it.gmariotti.cardslib.library.internal.CardHeader;
import it.gmariotti.cardslib.library.view.CardListView;
import java.util.ArrayList;
import java.util.List;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.example.webanajones.asyncTask.GetItemTask;
import com.example.webanajones.asyncTask.IResultsListener;
import com.example.webanajones.asyncTaskResponse.ItemJsonResponse;
import com.example.webanajones.asyncTaskResponse.ItemJsonResponse.Item;
/**
* A placeholder fragment containing a simple view.
*/
public class PlaceholderFragment extends Fragment implements
IResultsListener {
/**
* The fragment argument representing the section number for this
* fragment.
*/
static final String ARG_SECTION_NUMBER = "section_number";
public static int limit = 0;
IResultsListener listener = this;
ArrayList<Card> cards = new ArrayList<Card>();
CardArrayAdapter mCardArrayAdapter;
int flag = 0;
boolean loadMore = true;
CardListView listView;
private int idx;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Bundle data = getArguments();
// idx = data.getInt("idx") +1;
limit = 0;
flag = 0;
loadMore = true;
List<String> params = new ArrayList();
params.add(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
params.add(String.valueOf(limit));
GetItemTask getItemTask = new GetItemTask();
getItemTask.setOnResultsListener(listener);
getItemTask.execute(params);
}
/**
* Returns a new instance of this fragment for the given section number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#SuppressWarnings("unchecked")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
#Override
public void onGetItemTaskSucceeded(ItemJsonResponse itemJsonResponse) {
if (mCardArrayAdapter != null) {
mCardArrayAdapter.notifyDataSetChanged();
}
if (itemJsonResponse.getSuccess() != 0) {
loadMore = true;
final Item[] itemTable = itemJsonResponse.getItemArray();
for (int itemIndex = 0; itemIndex < itemTable.length; itemIndex++) {
if (itemTable[itemIndex].getTypeId() == 2) { // 2 = type GIF
final int index = itemIndex;
Card gifCard = new CardGif(getActivity()){
#Override
public void setupInnerViewElements(ViewGroup parent, View view) {
DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
int width = (int) (metrics.widthPixels * 0.97);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, LinearLayout.LayoutParams.WRAP_CONTENT);
params.bottomMargin = 30;
LinearLayout LinearLayout = (LinearLayout) parent.findViewById(R.id.inner_frame);
GIFWebView gifView = new GIFWebView (getActivity(), itemTable[index].getObjectUrl());
LinearLayout.addView(gifView);
}
};
CardHeader header = new CardHeader(getActivity());
header.setTitle(itemTable[itemIndex].getTitle());
cards.add(gifCard);
}
if (itemTable[itemIndex].getTypeId() == 1) { // 1 = image
Card card = new Card(getActivity());
CardHeader header = new CardHeader(getActivity());
header.setTitle(itemTable[itemIndex].getTitle());
card.addCardHeader(header);
MyThumbnail thumb = new MyThumbnail(getActivity(), itemTable[itemIndex].getObjectUrl());
thumb.setExternalUsage(true);
card.addCardThumbnail(thumb);
final int index = itemIndex;
card.addPartialOnClickListener(Card.CLICK_LISTENER_THUMBNAIL_VIEW, new Card.OnCardClickListener() {
#Override
public void onClick(Card card, View view) {
Intent intent = new Intent(getActivity(), FullscreenActivity.class);
intent.putExtra("imageUrl", itemTable[index].getObjectUrl());
startActivity(intent);
}
});
cards.add(card);
}
}
if (flag == 0) {
mCardArrayAdapter = new CardArrayAdapter(getActivity(), cards);
listView = (CardListView) getActivity().findViewById(
R.id.carddemo_list);
listView.setAdapter(mCardArrayAdapter);
flag = 1;
}
}
else {
loadMore = false;
}
loadMoreCards(mCardArrayAdapter, loadMore);
}
public void loadMoreCards(CardArrayAdapter mCardArrayAdapter, boolean loadMore) {
if (listView != null) {
mCardArrayAdapter.notifyDataSetChanged();
if (loadMore) {
listView.setOnScrollListener(new EndlessScrollListener() {
#Override
public void onLoadMore(int page, int totalItemsCount) {
limit += 5;
List<String> params = new ArrayList();
params.add("1");
params.add(String.valueOf(limit));
GetItemTask getItemTask = new GetItemTask();
getItemTask.setOnResultsListener(listener);
getItemTask.execute(params);
}
});
}
}
}
//fin placeholderfrag
#Override
public void onGetImageTaskSucceeded(Bitmap bitmap) {
// TODO Auto-generated method stub
}
}
Thanks #GabrieleMariotti, it helped ! In fact I already tried to use different classes for the different fragments, but I forget to give diferent IDs to my cardsLists. It solved the problem. Btw, good job for your lib, it is awesome.
So for the next one : create differents classes for all your differents fragments. They have to use differents layout, and the cardsList have to use differents ID.
how are you ?
i just found a code that let me create tabs and navigate through tabs in my android application... but in fact i faced a little problem
in this code the name of the tabs is Section + its number position
i am wondering if i can change the name of every tab and every name can be different
here's the code coders :
package com.example.android.effectivenavigation;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
// Set up the action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home/Up button should not be enabled, since there is no hierarchical
// parent.
actionBar.setHomeButtonEnabled(false);
// Specify that we will be displaying tabs in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between different app sections, select the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if we have a reference to the
// Tab.
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by the adapter.
// Also specify this Activity object, which implements the TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
* sections of the app.
*/
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
// The first section of the app is the most interesting -- it offers
// a launchpad into the other demonstrations in this example application.
return new LaunchpadSectionFragment();
default:
// The other sections of the app are dummy placeholders.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
fragment.setArguments(args);
return fragment;
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
return "Section " + (position + 1);
}
}
/**
* A fragment that launches other parts of the demo application.
*/
public static class LaunchpadSectionFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_launchpad, container, false);
// Demonstration of a collection-browsing activity.
rootView.findViewById(R.id.demo_collection_button)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), CollectionDemoActivity.class);
startActivity(intent);
}
});
// Demonstration of navigating to external activities.
rootView.findViewById(R.id.demo_external_activity)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create an intent that asks the user to pick a photo, but using
// FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET, ensures that relaunching
// the application from the device home screen does not return
// to the external activity.
Intent externalActivityIntent = new Intent(Intent.ACTION_PICK);
externalActivityIntent.setType("image/*");
externalActivityIntent.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(externalActivityIntent);
}
});
return rootView;
}
}
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_dummy, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
getString(R.string.dummy_section_text, args.getInt(ARG_SECTION_NUMBER)));
return rootView;
}
} }
The Tab title is appearing as Section + its number because you are setting it that way when creating the tabs in your code - .setText(mAppSectionsPagerAdapter.getPageTitle(i)). See below...
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by the adapter.
// Also specify this Activity object, which implements the TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i)) //this is where the title is set
.setTabListener(this));
}
Set the text .setText() as your desire.
For example, a simple way is to check the counter and set the title appropriately...
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
// one simple way
if(i == 0) {
actionBar.addTab(actionBar.newTab()
.setText("First Tab")
.setTabListener(this));
}
}
See ActionBar DOCS