I have a fragment (AdvertismentFragment) that contains two tabs, now the thing is i need to open in the layout of the first tab a fragment as shown bellow (AdsFragment).. now when i click for the first time the fragment is displayed within the tab and all its content, but when i leave this fragment and return it doesn't display the fragment inside the tab...
here is the code of one of the tabs:
public class AdsFragment extends Fragment {
public AdsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_ads, container, false);
getFragmentManager().beginTransaction().replace(R.id.attending_layout,EventsFragment.newInstance("all","upcoming")).commit();
return v;
}
}
what should i do then ???
here is the fragment that holds the two tabs:
public class AdvertisementFragment extends Fragment implements ViewPager.OnPageChangeListener, TabHost.OnTabChangeListener {
private TabHost tabHost;
private ViewPager viewPager;
private View v;
public AdvertisementFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_advertisement, container, false);
initViewPager();
initTabHost();
return v;
}
/**
* Initialize the {#link TabHost} {#code tabHost}.
*/
private void initTabHost() {
tabHost = ((TabHost) v.findViewById(R.id.tabHost));
tabHost.setup();
/**
* {#code tabName} {#link String} will hold the tab names.
*/
String tabName[] = { "Ads","Videos"};
for (int i = 0; i < tabName.length; i++) {
TabHost.TabSpec tabSpec;
tabSpec = tabHost.newTabSpec(tabName[i]);
tabSpec.setIndicator(tabName[i]);
tabSpec.setContent(new FakeContent(getActivity()));
tabHost.addTab(tabSpec);
}
/**
* Change the Text color associated with the {#link android.widget.TabWidget}.
*/
for (int tabIndex = 0; tabIndex < tabHost.getTabWidget().getTabCount(); tabIndex++) {
View tab = tabHost.getTabWidget().getChildTabViewAt(tabIndex);
TextView t = (TextView) tab.findViewById(android.R.id.title);
t.setTextColor(Color.parseColor("#1976D2"));
t.setAllCaps(false);
Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(),"Roboto-Medium.ttf");
t.setTypeface(typeface);
tab.setBackgroundResource(R.drawable.apptheme_tab_indicator_holo);
}
tabHost.getTabWidget().setDividerDrawable(null);
tabHost.setOnTabChangedListener(this);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
tabHost.setCurrentTab(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onTabChanged(String s) {
int selectedItem = tabHost.getCurrentTab();
viewPager.setCurrentItem(selectedItem);
/**
* Using {#link HorizontalScrollView} {#code horizontalScrollView}
* we can display page by page to the user while pressing the tab.
*/
HorizontalScrollView horizontalScrollView = (HorizontalScrollView) v.findViewById(R.id.h_scroll_view);
View tabView = tabHost.getCurrentTabView();
/**
* Allow the Scroll to be smooth.
*/
int scrollPos = tabView.getLeft() - (horizontalScrollView.getWidth() - tabView.getWidth() / 2);
horizontalScrollView.smoothScrollTo(scrollPos, 0);
}
/**
* Create and return the content of each tab created.
*/
public class FakeContent implements TabHost.TabContentFactory {
private Context context;
public FakeContent(Context context) {
this.context = context;
}
/**
* Callback to make the tab contents
*
* #param tag Which tab was selected.
* #return The view to display the contents of the selected tab.
*/
#Override
public View createTabContent(String tag) {
View fakeView = new View(context);
fakeView.setMinimumHeight(0);
fakeView.setMinimumWidth(0);
return fakeView;
}
}
private void initViewPager() {
viewPager = (ViewPager) v.findViewById(R.id.view_pager);
//viewPager.setPageTransformer(true, new AnimationUtilities.DepthPageTransformer());
List<Fragment> fragmentList = new ArrayList<Fragment>();
fragmentList.add(new AdsFragment());
fragmentList.add(new VideoFragment());
MyFragmentPagerAdapter myFragmentPagerAdapter = new MyFragmentPagerAdapter(((MainActivity)getActivity()).getFragmentManager(), fragmentList);
viewPager.setAdapter(myFragmentPagerAdapter);
viewPager.setOnPageChangeListener(this);
}
}
Related
I'm trying to open a new fragment in viewpager's fragment using this as example. But I'm getting this error of IndexOutOfBoundsException in the line tabLayout.getTabAt(0).setIcon(tabIcons[0]);. I pasted the logcate here. Can any one tell me how to solve this as I need tablayout with my viewpager while the example didn't had one?
public class FirstFragment extends Fragment {
private static final String TAG = "FirstFragment";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.first_fragment, container, false);
Button btn = (Button) view.findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction trans = getFragmentManager()
.beginTransaction();
/*
* IMPORTANT: We use the "root frame" defined in
* "root_fragment.xml" as the reference to replace fragment
*/
trans.replace(R.id.root_frame, new SecondFragment());
/*
* IMPORTANT: The following lines allow us to add the fragment
* to the stack and return to it later, by pressing back
*/
trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
trans.addToBackStack(null);
trans.commit();
}
});
return view;
}
}
First tab:
public class RootFragment extends Fragment {
private static final String TAG = "RootFragment";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/* Inflate the layout for this fragment */
View view = inflater.inflate(R.layout.root_fragment, container, false);
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
/*
* When this container fragment is created, we fill it with our first
* "real" fragment
*/
transaction.replace(R.id.root_frame, new FirstFragment());
transaction.commit();
return view;
}
}
Main Activity:
public class MainActivity extends AppCompatActivity {
// For this example, only two pages
static final int NUM_ITEMS = 2;
private TabLayout tabLayout;
private ViewPager mPager;
private int[] tabIcons = {
R.drawable.facebook,
R.drawable.twitter
};
SlidePagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Instantiate a ViewPager and a PagerAdapter. */
tabLayout=(TabLayout)findViewById(R.id.tabs);
mPager = (ViewPager) findViewById(R.id.viewpager);
mPagerAdapter = new SlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
setupTabIcons();
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
}
/* PagerAdapter class */
public class SlidePagerAdapter extends FragmentPagerAdapter {
public SlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
/*
* IMPORTANT: This is the point. We create a RootFragment acting as
* a container for other fragments
*/
if (position == 0)
return new RootFragment();
else
return new StaticFragment();
}
#Override
public int getCount() {
return NUM_ITEMS;
}
}
}
use below function
private void setupTabIcons() {
tabLayout.addTab(tabLayout.newTab().setIcon(tabIcons[0]));
tabLayout.addTab(tabLayout.newTab().setIcon(tabIcons[1]));
}
you have not added any tab to your tabLayout, so you get IndexOutOfBoundsException
Adapter: here I want images
public class MyFragmentPagerAdapter extends FragmentPagerAdapter{
final int PAGE_COUNT = 5;
Context mContext;
/** Constructor of the class */
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
/** This method will be invoked when a page is requested to create */
#Override
public Fragment getItem(int arg0) {
MyFragment myFragment = new MyFragment();
Bundle data = new Bundle();
data.putInt("current_page", arg0+1);
myFragment.setArguments(data);
return myFragment;
}
/** Returns the number of pages */
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
return "Page #" + ( position + 1 );
}
}
Fragment
public class MyFragment extends Fragment{
int mCurrentPage;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Getting the arguments to the Bundle object */
Bundle data = getArguments();
/** Getting integer data of the key current_page from the bundle */
mCurrentPage = data.getInt("current_page", 0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.myfragment_layout, container,false);
TextView tv = (TextView ) v.findViewById(R.id.tv);
tv.setText("You are viewing the page #" + mCurrentPage + "\n\n" + "Swipe Horizontally left / right");
return v;
}
}
MainActivity
public class MainActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** Getting a reference to the ViewPager defined the layout file */
ViewPager pager = (ViewPager) findViewById(R.id.pager);
/** Getting fragment manager */
FragmentManager fm = getSupportFragmentManager();
/** Instantiating FragmentPagerAdapter */
MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(fm);
/** Setting the pagerAdapter to the pager object */
pager.setAdapter(pagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
I want to add custom images and text in the ViewPager just like in the image(circled part). I'm getting text using this link. But I want custom Image above text and custom string[] for text like here.
.
I'm relatively new to the Android development and encountered the following problem:
I have a ListView with a corresponding ArrayAdapter which delivers simple item views. The item views are structured in a simple RelatveLayout manner revealing some behavior if clicked or long-pressed using the callback methods of OnItemClickListener and OnItemLongClickListener. This works fine so far. However, if I add an ImageButton to the item view with a corresponding onClick-callback, the original listener-methods on the item view itself don't work any more. The items in the ListView can't be selected any more as well. Why?
public class ProfileActivity extends Activity implements ActionBar.TabListener {
private static final String DEBUG_TAG = ProfileActivity.class
.getSimpleName();
private XMLBinder profilesDao;
private Config config;
/**
* 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_profile);
getActionBar().setSubtitle("Game Profiles");
// load profiles:
profilesDao = new XMLBinder(this);
try {
config = profilesDao.deserialize(Config.class,
R.raw.default_profiles);
} catch (Exception e) {
if (BuildConfig.DEBUG) {
Log.e(DEBUG_TAG, e.toString());
}
}
// 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(),
config.getCategories());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// 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);
}
});
// 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));
}
// SharedPreferences pref = getSharedPreferences("AGT",
// Context.MODE_PRIVATE);
// SharedPreferences.Editor prefEditor = pref.edit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.profile, 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.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private List<Category> categories;
/** */
public SectionsPagerAdapter(final FragmentManager fm,
final List<Category> categories) {
super(fm);
this.categories = categories;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class
// below).
final List<Profile> profiles = config.getCategories().get(position)
.getProfiles();
return PlaceholderFragment.newInstance(position + 1, profiles,
ProfileActivity.this);
}
#Override
public int getCount() {
// Show x total pages.
return this.categories.size();
}
#Override
public CharSequence getPageTitle(int position) {
return categories.get(position).getName();
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment implements
OnItemClickListener {
private List<Profile> list;
private ProfilesAdapter profilesAdapter;
private Context context;
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
*
* #param list
*/
public static PlaceholderFragment newInstance(int sectionNumber,
List<Profile> list, Context context) {
final PlaceholderFragment fragment = new PlaceholderFragment(list,
context);
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
super();
}
/** */
public PlaceholderFragment(List<Profile> list, Context context) {
this();
this.list = list;
this.context = context;
this.profilesAdapter = new ProfilesAdapter(this.context,
R.layout.view_profile, this.list);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_profile,
container, false);
// Configure the ListView with Adapter
final ListView profilesView = (ListView) rootView
.findViewById(R.id.profilesView);
profilesView.setAdapter(profilesAdapter);
// #TODO:
// profilesView.setDivider();
// profilesView.setEmptyView(emptyView);
profilesView.setOnItemClickListener(this);
profilesAdapter.notifyDataSetChanged();
return rootView;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if (view != null) {
final GameProfile selectedProfile = (GameProfile) parent
.getItemAtPosition(position);
final Intent intent = new Intent(this.context,
ChessClockActivity.class);
intent.putExtra(GameProfile.INTENT_EXTRA_SELECTED_PROFILE,
selectedProfile);
startActivity(intent);
}
}
}
/**
* #author Andy
*
*/
public static class ProfilesAdapter extends ArrayAdapter<Profile> {
private Context context;
private List<Profile> profiles;
/** */
public ProfilesAdapter(Context context, int resource,
List<Profile> profiles) {
super(context, resource, profiles);
this.context = context;
this.profiles = profiles;
}
#Override
public View getView(final int position, final View convertView,
final ViewGroup parent) {
View profileView = convertView;
if (null == profileView) {
final LayoutInflater inflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
profileView = inflater.inflate(R.layout.view_profile, null);
}
final TextView name = (TextView) profileView
.findViewById(R.id.profile_name);
name.setText(profiles.get(position).getTitle());
final TextView hint = (TextView) profileView
.findViewById(R.id.profile_desc);
hint.setText(profiles.get(position).getHint());
hint.setMaxLines(1);
hint.setEllipsize(TruncateAt.END);
return profileView;
}
}
}
use
android:descendantFocusability="blocksDescendants"
android:focusable="false"
hope it helps
Dont know if it's gonna help
ImageView yourImg=(ImageView).findViewById(R.id.icon);
yourImg.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// things you want to do
}
});
I am a beginner to android applications,I working around tab+swipe application,
my main class is like belove. please help me out.
public class MainScreenViewActivity extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.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.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
private static String list_display_data1 = "item#sec1";
private static String list_display_data2 = "item#sec2";
private static String list_display_data3 = "item#sec3";
private static View rootView;
/**
* 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_screen_view);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
/*mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
// When swiping between pages, select the
// corresponding tab.
getActionBar().setSelectedNavigationItem(position);
}
});*/
}
#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_screen_view, menu);
return true;
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = null;
fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#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;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(
R.layout.fragment_main_screen_view_dummy, container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
dummyTextView.setVisibility(View.INVISIBLE);
if(dummyTextView.getVisibility() == View.VISIBLE){
ListView sessionList = (ListView) rootView.findViewById(R.id.session_list);
initListView(getActivity(), sessionList, list_display_data1, 30, android.R.layout.simple_list_item_1);
}
else{
Log.d("", "");
}
//ListView sessionList = (ListView) rootView.findViewById(R.id.session_list);
//initListView(getActivity(), sessionList, list_display_data1, 30, android.R.layout.simple_list_item_1);
return rootView;
}
}
public static void initListView(Context context, ListView listView,String prefix, int numItems, int layout ){
// By using setAdpater method in listview we an add string array in list.
String[] arr = new String[numItems];
for(int i = 0; i< arr.length; i++){
arr[i] = prefix + (i +1);
}
listView.setAdapter(new ArrayAdapter<String>(context, layout, arr));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Context context = view.getContext();
String msg = "item[" + position + "]= " + parent.getItemIdAtPosition(position);
Toast.makeText(context, msg, 1000).show();
System.out.println(msg);
}
});
}
}
in onCreateView of dummySectionFragment how to add different list view. I just able to work on visibility of view.
You should Add Fragments to your viewpager for different page for different Tabs.
I decided to create some small library which create awesome menu using ViewPager, Tabhost and FragmentActivity. So I have 3 small classes:
Draw menu (drawing all xml things)
public class DrawAMKMenu extends FragmentActivity {
protected LinearLayout mLinearLayout;
protected static TabHost mTabHost;
protected static Context mContext;
protected ViewPager mViewPager;
protected RelativeLayout mMenuBar;
protected Resources res;
protected int screenwidth;
protected Drawable ThumbResource = null;
protected Drawable menuBg = null;
protected TabWidget tw;
/**
* constructor
* #param c
* #param main_layout
*/
protected DrawAMKMenu(FragmentActivity fa, LinearLayout main_layout){
mContext = fa.getApplicationContext();
mLinearLayout = main_layout;
res = fa.getResources();
Display display = fa.getWindowManager().getDefaultDisplay();
screenwidth = display.getWidth();
}
/**
*Draw main LinearLayout
*/
protected void DrawMenu()
{
mLinearLayout.removeAllViews();
mLinearLayout.setBaselineAligned(true);
mLinearLayout.setOrientation(LinearLayout.VERTICAL);
mLinearLayout.addView(createTabHost());
}
/**
* #return TabHost
* draw the TabHost view
*/
protected TabHost createTabHost(){
mTabHost = new TabHost(mContext);
mTabHost.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
mTabHost.addView(createTabContentLayout());
mTabHost.addView(createViewPager());
mTabHost.addView(createMenuBar());
mTabHost.setTag("TabHost");
SetupTabs(mTabHost);
return mTabHost;
}
/**
* Create FrameLayout for Content
* #return FrameLayout
*/
protected FrameLayout createTabContentLayout(){
/*Frame layout for Content*/
FrameLayout fl = new FrameLayout(mContext);
fl.setLayoutParams(new LinearLayout.LayoutParams(0,0,1));
fl.setId(android.R.id.tabcontent);
/*------------------------*/
return fl;
}
/**
* #return ViewPager
* draw ViewPager element
*/
protected ViewPager createViewPager(){
mViewPager = new ViewPager(mContext);
mViewPager.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,1));
mViewPager.setBackgroundColor(Color.WHITE);
mViewPager.setTag("viewpager");
return mViewPager;
}
/**
* #return RelativeLayout
* draw Menu bar
*/
protected RelativeLayout createMenuBar(){
/* Layout for Menu Bar */
mMenuBar = new RelativeLayout(mContext);
mMenuBar.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
//mMenuBar.setGravity(Gravity.BOTTOM);
/* ------------------ */
/* Tab Widget*/
tw = new TabWidget(mContext);
tw.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT,0));
tw.setOrientation(LinearLayout.HORIZONTAL);
tw.setId(android.R.id.tabs);
if(menuBg != null)
tw.setBackgroundDrawable(menuBg);
/*-----------*/
/* Scroll bar for menu */
HorizontalScrollView hsv = new HorizontalScrollView(mContext);
hsv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT,0));
hsv.setScrollBarStyle(View.GONE);
hsv.setFillViewport(true);
/* ----------------- */
//add tabWidget to HorizontalScrollView
hsv.addView(tw);
/*Seek Bar*/
SeekBar sb = new SeekBar(mContext);
sb.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
sb.setBackgroundColor(Color.TRANSPARENT);
sb.setProgressDrawable(res.getDrawable(android.R.id.empty));
if(ThumbResource!=null)
sb.setThumb(ThumbResource);
else
sb.setThumb(res.getDrawable(android.R.id.empty));
/*-------*/
/*Frame layout for SeekBar*/
FrameLayout fl = new FrameLayout(mContext);
fl.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
fl.addView(sb);
/*------------------------*/
mMenuBar.addView(hsv);
mMenuBar.addView(fl);
return mMenuBar;
}
/**
* Delete bottom strip from tabhost
* #param tabHost
*/
protected void SetupTabs(TabHost tabHost) {
Field mBottomLeftStrip;
Field mBottomRightStrip;
try {
mBottomLeftStrip = tw.getClass().getDeclaredField("mBottomLeftStrip");
mBottomRightStrip = tw.getClass().getDeclaredField("mBottomRightStrip");
if (!mBottomLeftStrip.isAccessible()) {
mBottomLeftStrip.setAccessible(true);
}
if (!mBottomRightStrip.isAccessible()) {
mBottomRightStrip.setAccessible(true);
}
mBottomLeftStrip.set(tw, res.getDrawable(Color.TRANSPARENT));
mBottomRightStrip.set(tw, res.getDrawable(Color.TRANSPARENT));
}
catch (java.lang.NoSuchFieldException e) {
// possibly 2.2
try {
Method stripEnabled = tw.getClass().getDeclaredMethod("setStripEnabled", boolean.class);
stripEnabled.invoke(tw, false);
}
catch (Exception e1) {
e1.printStackTrace();
}
}
catch (Exception e) {}
}
}
PagerAdapter class
public class PagerAdapter extends FragmentPagerAdapter
private List<Fragment> pFragments;
/**
* #param fm
* #param fragments
*/
public PagerAdapter(FragmentManager fm, List<Fragment> fr) {
super(fm);
this.pFragments = fr;
}
/* (non-Javadoc)
* #see android.support.v4.app.FragmentPagerAdapter#getItem(int)
*/
#Override
public Fragment getItem(int position) {
return this.pFragments.get(position);
}
/* (non-Javadoc)
* #see android.support.v4.view.PagerAdapter#getCount()
*/
#Override
public int getCount() {
return this.pFragments.size();
}
}
Create menu class.
public class AMKMenu extends DrawAMKMenu implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
private PagerAdapter mPagerAdapter;
private Vector<Fragment> fragments;
private FragmentManager mFragmentManager;
private FragmentActivity mFragmentActivity;
private static HashMap<Integer, Class<?>> TabsClass;
private static HashMap<Integer, String> TabsTabName;
private static HashMap<Integer, Drawable> TabsIcon;
/**
* CONSTRUCTOR
* Create AMKMenu object to setup settings and
* also initialize menu
* #param c
* #param main_layout
* #param fm
* #param screenWidth
*/
public AMKMenu(FragmentActivity fa, LinearLayout main_layout) {
super(fa, main_layout);
mFragmentActivity = fa;
mFragmentManager = fa.getSupportFragmentManager();
TabsClass = new HashMap<Integer, Class<?>>();
TabsTabName = new HashMap<Integer, String>();
TabsIcon = new HashMap<Integer, Drawable>();
}
/**
* Final method to create menu
* Use it after you setup all settings
*/
public void createMenu(){
super.DrawMenu();
initializeTabHost();
intializeViewPager();
}
/**
* A simple factory that returns dummy views to the Tabhost
* #author Gavryschuk Anatoliy V.
*/
public class TabFactory implements TabContentFactory {
private final Context fContext;
/**
* #param context
*/
public TabFactory(Context context) {
fContext = context;
}
/** (non-Javadoc)
* #see android.widget.TabHost.TabContentFactory#createTabContent(java.lang.String)
*/
public View createTabContent(String tag) {
View v = new View(fContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
/**
* Initialize ViewPager
*/
protected void intializeViewPager() {
fragments = new Vector<Fragment>();
if(getTabsClass().size()>0)
{
for(int i=0;i<getTabsClass().size();i++)
{
fragments.add(Fragment.instantiate(mFragmentActivity, getTabsClass(i).getName()));
}
}
setPagerAdapter(new PagerAdapter (mFragmentManager, fragments));
mViewPager.setAdapter(getPagerAdapter());
mViewPager.setOnPageChangeListener(this);
}
/**
* Initialize the Tab Host
*/
protected void initializeTabHost() {
if(getTabsClass().size()>0)
{
TabHost mTabHost = (TabHost) mLinearLayout.findViewWithTag("TabHost");
mTabHost.setup();
for(int i=0;i<getTabsClass().size();i++)
{
TabSpec tabSpec = mTabHost.newTabSpec(getTabsTabName(i));
tabSpec.setIndicator(getTabsTabName(i), getTabsIcon(i));
tabSpec.setContent(new TabFactory(mFragmentActivity));
mTabHost.addTab(tabSpec);
}
mTabHost.setOnTabChangedListener(this);
mTabHost.getTabWidget().setHorizontalScrollBarEnabled(false);
for(int i=0;i<mTabHost.getTabWidget().getChildCount();i++)
{
//mTabHost.getTabWidget().getChildAt(i).setLayoutParams(new LinearLayout.LayoutParams(65,65));
mTabHost.getTabWidget().getChildAt(i).setBackgroundResource(0);
}
// mTabHost.setCurrentTab(0);
}else
return;
}...
}
after I use this library in this way
AMKMenu menu = new AMKMenu(this, (LinearLayout)findViewById(R.id.main_layout));
menu.setMenuBg(getResources().getDrawable(R.drawable.menu_bg));
menu.setCursor(getResources().getDrawable(R.drawable.new_cursor));
menu.AddTab(Tab1Fragment.class, "tab1", getResources().getDrawable(R.drawable.f_icon));
menu.AddTab(Tab2Fragment.class, "tab2", getResources().getDrawable(R.drawable.s_icon));
menu.AddTab(Tab3Fragment.class, "tab3", getResources().getDrawable(R.drawable.t_icon));
menu.createMenu();
I get error
java.lang.IllegalArgumentException: No new found for id for fragment
The problem is in intializeViewPager() method in AMKMenu class.
Please Somebody (Android guru) help me what do I do wrong?
I hope I explained everything clear.
Hear is my solution for the (Tabs + Fragment + ViewPager) it is works for me as i wanted, hope that works for you as well
hear is the xml file
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="5" />
<FrameLayout
android:id="#+id/fragment_details"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="4.3" />
</LinearLayout>
hear is the code for MainActivity.java I'll post relevant code only so you'll have to manage it
public class MainActivity extends FragmentActivity implements
DialogInterface.OnDismissListener, TabDataResponder {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
artistTab = getSupportActionBar().newTab().setText(
R.string.tab_name_artist);
albumTab = getSupportActionBar().newTab().setText(
R.string.tab_name_album);
songTab = getSupportActionBar().newTab().setText(
R.string.tab_name_songs);
map = new HashMap<String, Integer>();
mViewPager = (ViewPager) findViewById(R.id.pager);
FrameLayout deatil = (FrameLayout) findViewById(R.id.fragment_details);
mDualPane = (deatil != null) && (deatil.getVisibility() == View.VISIBLE);
mTabsAdapter = new TabsAdapter(this, getSupportActionBar(), mViewPager);
if (savedInstanceState != null) {
flag = true;
index = savedInstanceState.getInt("index");
}
setUpTabView();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("index", getSupportActionBar()
.getSelectedNavigationIndex());
}
private void setUpTabView() {
mTabsAdapter.addTab(artistTab, ArtistFragment.class, null);
mTabsAdapter.addTab(albumTab, AlbumFragment.class, null);
mTabsAdapter.addTab(songTab, SongFragment.class, null);
getSupportActionBar().setSelectedNavigationItem(index);
}
public static class TabsAdapter extends FragmentPagerAdapter implements
ViewPager.OnPageChangeListener, ActionBar.TabListener {
private FragmentActivity mContext;
private ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<String> mTabs = new ArrayList<String>();
private TabDataResponder responder;
public TabsAdapter(FragmentActivity activity, ActionBar actionBar,
ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = actionBar;
mViewPager = pager;
// TabDataResponder is an interface which is implemented in MainActivity
// You can find implementation # the last
responder = (TabDataResponder) activity;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
//I have used map to save state of the fragment
map.put(SongFragment.TYPE_FRAGMENT.trim(), 0);
map.put(AlbumFragment.TYPE_FRAGMENT.trim(), 0);
map.put(ArtistFragment.TYPE_FRAGMENT.trim(), 0);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
mTabs.add(clss.getName());
// mArgs.add(args);
mActionBar.addTab(tab.setTabListener(this));
notifyDataSetChanged();
}
#Override
public int getCount() {
return mTabs.size();
}
#Override
public Fragment getItem(int position) {
return Fragment
.instantiate(mContext, mTabs.get(position), /*
* mArgs.get(
* position)
*/null);
}
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Log.i(TAG, "PageSelected....");
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
Log.i(TAG, "ScrollSateChanged....");
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
String a = null;
if (mDualPane) {
a = mTabs.get(tab.getPosition());
responder.loadData(a, map.get(a));
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
Log.i(TAG, "Tab is released now....");
}
}
#Override
public void onDismiss(DialogInterface dialog) {
setUpTabView();
}
//This interface must be call from fragment class
//# the time of event you want to show detail
// pass the class name in the type argument using class.getName() method
#Override
public void loadData(String type, int index) {
DetailFragment viewer = (DetailFragment) getSupportFragmentManager()
.findFragmentById(R.id.fragment_details);
if (mDualPane) {
if (viewer == null || viewer.getShownIndex() != index
|| viewer.getTypeFragment() != type) {
DetailFragment df = DetailFragment.newInstance(index, type);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_details, df)
.setTransition(
FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
map.put(type.trim(), index);
}
} else {
Intent intent = new Intent();
intent.setClass(MainActivity.this, DetailActivity.class);
intent.putExtra("index", index);
intent.putExtra("type", type);
startActivity(intent);
}
}
}
and hear is how i deal with detail fragment not very efficient but kind of working
public class DetailFragment extends Fragment{
public static DetailFragment newInstance(int index, String TYPE_FRAGMENT) {
DetailFragment f = new DetailFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
args.putString("type", TYPE_FRAGMENT);
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
public String getTypeFragment(){
String a = getArguments().getString("type");
return a;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//template is blank layout
View view = inflater.inflate(R.layout.template, container, false);
if(getTypeFragment().equals(ArtistFragment.TYPE_FRAGMENT)){
view = null;
view = inflater.inflate(R.layout.artist_details, container, false);
//....
}
else if(getTypeFragment().equals(AlbumFragment.TYPE_FRAGMENT)){
//do's for album fragment
}
else if(getTypeFragment().equals(SongFragment.TYPE_FRAGMENT)){
//do's for song fragment
}
return view;
}
}
do not save the state of tab in their individual fragment it will conflict, we are already doing it hear
Hope It Helps