I found a tab navigation snippet online and I wonder how to add multiple fragment to it.
I would like to make it work that way:
If i choose first position in menu, it will open fragment_one.xml.
If i choose second position in menu, it will open fragment_two.xml.
Currently, I have only 1 fragment and I dont know how add more.
package com.example.myapp;
import java.util.Locale;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
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;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "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() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_omnie, container, false);
return rootView;
}
}
}
Well you need to create 3 diffrent fragments Like your "PlaceholderFragment"
and In SectionPagerAdapter
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position)
{
case 0: return PlaceholderFragment.newInstance(position + 1);
case 1: return FirstFragment(position + 1);
case n: return nthFragment(position + 1);
}
}
#Override
public int getCount() {
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;
}
}
or take a look at this tutorial
http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/
Related
I need to pass the String data to tab layout. i'm already pass the data from adapter to fragments in Tab layout. But my problem is I cannot to pass that data from activity to Adapter java class. I need to pass the data to more than one fragment. how can i do this?
Main Activity Code
package com.example.tablay;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import com.google.android.material.tabs.TabLayout;
import java.util.List;
import java.util.Stack;
public class MainActivity extends AppCompatActivity {
private ViewPager pager;
private TabLayout tabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pager=(ViewPager) findViewById(R.id.pager);
tabs=(TabLayout) findViewById(R.id.tabs);
pager.setAdapter(new TabFragmentPagerAdapter(getSupportFragmentManager()));
tabs.setupWithViewPager(pager);
tabs.setTabGravity(TabLayout.GRAVITY_FILL);
}
}
Page Adapter Code :
package com.example.tablay;
import android.os.Bundle;
import android.provider.ContactsContract;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import java.util.Date;
import java.util.List;
public class TabFragmentPagerAdapter extends FragmentPagerAdapter {
String[] title = new String[]{
"Tab 1", "Tab 2", "Tab 3"
};
public TabFragmentPagerAdapter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
Fragment fragment=null;
switch (position){
case 0:
tab1Fragment tab1Fragment=new tab1Fragment();
Bundle bundle = new Bundle();
bundle.putString("edttext", "data From Activity");
tab1Fragment.setArguments(bundle);
return tab1Fragment;
case 1:
tab2Fragment tab2Fragment=new tab2Fragment();
bundle = new Bundle();
bundle.putString("edttext1", "data From Activity1");
tab2Fragment.setArguments(bundle);
return tab2Fragment;
case 2:
tab3Fragment tab3Fragment=new tab3Fragment();
return tab3Fragment;
default:
fragment=null;
break;
}
return fragment;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return title[position];
}
#Override
public int getCount() {
return title.length;
}
}
Fragment Code:
package com.example.tablay;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class tab1Fragment extends Fragment {
public tab1Fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_tab1, container, false);
TextView tes=(TextView) view.findViewById(R.id.testtab1);
String strtext = getArguments().getString("edttext");
tes.setText(strtext);
return view;
}
}
I need to pass the String data to tab layout. i'm already pass the data from adapter to fragments in Tab layout. But my problem is I cannot to pass that data from activity to Adapter java class. I need to pass the data to more than one fragment. how can i do this?
You can pass data from activity to the adapter by constructor like this :
public class MainActivity extends AppCompatActivity {
private ViewPager pager;
private TabLayout tabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pager=(ViewPager) findViewById(R.id.pager);
tabs=(TabLayout) findViewById(R.id.tabs);
pager.setAdapter(new TabFragmentPagerAdapter(getSupportFragmentManager(),ActivityStringData));
tabs.setupWithViewPager(pager);
tabs.setTabGravity(TabLayout.GRAVITY_FILL);
}
to
public class TabFragmentPagerAdapter extends FragmentPagerAdapter {
String[] title = new String[]{
"Tab 1", "Tab 2", "Tab 3"
};
String data=null;
public TabFragmentPagerAdapter(#NonNull FragmentManager fm,String activityData) {
super(fm);
this.data=activityData
}
#NonNull
#Override
public Fragment getItem(int position) {
Fragment fragment=null;
switch (position){
case 0:
tab1Fragment tab1Fragment=new tab1Fragment();
Bundle bundle = new Bundle();
bundle.putString("edttext", "data From Activity");
tab1Fragment.setArguments(bundle);
return tab1Fragment;
case 1:
tab2Fragment tab2Fragment=new tab2Fragment();
bundle = new Bundle();
bundle.putString("edttext1", "data From Activity1");
tab2Fragment.setArguments(bundle);
return tab2Fragment;
case 2:
tab3Fragment tab3Fragment=new tab3Fragment();
return tab3Fragment;
default:
fragment=null;
break;
}
return fragment;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return title[position];
}
#Override
public int getCount() {
return title.length;
}
}
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) {
}
}
Android Studio - Why WebView Doesn't Load Web URL
-------------------------------My MainActivity.java-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
package com.spgisslive;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
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.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import static com.spgisslive.R.id.webview;
public class MainActivity extends AppCompatActivity {
/**
* 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.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
private WebView mWebView;
private ViewPager mViewPager;
#Override
protected 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 activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* 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;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
View rootView = inflater.inflate(R.layout.fragment_sub_page01, container, false);
return rootView;
}
else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
View rootView = inflater.inflate(R.layout.fragment_sub_page02, container, false);
return rootView;
}
else if (getArguments().getInt(ARG_SECTION_NUMBER) == 3) {
View rootView = inflater.inflate(R.layout.fragment_sub_page03, container, false);
return rootView;
}
else
{
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
/**
* 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 PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Page 01";
case 1:
return "Page 02";
case 2:
return "SECTION 3";
}
return null;
}
}
}
Sorry I can't speak well. Thank you very much.
Try to load WebView with URL in onCreateView() with check first section case from PlaceholderFragment as below :
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
View rootView = inflater.inflate(R.layout.fragment_sub_page01, container, false);
mWebView = (WebView) rootView.findViewById(R.id.webview);
mWebView.loadUrl("http://www.google.com")
return rootView;
}
Another way to achieve using each Fragment class :
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if(position==0){
return SubPage01.newInstance(position + 1);
}else if(position==1){
return SubPage02.newInstance(position + 1);
}else{
return SubPage03.newInstance(position + 1);
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Page 01";
case 1:
return "Page 02";
case 2:
return "SECTION 3";
}
return null;
}
}
I've created a new activity with swipe views, and added some code.
I have now two swipeable pages, but with the same content, how can i change the content of the second swipe page.
Do I have to create a new activity or just to redirect it to another xml?
import java.util.Locale;
import android.graphics.Bitmap;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
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.ImageView;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
public class ListItemClicked extends ActionBarActivity {
static Bundle extras;
SectionsPagerAdapter mSectionsPagerAdapter;
static ImageLoader imageLoader;
static DisplayImageOptions options;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item_clicked);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
extras = getIntent().getExtras();
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
//Setup the ImageLoader, we'll use this to display our images
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
//Setup options for ImageLoader so it will handle caching for us.
options = new DisplayImageOptions.Builder()
.cacheInMemory()
.cacheOnDisc()
.build();
}
#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_activity2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section4).toUpperCase(l);
case 1:
return getString(R.string.title_section5).toUpperCase(l);
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "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() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_list_item_clicked, container, false);
TextView pDate = (TextView) rootView.findViewById(R.id.textView);
pDate.setText( extras.getString("pdate") );
TextView ptitle = (TextView) rootView.findViewById(R.id.section_label);
ptitle.setText(extras.getString("pname"));
TextView pnText = (TextView) rootView.findViewById(R.id.textView2);
pnText.setText( extras.getString("pText"));
//Setup a listener we can use to swtich from the loading indicator to the Image once it's ready
ImageLoadingListener listener = new ImageLoadingListener(){
#Override
public void onLoadingStarted(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingCancelled(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
// i/ndicator.setVisibility(View.INVISIBLE);
// iconImg.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
// TODO Auto-generated method stub
}
};
//Load the image and use our options so caching is handled.
final ImageView iconImg = (ImageView) rootView.findViewById(R.id.imageView);
imageLoader.displayImage( extras.getString("pImage"), iconImg, options, listener);
return rootView;
}
}
}
thanks!
based on the page number you get from Placeholder Fragment you can set the new content
on your PlaceholderFragment class you can get current page position passed from newInstance method.after that, you can change your fragment content according page section number
There are many ways to do this. You don't have to create another Activity.
Below is a simple way, it rewrites your PlaceholderFragment and make it return different view in different position on onCreateView.
public static class PlaceholderFragment extends Fragment {
private int position;
public static PlaceholderFragment newInstance(int sectionNumber) {
return new PlaceholderFragment(sectionNumber);
}
public PlaceholderFragment(int sectionNumber) {
this.position = sectionNumber;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView;
switch(position){
case 1:
rootView = inflater.inflate(..);
//init view widget.
break;
case 2:
rootView = inflater.inflate(..);
//init view widget.
break;
}
return rootView;
}
}
I am making some android apps with viewpager in fragment. It shows tabs correct, but I can't see any content in my code. I trying to find and search in stackoverflow and google but I don't know why this code is not working. The code looks strange and i am very sorry about that. I am a first quesiton on here. Thx to help me :-)
This is MainActivity.java
package com.yeungnam.food;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.Fragment;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
CustomDrawerAdapter adapter;
List<DrawerItem> dataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing
dataList = new ArrayList<DrawerItem>();
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
/* mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START); */
dataList.add(new DrawerItem(true));
dataList.add(new DrawerItem("Message", R.drawable.ic_action_camera));
dataList.add(new DrawerItem("Likes", R.drawable.ic_action_cloud));
dataList.add(new DrawerItem("Games", R.drawable.ic_action_email));
adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,
dataList);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
SelectItem(1);
}
}
public void SelectItem(int possition) {
Fragment fragment = null;
Bundle args = new Bundle();
switch (possition) {
case 1:
fragment = new FragmentFood();
/* args.putString(FragmentFood.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentFood.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID()); */
break;
case 2:
fragment = new FragmentFood();
/* args.putString(FragmentFood.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentFood.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID()); */
break;
case 3:
fragment = new FragmentFood();
/* args.putString(FragmentFood.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentFood.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID()); */
break;
default:
break;
}
fragment.setArguments(args);
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment)
.commit();
mDrawerList.setItemChecked(possition, true);
setTitle(dataList.get(possition).getItemName());
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return false;
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if(dataList.get(position).isFirst == false)
SelectItem(position);
}
}
#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);
} */
}
This is FragmentFood.java
package com.yeungnam.food;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.astuetz.PagerSlidingTabStrip;
public class FragmentFood extends Fragment {
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private FoodAdapter adapter;
public FragmentFood() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_food, container,
false);
tabs = (PagerSlidingTabStrip) view.findViewById(R.id.tabs);
pager = (ViewPager) view.findViewById(R.id.pager);
adapter = new FoodAdapter(getActivity());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
return view;
}
public class FoodAdapter extends PagerAdapter {
private final String[] TITLES = { "breafkast", "lunch", "dinner" };
private LayoutInflater mInflater;
public FoodAdapter(Context c) {
super(); mInflater = LayoutInflater.from(c);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Object instantiateItem(ViewGroup pager, int position) {
// looks a little bit messy here
TextView v = new TextView(getActivity());
v.setBackgroundResource(R.color.background_window);
v.setText("PAGE " + (position + 1));
final int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, getResources()
.getDisplayMetrics());
v.setPadding(padding, padding, padding, padding);
v.setGravity(Gravity.CENTER);
pager.addView(v, 0);
return v;
}
#Override
public void destroyItem(ViewGroup container, int position, Object view) {
container.removeView((View) view);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
}
}
I also encountered a similar problem,but i use FragmentAdapter. you can refer to the following:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_first_main, container, false);
textViewMesuemInfo = (TextView) view.findViewById(R.id.textViewMesuemInfo);
textViewOpenInfo = (TextView) view.findViewById(R.id.textViewOpenInfo);
fragmentAdapter = new IntroPagerAdapter(**getChildFragmentManager()**);
sliViewPager = (ViewPager) view.findViewById(R.id.viewPagerMain);
sliViewPager.setOnPageChangeListener(pagerChangeListener);
sliViewPager.setAdapter(fragmentAdapter);
sliViewPager.setCurrentItem(0);
return view;
}
private class IntroPagerAdapter extends FragmentPagerAdapter {
public IntroPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 4;
}
#Override
public Fragment getItem(int position) {
Log.i("position=",position+"");
switch (position) {
case 0:
return new IntroFragment().setLayout(R.layout.fragment_colckbuild);
case 1:
return new IntroFragment().setLayout(R.layout.fragment_playclock);
case 2:
return new IntroFragment().setLayout(R.layout.fragment_measureinfo);
case 3:
return new IntroFragment().setLayout(R.layout.fragment_playclock);
default:
return null;
}
}