Here is the library: https://github.com/astuetz/PagerSlidingTabStrip
I'm trying to implement it but my app keeps crashing on startup. I've tried to understand the sample app that is posted but don't think I'm doing something right. Here is my code:
MainActivity.java
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
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.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.astuetz.PagerSlidingTabStrip;
public class MainActivity extends FragmentActivity {
private final Handler handler = new Handler();
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private MyPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
pager = (ViewPager) findViewById(R.id.pager);
adapter = new MyPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
}
#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
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
}
private Drawable.Callback drawableCallback = new Drawable.Callback() {
#Override
public void invalidateDrawable(Drawable who) {
getActionBar().setBackgroundDrawable(who);
}
#Override
public void scheduleDrawable(Drawable who, Runnable what, long when) {
handler.postAtTime(what, when);
}
#Override
public void unscheduleDrawable(Drawable who, Runnable what) {
handler.removeCallbacks(what);
}
};
public class MyPagerAdapter extends FragmentPagerAdapter{
private final String[] TITLES = {"T1","T2"};
public MyPagerAdapter(FragmentManager fm){
super(fm);
}
public CharSequence getPageTitle(int position){
return TITLES[position];
}
#Override
public Fragment getItem(int i) {
return null;
}
#Override
public int getCount() {
return TITLES.length;
}
}
}
And here is activity_main.xml
<RelativeLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="edu.purdue.test.app.MainActivity">
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tabs"
tools:context=".MainActivity" />
</RelativeLayout>
You're not instantiating any of the fragments you wish to become tabs in the FragmentPagerAdapter, getItem method. Instead you're returning null and therefore there are no views to fill the viewpager. I can see you've checked out his sample project, maybe take a closer look at the fragments you're trying to add to the viewpager. The above answer looks like a sound implementation.
Here is an example that I am using right now,
public class Formulario extends FragmentActivity implements ActionBar.TabListener {
private static final FragmentTransaction transaction = null;
public String ambitorec;
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "tab 1", "tab 2", "tab 3" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_formulario);
ambitorec = getIntent().getStringExtra("ambito");
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
also you need to add the adapter, in this case :
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// tab 1 fragment activity
return new Formulario1Fragment();
case 1:
// tab2 fragment activity
return new Formulario2Fragment();
case 2:
// tab 3 fragment activity
return new MultimediaFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
hope it helps, if you need more help ill try to explain
In FragmentPagerAdapter#getItem, you are not instantiating any of the fragments you want to become tabs. Instead of returning a fragment, you're returning null, which means there are no views to fill the viewpager. I see you've looked over his sample project, so look over the fragments you're trying to add to the viewpager again. The above response appears to be a second implementation.
Related
Like a title , how can i fix it
Error
java.lang.RuntimeException:
com.example.doanlttbdd.MainActivity#28acf243 must implement
OnFragmentInteractionListener
There is MainActivity
public class MainActivity extends AppCompatActivity {
private Toolbar mToolbar;
private ViewPager viewPager;
private TabLayout tabLayout;
private TabsAccessorAdapter tabsAccessorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar= findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("F9");
viewPager= findViewById(R.id.main_tabs_paper);
tabsAccessorAdapter= new TabsAccessorAdapter(getSupportFragmentManager());
viewPager.setAdapter(tabsAccessorAdapter);
tabLayout= findViewById(R.id.main_tabs);
tabLayout.setupWithViewPager(viewPager);
}
Here is myAdapter
public TabsAccessorAdapter(#NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
#NonNull
#Override
public Fragment getItem(int i) {
switch (i){
case 0:
ChatsFragment chatsFragment=new ChatsFragment();
return chatsFragment;
case 1:
GroupsFragment groupsFragment=new GroupsFragment();
return groupsFragment;
case 2:
ContactsFragment contactsFragment=new ContactsFragment();
return contactsFragment;
default:
return null;
}
}
#Override
public int getCount() {
return 3;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "Chats";
case 1:
return "Groups";
case 2:
return "Contacts";
default:
return null;
}
}
My chatsfragment
public class ChatsFragment extends Fragment {
public ChatsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_chats, container, false);
}
the other fragment just like this
i think it is bacause i'm using androidx so i cannot find any solution to fix it in the internet
RedLine in this (getSupportFragmentManager())
The quick solution first then the explanation
public class MainActivity extends AppCompatActivity implements OnFragmentInteractionListener
It is gonna red lint the MainActivity, alt + enter and choose the solution it will add the missing methods.
The problem is one of your fragments need the parent activity implements that interface to be used as a callback. Probably the fragment is doing something like this
#Override
onAttach...
if context is casteable to the Interface then initialize a field, otherwise crash with the message
These are common patterns. The callback in the parent activity is used to coordinate with other fragments.It is a way to know when something happen on a fragment and then do something on other. The exception throwed is to make sure you implement the needed interface.
This also probably happen for using the fragment wizarf on Android Studio but not reading the checkbox Include callback...
Create a new project.
create a pager adapter TabsPagerAdapter.java
import info.androidhive.tabsswipe.GamesFragment;
import info.androidhive.tabsswipe.MoviesFragment;
import info.androidhive.tabsswipe.TopRatedFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new TopRatedFragment();
case 1:
// Games fragment activity
return new GamesFragment();
case 2:
// Movies fragment activity
return new MoviesFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
Now create First Tab View fragment_top_rated.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="#fa6a6a" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Design Top Rated Screen"
android:textSize="20dp"
android:layout_centerInParent="true"/>
</RelativeLayout>
now create TopRatedFragment.java
import info.androidhive.tabsswipe.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TopRatedFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
return rootView;
}
}
similarly repeat step 3 and 4 to create GamesFragment and MoviesFragment and their XML
now create MainActivity.java
import info.androidhive.tabsswipe.adapter.TabsPagerAdapter;
import info.androidhive.tabsswipe.R;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Top Rated", "Games", "Movies" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
I'm trying to implement a swipe tab views like this http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/.
But when I try to implement getItems method in the Adapter, it doesn't accept my custom Fragment.
Here's the code:
MyActivity.java
package com.bob.app;
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.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.*;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity implements android.support.v7.app.ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private String[] tabs = { getString(R.string.tab_home), getString(R.string.tab_city), getString(R.string.tab_name),getString(R.string.tab_favorites) };
private DrawerLayout drawerLayout;
private ListView listView;
private String[] Drawer_menu_item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final android.support.v7.app.ActionBar actionbar = getSupportActionBar();
actionbar.setNavigationMode(android.support.v7.app.ActionBar.NAVIGATION_MODE_TABS);
viewPager = (ViewPager) findViewById(R.id.pager);
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionbar.setHomeButtonEnabled(true);
// Adding Tabs
for (String tab_name : tabs) {
actionbar.addTab(actionbar.newTab().setText(tab_name)
.setTabListener((android.support.v7.app.ActionBar.TabListener) this));
Drawer_menu_item= getResources().getStringArray(R.array.menu_item);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
listView = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
listView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer, Drawer_menu_item));
/* Set the list's click listener
listView.setOnItemClickListener(new DrawerItemClickListener());*/
}
}
#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;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(android.support.v7.app.ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {
}
#Override
public void onTabUnselected(android.support.v7.app.ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {
}
#Override
public void onTabReselected(android.support.v7.app.ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {
}
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
/* Home fragment
return new Home_fragment();
case 1:
/* City fragment
return new City_fragment();
case 2:
/* Name fragment
return new Name_fragment();
case 3:
/* Favourites fragment
return new Fav_fragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return tabs.length;
}
}
}
Name_fragment.java
package com.bob.sluurpy.app;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by boob on 11/09/15.
*/
public class Name_fragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.name, container, false);
return rootView;
}
}
Please import this import android.support.v4.app.Fragment; in place of import android.app.Fragment; in Name_fragment this may solve your issue!
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.parse.ParseAnalytics;
import com.parse.ParseUser;
import adapter.SectionPargerAdapter;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener
{
public static final String TAG = MainActivity.class.getSimpleName();
/**
* 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}.
*/
SectionPargerAdapter mSectionPargerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ParseAnalytics.trackAppOpened(getIntent());
ParseUser currentUser = ParseUser.getCurrentUser();
if(currentUser == null) {
navigateToLogin();
} else {
Log.i(TAG, currentUser.getUsername());
}
final ActionBar actionBar = getActionBar();
// actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionPargerAdapter = new SectionPargerAdapter(this, getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionPargerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
for (int i = 0; i < mSectionPargerAdapter.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( mSectionPargerAdapter.getPageTitle(i))
.setTabListener(MainActivity.this));}
}
});
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
private void navigateToLogin() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
#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 itemId = item.getItemId();
//noinspection SimplifiableIfStatement
if (itemId == R.id.action_logout) {
ParseUser.logOut();
navigateToLogin();
}
return super.onOptionsItemSelected(item);
}
}
I face actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS) has produce NullPointerException. How can I fix this error? I don't know how to fix. In tutorial video, this has no error but tutorial use with Eclipse. I use Android Studio. Please tell me how to fix? Thanks you very much!
Take a look at this one over here. This guy implements it very nice. However i would not suggest working with actionBar tabs because if you want to upgrade your app to later versions this method is deprecated. So you dont use the actionBar and you can use the following if you would like
YourAdapter mAdapter;
ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection_demo);
// ViewPager and its adapters use support library
// fragments, so use getSupportFragmentManager.
mAdapter = new YourAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAdapter);
}
The Adapter:
public class YourAdapter extends FragmentStatePagerAdapter {
private String[] titles = { "Item 1", "Item 2", "Item 3" };
public YourAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch(i){
case 0:{
return new FragementA();
}case 1:{
return new FragmentB();
}case 2:{
return new FragmentC();
}
}
}
#Override
public int getCount() {
return titles.length;
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
The Fragment that you will return and implementation of the onCreateView Method:
public static class FragmentA extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.my_layout_file, container, false);
//Simple implementation how to target text view in your layout
TextView tv = (TextView)rootView.findViewById(R.id.my_text_view);
return rootView;
}
}
The real problem is in res/values/style.xml and res/values-v14/style.xml in the AppBaseTheme (in two styles).
If change Theme.AppCompat.Light and Theme.AppCompat.Light.DarkActionBar by Theme.Holo.Light and Theme.Holo.Light.DarkActionBar in manifest down android:minSdkVersion to version 11, it SOLVES the problem...
But it generates another problem: you lose AppCompat.Light theme...
But error NullExceptionPointer in actionbar.setNavigationmode is solved..
I am trying to build sample Android app in which the main activity contains a YouTubePlayerFragment. I get no errors with my implementation, but when I run this app on an AVD or my phone, the fragment for the YouTubePlayerFragment is just a black box. No video loads.
Any help is greatly appreciated.
Here is my code:
YouTubeFragment.java
package androidsample.example.com.fragments1;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerFragment;
public class YouTubeFragment extends YouTubePlayerFragment implements YouTubePlayer.OnInitializedListener {
// TODO: Rename and change types and number of parameters
public static YouTubeFragment newInstance() {
YouTubeFragment fragment = new YouTubeFragment();
return fragment;
}
private void init(){
initialize(DeveloperKey.DEVELOPER_KEY, this);
}
public YouTubeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.activity_main, container, false);
YouTubeFragment ytf = newInstance();
ytf.init();
//inside fragment use getFragmentManager instead of getFragmentSupportManager
getFragmentManager().beginTransaction()
.add(R.id.youTubePlayer, ytf)
.commit();
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.cueVideo("nCgQDjiotG0");
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Toast.makeText(getActivity(), "Failured to Initialize!", Toast.LENGTH_LONG).show();
}
}
MainActivity.java
package androidsample.example.com.fragments1;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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;
}
return super.onOptionsItemSelected(item);
}
}
activity_main.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">
<fragment
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:id="#+id/youTubePlayer"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
I don't think you need to create a newInstance(). The instance is created in your xml. And when you are in onCreateView that is a specific instance already.
So you should be able to replace these lines
YouTubeFragment ytf = newInstance();
ytf.init();
With
this.init();
Or more simply
init();
With some help, I have a working version of this (problems with target SDK 21, using 19):
YouTubeFailureRecoveryActivity.java
package androidsample.example.com.fragments2;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerFragment;
public class YouTubeFailureRecoveryActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener{
private static final int RECOVERY_DIALOG_REQUEST = 1;
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
//String errorMessage = String.format(getString(R.string.error_player), errorReason.toString());
String errorMessage = "custom ERror MessAgE";
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider arg0, YouTubePlayer player,
boolean wasRestored) {
// TODO Auto-generated method stub
if (!wasRestored) {
player.cueVideo("nCgQDjiotG0");
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
// TODO Auto-generated method stub
return (YouTubePlayerFragment) getFragmentManager().findFragmentById(
R.id.youtube_fragment);
}
}
MainActivity.java
package androidsample.example.com.fragments2;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.youtube.player.YouTubePlayerFragment;
public class MainActivity extends YouTubeFailureRecoveryActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YouTubePlayerFragment youTubePlayerFragment = (YouTubePlayerFragment) getFragmentManager()
.findFragmentById(R.id.youtube_fragment);
youTubePlayerFragment.initialize(DeveloperKey.DEVELOPER_KEY, this);
}
#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;
}
return super.onOptionsItemSelected(item);
}
}
activity_main.xml
<RelativeLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<fragment
android:id="#+id/youtube_fragment"
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
I am trying to make an application on Android with a ViewPager filled with 2 Fragments as a start and a NavigationDrawer to have a side menu and be able to navigate between all Fragments.
But the method "OnClickListener" overloaded for the NavigationDrawer does not respond when the OnClick event is done. I have already tried to change the XML parameters of the drawer items and the list but no changes appears.
Please if some have a few minutes to check that, thanks a lot
MainActivity.java
public class MainActivity extends FragmentActivity {
private String[] drawerItemsList;
private ListView myDrawer;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout drawerLayout;
private ViewPager pager;
private FragmentManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pager = (ViewPager) findViewById(R.id.viewPager);
manager = getSupportFragmentManager();
pager.setAdapter(new MyPagerAdapter(manager));
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerItemsList = getResources().getStringArray(R.array.items);
myDrawer = (ListView) findViewById(R.id.my_drawer);
myDrawer.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_item, drawerItemsList));
myDrawer.setOnItemClickListener(new MyDrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
R.drawable.ic_launcher, R.string.open, R.string.close) {
public void onDrawerClosed(View view) {
getActionBar().setTitle("Appli");
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(R.string.menu);
invalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(mDrawerToggle);
}
private class MyDrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> adapter, View v, int pos, long id) {
displayView(pos);
}
private void displayView(int position) {
pager.setCurrentItem(position);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#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;
}
}
activity_main.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/my_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#333"
android:divider="#AAA"
android:dividerHeight="1dp"/>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="10dp" />
</android.support.v4.widget.DrawerLayout>
And the last file
MyPagerAdapter.java
package com.example.test;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.view.View;
public class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(android.support.v4.app.FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return ArtistFragment.newInstance();
case 1: return AlbumFragment.newInstance();
default: return ArtistFragment.newInstance();
}
}
#Override
public int getCount() {
return 3;
}
}
Please check the navigation drawer menu implementation from the sample app in developers guide.
http://developer.android.com/training/implementing-navigation/index.html