First of all, I'm a beginner in Android programming. What I'm trying to do is to program three Tabs with each a ListView inside (you know it from e.g. WhatsApp). Android Studio makes it easy to automatically create a Tabbed Activity. So the question is: how can I implement a ListView for each Tab?
Actually there is a nice tutorial on http://www.androidhive.info/2012/05/android-combining-tab-layout-and-list-view/ which uses TabActivity. However this method is deprecated and Fragments should be used instead. I have extended main_fragment.xml (which was created by Android Studio) with a ListView. But what is the correct way to set the corresponding list adapters and especially where to set them? Setting them like ListView list_all = (ListView) findViewById(R.id.listViewAll) in onCreate() does not work because of a null object reference error. Also I didn't find out how to use the rootView which is returned by onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) So how can I solve this problem?
main_fragment.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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:background="#color/colorAccent"
android:paddingTop="#dimen/activity_vertical_margin">
<ListView
android:id="#+id/listViewAll"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
</RelativeLayout>
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:background="#color/white"
tools:context="de.url.members">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:background="#color/bg_login_dark"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/bg_login_dark"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
app:tabMode="fixed"
android:fillViewport="false" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
main.java:
public class main 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;
// The {#link ViewPager} that will host the section contents.
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// 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);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// action here
}
});
}
#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_members, 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.logout) {
//action here
}
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) {
int sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);//INDEX of selected TAB
View rootView;
if (sectionNumber == 1){
rootView = inflater.inflate(R.layout.main_fragment, container, false);
}else if (sectionNumber == 2){
rootView = inflater.inflate(R.layout.main_fragment, container, false);
}else if (sectionNumber == 3){
rootView = inflater.inflate(R.layout.main_fragment, container, false);
}else{
rootView = inflater.inflate(R.layout.main_fragment, 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 getResources().getString(R.string.title_section1);
case 1:
return getResources().getString(R.string.title_section2);
case 2:
return getResources().getString(R.string.title_section3);
}
return null;
}
}
}
If you want to use Listing with tablayout and viewpager try this way it will work for you
public class MainActivity extends AppCompatActivity {
private static Toolbar toolbar;
private static ViewPager viewPager;
private static TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewPager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);//setting tab over viewpager
//Implementing tab selected listener over tablayout
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());//setting current selected item over viewpager
switch (tab.getPosition()) {
case 0:
Log.e("TAG","TAB1");
break;
case 1:
Log.e("TAG","TAB2");
break;
case 2:
Log.e("TAG","TAB3");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
//Setting View Pager
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new DummyFragment("ANDROID"), "ANDROID");
adapter.addFrag(new DummyFragment("iOS"), "iOS");
adapter.addFrag(new DummyFragment("WINDOWS"), "WINDOWS");
viewPager.setAdapter(adapter);
}
//View Pager fragments setting adapter class
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();//fragment arraylist
private final List<String> mFragmentTitleList = new ArrayList<>();//title arraylist
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
//adding fragments and title method
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
For more see android-material-design-tabs-using-tablayout
OR
Check this http://www.tutorialsbuzz.com/2015/10/Android-Sliding-TabLayout-ListView-WhatsApp.html
And check this https://github.com/codepath/android_guides/wiki/Handling-Scrolls-with-CoordinatorLayout
OUTPUT
I will explain what you have to do to put a ListView on one of the fragments. (Sorry if I write a bad English)
You should put your listView view on the xml witch is displayed by one of your fragments. In the code that you have post the layout witch fragment displays is R.layout.main_fragment
Then on the fragment you have to declare your ListView:
ListView list_all = (ListView) rootView.findViewById(R.id.listViewAll);
You have to create a ListView adapter, an object class and some other files, you can use the tutorial witch you have post.
Link
Then write your code to set an Adapter to this ListView after the rootView is assigned on the fragment:
if (sectionNumber == 1){
rootView = inflater.inflate(R.layout.main_fragment, container, false);
}else if (sectionNumber == 2){
rootView = inflater.inflate(R.layout.main_fragment, container, false);
}else if (sectionNumber == 3){
rootView = inflater.inflate(R.layout.main_fragment, container, false);
}else{
rootView = inflater.inflate(R.layout.main_fragment, container, false);
}
ArrayList<Object> arrayListOfObjects = new ArrayList<>();
arrayListOfObjects.add(new Object(...));
MyAdapter adapter = new MyAdapter(arrayListOfObjects);
list_all.setListAdapter(adapter);
I have solved it now by simply editing the getItem() method of public class SectionsPagerAdapter in main.java.
Just return a default ListFragment instead of the PlaceholderFragment.
Interesting note: Returning the same ListFragment object for all tabs leads to an error.
main.java:
public class MainActivity extends AppCompatActivity {
private ArrayAdapter<String> adapter;
private ListFragment contacts1 = new ListFragment();
private ListFragment contacts2 = new ListFragment();
private ListFragment contacts3 = new ListFragment();
List<String> words = new ArrayList<String>();
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// 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);
words.add("Hello");
words.add("World");
words.add("!");
adapter = new ArrayAdapter<String>(this,R.layout.item,words);
contacts1.setListAdapter(adapter);
contacts2.setListAdapter(adapter);
contacts3.setListAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Update List", Snackbar.LENGTH_LONG).setAction("Action", null).show();
words.add("New Item");
adapter.notifyDataSetInvalidated();
}
});
}
#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);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public ListFragment getItem(int position) {
if (position == 0){
return contacts1;
}else if (position == 1){
return contacts2;
}else{
return contacts3;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
}
Related
Before put -1 in the score, I tell you that I read all, I repeat ALL the answers about this problem in this site and even in other site, so, if you can give me an hand.
Hi guys, i'm having this problem with my application and I'm wasting too much time in this.
My application is composed by 4 fragments, and I'm having problems with the two with the recyclerview (in fragment_fibra and fragment_adsl).
main.java
public class main extends AppCompatActivity implements
OnFragmentInteractionListener //I HAVE a problem with
OnFragmentInteractionListener {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = findViewById(R.id.tabs);
// tabLayout.setupWithViewPager(mViewPager); //aggiunta dopo
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(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_homepage, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
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) {
View rootView = null;
switch(getArguments().getInt(ARG_SECTION_NUMBER))
{
case 1:
rootView = inflater.inflate(R.layout.fragment_homepage, container, false);
break;
case 2:
rootView = inflater.inflate(R.layout.fragment_fibra, container, false);
break;
case 3:
rootView = inflater.inflate(R.layout.fragment_adsl, container, false);
break;
case 4:
rootView = inflater.inflate(R.layout.fragment_aiuto, container, false);
break;
}
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return PlaceholderFragment.newInstance(1);
case 1:
return PlaceholderFragment.newInstance(2);
case 2:
return PlaceholderFragment.newInstance(3);
case 3:
return PlaceholderFragment.newInstance(4);
default: return PlaceholderFragment.newInstance(1);
// here i have other problems, so like this the app still work, but if i change something it crash (and I know it's wrong like this)
}
//return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 4;
}
}
}
activity_homepage.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".homepage">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_weight="1"
android:background="#color/colorPrimaryDark"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/PopupOverlay"
app:title="#string/app_name">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary">
<android.support.design.widget.TabItem
android:id="#+id/tabItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_1" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_2" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_3" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_4" />
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
homepage.java (first fragment)
public class homepage extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_homepage, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
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) {
View rootView = null;
switch(getArguments().getInt(ARG_SECTION_NUMBER))
{
case 1:
rootView = inflater.inflate(R.layout.fragment_homepage, container, false);
break;
case 2:
rootView = inflater.inflate(R.layout.fragment_fibra, container, false);
break;
case 3:
rootView = inflater.inflate(R.layout.fragment_adsl, container, false);
break;
case 4:
rootView = inflater.inflate(R.layout.fragment_aiuto, container, false);
break;
}
return rootView;
}
}
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 4;
}
}
}
fragment_fibra.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fibra"
android:background="#EFEFEF">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:drawablePadding="22dp"
android:gravity="center"
android:hint="#string/cercasugg"
android:textColor="#000000"
android:padding="16dp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/ListaFibra"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
fibra.java (second fragment)
public class fibra extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private OnFragmentInteractionListener mListener;
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
public fibra() {
}
public static fibra newInstance(String param1, String param2) {
fibra fragment = new fibra();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.fragment_fibra, container, false);
recyclerView = V.findViewById(R.id.ListaFibra);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
List<String> input = new ArrayList<>();
for (int i = 0; i < 100; i++) {
input.add("Test" + i);
}
mAdapter = new adFibra(input);
recyclerView.setAdapter(mAdapter);
return V;
/*View rootView = inflater.inflate(R.layout.fragment_fibra, container, false);
RecyclerView recyclerView = rootView.findViewById(R.id.ListaFibra);
recyclerView.setHasFixedSize(true); //per migliorare performance
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(llm);
adFibra adapter = new adFibra(new String[]{"Example One"});
recyclerView.setAdapter(adapter);
return rootView;*/
//return inflater.inflate(R.layout.fragment_fibra, container, false);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
try to put
recyclerView.setLayoutManager(llm);
before
recyclerView.setAdapter(adapter);
so it will be
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(llm);
MyAdapter adapter = new MyAdapter(new String[]{"Example One", "Example Two", "Example Three", "Example Four", "Example Five" , "Example Six" , "Example Seven"});
recyclerView.setAdapter(adapter);
Happy Coding :D
Are you sure you actually call the fibra fragment?
You are creating a PlaceHolderFragment every time and just inflating different layouts. You don't actually create a fibra fragment, so the recycler is not populated, thus the message.
In your SectionsPagerAdapter, in method getItem, return the fragment instance that corresponds to the position.
For example:
switch (position) {
case 0:
return homepage.newInstance();
case 1:
return fibra.newInstance();
case 2:
return adsl.newInstance();
case 3:
return aiuto.newInstance();
default:
return homepage.newInstance();
}
Remove the PlaceHolderFragment from your main activity. Also homepage is not a fragment, but an activity. All your fragments should look like fibra.
And implement all the fragment interfaces like:
implements fibra.OnFragmentInteractionListener
and create a method to implement it:
#Override
public void onFragmentInteraction(Uri uri) {
// your code here...
}
The problem I have is the List View does not show up on my fragment. I tried different suggestions from the internet, but it doesn't work.
Here is my code for MainMenuFragment.java
package project.foodkit.tabbed_activity;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.lang.reflect.Array;
public class MainMenuFragment extends Fragment {
private ArrayAdapter<String> adapter;
private ListView listView;
public MainMenuFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main_menu, container, false);
//array holding data->to be changed to list data from database
String[] food = {"pizza", "burger", "chocolate", "ice-cream", "banana", "apple"};
listView = (ListView) view.findViewById(R.id.mainMenu);
adapter = new ArrayAdapter<String>(
getActivity(),
android.R.layout.simple_list_item_1,
food
);
listView.setAdapter(adapter);
// Inflate the layout for this fragment
return view;
}
and the code for fragment_main_menu.xml
<FrameLayout 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"
tools:context="project.foodkit.tabbed_activity.MainMenuFragment">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/mainMenu" />
</FrameLayout>
and the mainActivity.java
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;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// 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);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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) {
View rootView = inflater.inflate(R.layout.fragment_main_menu, 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 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Shopping Cart";
case 1:
return "Existing ingredients";
}
return null;
}
}
}
Here you used PlaceholderFragement not your MainMenuFragment
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1); <-- here is the problem
}
you should use your fragment instead. like
#Override
public Fragment getItem(int position) {
return new MainMenuFragment();
}
There is no issue in setting listview inside MainMenuFragment();
You have wrong code inside SectionsPagerAdapter
replace return PlaceholderFragment.newInstance(position + 1); with return new MainMenuFragment();
remove PlaceholderFragment from MainActivity.class
I set up a fragment which looks like this:
The EditText("5") has the id et_input. Now I want to interact with my EditText but it doesn't work.
MainActivity.java
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;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// 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);
getSupportActionBar().hide();
}
/**
* 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) {
switch (getArguments().getInt(ARG_SECTION_NUMBER) - 1) {
case 1:
return inflater.inflate(R.layout.fragment_roman_numbers, container, false);
case 2:
return inflater.inflate(R.layout.fragment_binary_numbers, container, false);
default:
return inflater.inflate(R.layout.fragment_main, container, false);
}
}
}
/**
* 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) {
if(position == 0) {
return main.newInstance();
} else if(position == 1) {
return roman_numbers.newInstance();
} else if(position == 2) {
return binary_numbers.newInstance();
}
throw new IllegalArgumentException("There is no fragment for position [" + position + "]");
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.fragment_home);
case 1:
return getString(R.string.fragment_roman_numbers);
case 2:
return getString(R.string.fragment_binary_numbers);
}
return null;
}
}
}
binary_numbers.java
public class binary_numbers extends Fragment {
public binary_numbers() {
// Required empty public constructor
}
public static binary_numbers newInstance() {
binary_numbers fragment = new binary_numbers();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_binary_numbers, container, false);
EditText et_input = (EditText) view.findViewById(R.id.et_input);
et_input.setText("TEST");
// Inflate the layout for this fragment
return view;
}
}
roman_numbers.java and main.java look exactly the same except for binary_numbers being replaced with their names.
fragement_binary_numbers.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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.ngtnttnmnt.xtool.MainActivity$PlaceholderFragment">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/et_input"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:hint="#string/input_hint"
android:gravity="center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:id="#+id/tv_output"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textSize="40dp"
android:gravity="center" />
fragement_roman_numbers.xml looks exactly the same and fragement_main.xml has two TextView's
Should be
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_binary_numbers, container, false);
EditText et_input = (EditText) view.findViewById(R.id.et_input);
et_input.setText("TEST");
// Inflate the layout for this fragment
return view;
}
EDIT:
As I said, you're showing a different fragment. In reality, you are showing the PlaceholderFragment created within your SectionsPagerAdapter, which just selects the binary_number layout when it's inflated, but you're not actually showing a binary_numbers fragment.
Your code should be the following:
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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);
getSupportActionBar().hide();
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if(position == 0) {
return home.newInstance();
} else if(position == 1) {
return roman_numbers.newInstance();
} else if(position == 2) {
return binary_numbers.newInstance();
}
throw new IllegalArgumentException("There is no fragment for position [" + position + "]");
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.fragment_home);
case 1:
return getString(R.string.fragment_roman_numbers);
case 2:
return getString(R.string.fragment_binary_numbers);
}
throw new IllegalArgumentException("There is no fragment for position [" + position + "]");
}
}
}
Please note the complete removal of the PlaceholderFragment class, because you won't need it, ever.
EDIT: also add
public class home extends Fragment {
public static home newInstance() {
return new home();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
}
EDIT:
Also modify your binary_numbers class like so
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import com.ngtnttnmnt.xtool.InputFilterMinMax;
import com.ngtnttnmnt.xtool.R;
public class binary_numbers extends Fragment {
public binary_numbers() {
// Required empty public constructor
}
public static binary_numbers newInstance() {
binary_numbers fragment = new binary_numbers();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_binary_numbers, container, false);
EditText et_input = (EditText) view.findViewById(R.id.et_input);
et_input.setText("TEST");
// Inflate the layout for this fragment
return view;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private PlaceholderFragment mPlaceholderFragment;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if(mPlaceholderFragment == null){
mPlaceholderFragment = PlaceholderFragment.newInstance(position + 1);
}
return mPlaceholderFragment;
}
It should be like this
I would like to give my tabs names in my main.xml file. After a lot of searching i still havent found a working solution. if someone can provide a working solution/suggestion for this, all be it programatically or with xml i would be very thankful.
main_activity.java
public class MainActivity extends AppCompatActivity {
private Toolbar mToolbar;
private TabLayout mTabLayout;
private ViewPager mPager;
private MyPagerAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new MyPagerAdapter(getSupportFragmentManager());
mToolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(mToolbar);
mTabLayout = (TabLayout) findViewById(R.id.tab_layout);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mTabLayout.setTabsFromPagerAdapter(mAdapter);
mTabLayout.setupWithViewPager(mPager);
mPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
}
#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);
}
public static class MyFragment extends Fragment {
public static final java.lang.String ARG_PAGE = "arg_page";
public MyFragment() {
}
public static MyFragment newInstance(int pageNumber) {
MyFragment myFragment = new MyFragment();
Bundle arguments = new Bundle();
arguments.putInt(ARG_PAGE, pageNumber + 1);
myFragment.setArguments(arguments);
return myFragment;
}
}
}
class MyPagerAdapter extends FragmentStatePagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = MainActivity.MyFragment.newInstance(position); //FRAGMENT fragment;
switch (position) {
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
default:
break;
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
return "Fragment " + (position + 1);
}
}
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.lvlastuin.tabnav.MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
app:tabGravity="fill"
app:tabMaxWidth="0dp"
app:tabTextAppearance="#style/TextAppearance.Design.Tab"
app:tabSelectedTextColor="#color/colorAccent"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
over ride this method in your pager adapter
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "tab1 name";
case 1:
return "tab2 name";
}
return null;
}
In your MyPagerAdapter class you have a
#Override
public CharSequence getPageTitle(int position) {
return "Fragment " + (position + 1);
}
Which is generally where you set the names of the tabs. So when you instantiate it, just pass a collection of names you'd like to name the tabs
I am trying to open a fragment, when a dialog is clicked inside another fragment. I am using ActionBarSherlock with Tab. My fragment is attached in the view pager. I have almost done the job. But I can't replace a new fragment inside a view pager. I got an error. I read the thread here. The solution isn't clear.
Error:
10-18 21:34:40.379: E/AndroidRuntime(19618): FATAL EXCEPTION: main
10-18 21:34:40.379: E/AndroidRuntime(19618):
java.lang.IllegalArgumentException: No view found for id 0x7f040032
(com.example.actionbartestwithsherlock:id/pager) for fragment
AllContactsFragment{41fd4ba0 #0 id=0x7f040032} 10-18 21:34:40.379:
E/AndroidRuntime(19618): at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:903)
I have three fragment associates with pager named FragmentTab1,FragmentTab2 & FragmentTab3.
My MainActivity & FragmentAdapter looks like below:
public class MainActivity extends SherlockFragmentActivity {
ActionBar.Tab Tab1, Tab2, Tab3, Tab4;
private Context context = this;
// view pager
// Declare Variables
ActionBar actionBar;
ViewPager mPager;
Tab tab;
FragmentAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// set application in portrait mode
ActivityHelper.initialize(this);
actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Locate ViewPager in activity_main.xml
mPager = (ViewPager) findViewById(R.id.pager);
// add an adapter to pager
mPager.setAdapter(new FragmentAdapter(getSupportFragmentManager(),
mPager, actionBar));
addActionBarTabs();
}
private void addActionBarTabs() {
String[] tabs = { "Tab 1", "Tab 2", "Tab 3" };
for (String tabTitle : tabs) {
ActionBar.Tab tab = actionBar.newTab().setText(tabTitle)
.setTabListener(tabListener);
actionBar.addTab(tab);
}
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
private ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
mPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
};
class FragmentAdapter extends FragmentPagerAdapter implements
ViewPager.OnPageChangeListener {
private ViewPager mViewPager;
final int TOTAL_PAGES = 3;
public FragmentAdapter(FragmentManager fm, ViewPager pager,
ActionBar actionBar) {
super(fm);
this.mViewPager = pager;
this.mViewPager.setOnPageChangeListener(this);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return FragmentTab1.newInstance();
case 1:
return FragmentTab2.newInstance();
case 2:
return FragmentTab3.newInstance();
default:
throw new IllegalArgumentException(
"The item position should be less or equal to:"
+ TOTAL_PAGES);
}
}
#Override
public int getCount() {
return TOTAL_PAGES;
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
}
}
Now, Inside my first tab FragmentTab1, I open a customized dialog when a button clicks. I want to replace new fragment AllContactsFragment in FragmentTab1 when the dialog options are selected.
FragmentTab1 fragment class:
public class FragmentTab1 extends SherlockFragment implements OnClickListener {
Button btnTest;
ViewPager pager;
LinearLayout layoutBlockNumbers;
LinearLayout layoutContact, layoutCallLog, layoutSMSLog, layoutManually;
Context context;
CustomizedDialog dialog;
private static final int CONTACT_PICKER_RESULT = 1001;
private static final String DEBUG_TAG = "Contact List";
private static final double RESULT_OK = -1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab1, container,
false);
layoutBlockNumbers = (LinearLayout) rootView
.findViewById(R.id.layoutAddBlockNumbers);
layoutBlockNumbers.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
if (v == layoutCallLog) {
dialog.dismiss();
// want to replace new fragment at position 0 in pager
// problem is here ??? how to open new fragmnet
Fragment allContactsFragment = AllContactsFragment.newInstance();
FragmentTransaction transaction = getChildFragmentManager()
.beginTransaction();
transaction.addToBackStack(null);
transaction.replace(R.id.pager, allContactsFragment).commit();
}
if (v == layoutBlockNumbers) {
// open a dialog
showDialog();
} else if (v == layoutContact) {
openContactList();
dialog.dismiss();
} else if (v == layoutSMSLog) {
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
setUserVisibleHint(true);
}
// open a dialog
private void showDialog() {
dialog = new CustomizedDialog(getActivity());
dialog.setContentView(R.layout.dialog_add_number_type);
dialog.setTitle("Add Black List Number");
//initialize all linear layouts in dialog
layoutCallLog = (LinearLayout) dialog.findViewById(R.id.layoutCallLog);
layoutContact = (LinearLayout) dialog.findViewById(R.id.layoutContact);
layoutSMSLog = (LinearLayout) dialog.findViewById(R.id.layoutSMSLog);
layoutManually = (LinearLayout) dialog
.findViewById(R.id.layoutManually);
// add listener to several linear layout
layoutContact.setOnClickListener(this);
layoutCallLog.setOnClickListener(this);
layoutSMSLog.setOnClickListener(this);
layoutManually.setOnClickListener(this);
dialog.show();
}
public static Fragment newInstance() {
Fragment f = new FragmentTab1();
return f;
}
}
activity_main.xml looks like below :
<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.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</android.support.v4.view.ViewPager>
</RelativeLayout>
Can anybody can help me to solve this issue? Sorry for the massive code.
I'm not sure you can do things the way you want to. A ViewPager is not set up the same way a normal container/fragment set up would be. In a ViewPager you're not using fragment transactions to add fragments but rather an adapter that loads instances of fragments from a backing list.
Replacing the fragment would then work as follows:
(1) Create an instance of the fragment you want to add
(2) Add that fragment to the list that is backing your PagerAdapter
(3) Display the new fragment
(4) Remove the old one
The problem with implementing this in your current project is the set up of your adapter. Currently you are using a switch statment that can only return a fixed number of fragments. Your adapter should be set up something like this.
class MyPageAdapter extends FragmentPagerAdapter{
private List<Fragment> fragments
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
Then you can just add a method to your adapter class to add or remove new fragments. If you know the index of the fragment you want to replace accomplishing this should be pretty easy. All you have to do is create a new instance of the contacts fragment, add it to your array or list. This Post explains how a ViewPager handles the adding/removing of new content and how to ensure your new fragment is displayed.
After I read this post I solved the answer.
I just add an ID android:id="#+id/fragmentTabLayout1 to top layout of my fragmenttab1.xml . Then call
new fragment as usual:
Fragment allContactsFragment = AllContactsFragment.newInstance();
FragmentTransaction transaction = getChildFragmentManager()
.beginTransaction();
transaction.addToBackStack(null);
// use this id to replace new fragment
transaction.replace(R.id.fragmentTabLayout1, allContactsFragment).commit();