How to add swiping gesture on fragment TAbHost - android

I want to change tab by swiping on the screen i am creating tabs using fragment tabhost but when i implement swiping feature in my project it doesn't open nested fragment in each tab means i am opening nested child fragment inside each tab.
Please tell me its very important for me.
here is my code.
this my Main activity.
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
public class Home extends FragmentActivity implements OnTabChangeListener,OnPageChangeListener {
private static final String TAB_1_TAG = "tab_1";
private static final String TAB_2_TAG = "tab_2";
private static final String TAB_3_TAG = "tab_3";
private static final String TAB_4_TAG = "tab_4";
private static final String TAB_5_TAG = "tab_5";
private FragmentTabHost mTabHost;
// ViewPager viewPager;
// TabsPagerAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
viewPager =(ViewPager)findViewById(R.id.viewpager);
initView();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
viewPager.setOnPageChangeListener(Home.this);
}
private void initView() {
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
// mTabHost.addTab(mTabHost.newTabSpec(TAB_1_TAG).setIndicator("Talk", getResources().getDrawable(R.drawable.ic_launcher)), TalkContainerFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec(TAB_1_TAG).setIndicator("Talk"), TalkContainerFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec(TAB_2_TAG).setIndicator("Map"), Map_fragment.class, null);
// mTabHost.addTab(mTabHost.newTabSpec(TAB_3_TAG).setIndicator("Go"), GoContainerFragment.class, null);
// mTabHost.addTab(mTabHost.newTabSpec(TAB_4_TAG).setIndicator("Watch"), WatchContainerFragment.class, null);
// mTabHost.addTab(mTabHost.newTabSpec(TAB_5_TAG).setIndicator("More"), MoreContainerFragment.class, null);
/* Increase tab height programatically
* tabs.getTabWidget().getChildAt(1).getLayoutParams().height = 150;
*/
for (int i = 0; i < mTabHost.getTabWidget().getChildCount(); i++) {
final TextView tv = (TextView) mTabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);
if (tv == null)
continue;
else
tv.setTextSize(10);
}
}
#Override
public void onBackPressed() {
boolean isPopFragment = false;
String currentTabTag = mTabHost.getCurrentTabTag();
if (currentTabTag.equals(TAB_1_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_1_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_2_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_2_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_3_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_3_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_4_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_4_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_5_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_5_TAG)).popFragment();
}
if (!isPopFragment) {
finish();
}
}
#Override
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
int pos = this.mTabHost.getCurrentTab();
this.viewPager.setCurrentItem(pos);
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
int pos = this.viewPager.getCurrentItem();
this.mTabHost.setCurrentTab(pos);
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
}
}
This Container fragment class
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
public class BaseContainerFragment extends Fragment {
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.replace(R.id.container_framelayout, fragment);
transaction.commit();
getChildFragmentManager().executePendingTransactions();
}
public boolean popFragment() {
Log.e("test", "pop fragment: " + getChildFragmentManager().getBackStackEntryCount());
boolean isPop = false;
if (getChildFragmentManager().getBackStackEntryCount() > 0) {
isPop = true;
getChildFragmentManager().popBackStack();
}
return isPop;
}
}
Created Container for each TAb
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TalkContainerFragment extends BaseContainerFragment {
private boolean mIsViewInited;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.e("test", "tab 1 oncreateview");
return inflater.inflate(R.layout.container_fragment, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.e("test", "tab 1 container on activity created");
if (!mIsViewInited) {
mIsViewInited = true;
initView();
}
}
TAlk.java file
import java.util.HashSet;
import java.util.Set;
import org.json.JSONObject;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
public class Talk extends Fragment {
/** Define global variables over here */
//private ProgressDialog pDialog;
// StaticApiList sal;
// TalkModelAll tma;
JSONObject myJasonObject = null;
private ListView lv;
// private ArrayList<TalkModelAll> m_ArrayList = null;
//ArrayList<String> stringArrayList = new ArrayList<String>();
// TalkArrayAdapter taa;
Set<String> uniqueValues = new HashSet<String>();
TextView rowTextView = null;
boolean vivek = false;
int postid;
String title;
String thumsrc;
String largeimg;
String excert;
String description;
String cat;
String myUrl;
String jsonString;
int mCurCheckPosition;
String check_state = null;
String ccc;
LinearLayout myLinearLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.talk, null);
Button btn = (Button) rootView.findViewById(R.id.your_btn_id);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Here TalkDetail is name of class that needs to open
TalkDetail talkfragment = new TalkDetail();
// if U need to pass some data
Bundle bundle = new Bundle();
//
// bundle.putString("title", m_ArrayList.get(arg2).title);
// bundle.putString("largeimg", m_ArrayList.get(arg2).largeimg);
// bundle.putString("excert", m_ArrayList.get(arg2).excert);
// bundle.putString("description", m_ArrayList.get(arg2).description);
// bundle.putString("cat", m_ArrayList.get(arg2).cat);
// //bundle.putInt("postid", m_ArrayList.get(arg2).postid);
talkfragment.setArguments(bundle);
((BaseContainerFragment)getParentFragment()).replaceFragment(talkfragment, true);
}
});
return rootView;
}
}
Talkddetail.class
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class TalkDetail extends android.support.v4.app.Fragment {
/* (non-Javadoc)
* #see android.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view=LayoutInflater.from(getActivity()).inflate(R.layout.activity_talk_detail, null);
return view;
}
}

You have to use a ViewPager. Read more at Android Developer website. You can find a lot of custom view pagers on Android Arsenal. This is the current standard, so you should use this over TabHost.

you can have a look at its demo in eclips go to
file->other->android Activity->tabbed activity
or learn the view Fliper from android developer website
package com.example.mystack;
import java.util.Locale;
import android.support.v7.app.ActionBarActivity;
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 ActionBarActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a {#link FragmentPagerAdapter}
* derivative, which will keep every loaded fragment in memory. If this
* becomes too memory intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show FirstFragment
return new TalkContainerFragment(0, "Talk");
case 1: // Fragment # 0 - This will show FirstFragment different title
return new Map_fragment(1, "map");
//Rest of them add here
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A 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";
/**
* Returns a new instance of this fragment for the given section number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
and xml is
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mystack.MainActivity" />
<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.example.mystack.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Use this method in your activity for all fragment trancation
// For the Fragment Replace And AddtobackStack
void replaceFragment(Fragment fragment) {
String backStateName = fragment.getClass().getName();
String fragmentTag = backStateName;
FragmentManager manager = this.getSupportFragmentManager();
boolean fragmentPopped = manager
.popBackStackImmediate(backStateName, 0);
if (!fragmentPopped && manager.findFragmentByTag(fragmentTag) == null) {
// fragment not in back stack, create it.
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.container, fragment, fragmentTag);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(backStateName);
ft.commit();
}
}
and use it like this whenever you need to go for nested fragment from one fragmnet
if (DetailsFragment.this.getActivity() != null
&& DetailsFragment.this.getActivity() instanceof HomeActivity)
((HomeActivity) DetailsFragment.this.getActivity())
.replaceFragment(cartfragment);
in the above suppose i am in details fragment and from here i want to go to cartfragment
then get the activitiy instance and cast it like the above

Related

Unable to distinguish between two fragments with chart click events

I have implemented two pie charts in two different fragments. Whenever I click on a pie chart it will call the second fragments click events on both fragments.
Here is my MainActivity.java code.
package longitude.com.anychart;
import android.content.res.Resources;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentStatePagerAdapter;
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.util.SparseArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.anychart.chart.common.dataentry.DataEntry;
import com.anychart.chart.common.dataentry.ValueDataEntry;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
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}.
*/
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
private AccountDashboardAdapter mSectionsPagerAdapter;
#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.
mViewPager = (ViewPager) findViewById(R.id.container);
//mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
ArrayList<DataEntry> dateData = new ArrayList<>();
dateData.add(new ValueDataEntry("Apples", 123456));
dateData.add(new ValueDataEntry("Pears", 852465));
dateData.add(new ValueDataEntry("Bananas", 753159));
dateData.add(new ValueDataEntry("Grapes", 963215));
dateData.add(new ValueDataEntry("Oranges", 415263));
ArrayList<DataEntry> collectorData = new ArrayList<>();
collectorData.add(new ValueDataEntry("Applessssss", 6371664));
collectorData.add(new ValueDataEntry("Pearsssss", 789622));
collectorData.add(new ValueDataEntry("Bananasssss", 7216301));
collectorData.add(new ValueDataEntry("Grapesssss", 1486621));
collectorData.add(new ValueDataEntry("Orangesssss", 1200000));
HashMap<String, ArrayList<DataEntry>> childData=new LinkedHashMap<>();
childData.put("Apples",collectorData);
childData.put("Pears",collectorData);
childData.put("Bananas",collectorData);
childData.put("Grapes",collectorData);
childData.put("Oranges",collectorData);
childData.put("Applessssss",dateData);
childData.put("Pearsssss",dateData);
childData.put("Bananasssss",dateData);
childData.put("Grapesssss",dateData);
childData.put("Orangesssss",dateData);
mSectionsPagerAdapter = new AccountDashboardAdapter(getResources(), getSupportFragmentManager(), dateData, collectorData, childData);
mViewPager.setOffscreenPageLimit(5);
// Set up the ViewPager with the sections adapter.
mViewPager.setAdapter(mSectionsPagerAdapter);
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, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class AccountDashboardAdapter extends FragmentStatePagerAdapter {
private final List<DataEntry> collectorData;
private final HashMap<String, ArrayList<DataEntry>> childData;
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
List<DataEntry> dateData;
/**
* Create pager adapter
*
* #param resources
* #param fm
* #param data
* #param childData
*/
public AccountDashboardAdapter(final Resources resources, FragmentManager fm, List<DataEntry> data, List<DataEntry> collectorData, HashMap<String, ArrayList<DataEntry>> childData) {
super(fm);
this.dateData = data;
this.collectorData = collectorData;
this.childData = childData;
}
#Override
public Fragment getItem(int position) {
final Fragment result;
switch (position) {
case 0:
// First Fragment of First Tab
//result = new DatewiseAccountDashboardFragment();
result = new fragment1();
Bundle bundle = new Bundle();
bundle.putSerializable("data", (Serializable) dateData);
bundle.putSerializable("childData", childData);
result.setArguments(bundle);
break;
case 1:
// First Fragment of Second Tab
//result = new CollectorwiseAccountDashboardFragment();
result = new fragment2();
Bundle bundle1 = new Bundle();
bundle1.putSerializable("data", (Serializable) collectorData);
bundle1.putSerializable("childData", childData);
result.setArguments(bundle1);
break;
case 2:
// First Fragment of Second Tab
//result = new CollectorwiseAccountDashboardFragment();
result = new fragment1();
Bundle bundle2 = new Bundle();
bundle2.putSerializable("data", (Serializable) dateData);
bundle2.putSerializable("childData", childData);
result.setArguments(bundle2);
break;
default:
result = null;
break;
}
return result;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(final int position) {
switch (position) {
case 0:
return "DATEWISE";
case 1:
return "COLLECTORWISE";
default:
return null;
}
}
/**
* On each Fragment instantiation we are saving the reference of that Fragment in a Map
* It will help us to retrieve the Fragment by position
*
* #param container
* #param position
* #return
*/
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
/**
* Remove the saved reference from our Map on the Fragment destroy
*
* #param container
* #param position
* #param object
*/
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
/**
* Get the Fragment by position
*
* #param position tab position of the fragment
* #return
*/
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
}
My First Fragment1.java code
package longitude.com.anychart;
import android.app.Activity;
import android.content.Intent;
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.Toast;
import com.anychart.APIlib;
import com.anychart.AnyChart;
import com.anychart.AnyChartView;
import com.anychart.chart.common.dataentry.DataEntry;
import com.anychart.chart.common.listener.Event;
import com.anychart.chart.common.listener.ListenersInterface;
import com.anychart.charts.Pie;
import com.anychart.enums.Align;
import com.anychart.enums.LegendLayout;
import java.util.List;
public class Fragment1 extends Fragment {
private AnyChartView anyChartView;
private List<DataEntry> data;
private Pie pie;
public Fragment1() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
data = (List<DataEntry>) getArguments().getSerializable("data");
//childData = (HashMap<String, ArrayList<DataEntry>>) getArguments().getSerializable("childData");
getArguments().remove("data");
getArguments().remove("childData");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
anyChartView = rootView.findViewById(R.id.any_chart_view1);
anyChartView.setProgressBar(rootView.findViewById(R.id.progress_bar1));
showChart(anyChartView, data);
return rootView;
}
private void showChart(AnyChartView anyChartView, List<DataEntry> data) {
APIlib.getInstance().setActiveAnyChartView(anyChartView);
pie = AnyChart.pie();
pie.data(data);
pie.title("1st Anychart Title");
//pie.labels().position("outside");
pie.innerRadius(50);
pie.legend().title().enabled(true);
pie.legend().title(false);
pie.legend()
.position("center-bottom")
.itemsLayout(LegendLayout.HORIZONTAL_EXPANDABLE)
.align(Align.CENTER);
//pie.fill("aquastyle");
pie.labels().format("{%x}\\n{%value}");
anyChartView.setChart(pie);
pie.tooltip(false);
pie.setOnClickListener(new ListenersInterface.OnClickListener(new String[]{"x", "value"}) {
#Override
public void onClick(Event event) {
Toast.makeText(getActivity(), "Fragment1==>" + event.getData().get("x") + ":" + event.getData().get("value"), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
My Second Fragment2.java code
package longitude.com.anychart;
import android.app.Activity;
import android.content.Intent;
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.Button;
import android.widget.Toast;
import com.anychart.APIlib;
import com.anychart.AnyChart;
import com.anychart.AnyChartView;
import com.anychart.chart.common.dataentry.DataEntry;
import com.anychart.chart.common.listener.Event;
import com.anychart.chart.common.listener.ListenersInterface;
import com.anychart.charts.Pie;
import com.anychart.enums.Align;
import com.anychart.enums.LegendLayout;
import java.util.List;
public class Fragment2 extends Fragment {
private AnyChartView anyChartView;
private List<DataEntry> data;
private Pie pie;
public Fragment2() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
data = (List<DataEntry>) getArguments().getSerializable("data");
//childData = (HashMap<String, ArrayList<DataEntry>>) getArguments().getSerializable("childData");
getArguments().remove("data");
getArguments().remove("childData");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
anyChartView = rootView.findViewById(R.id.any_chart_view1);
anyChartView.setProgressBar(rootView.findViewById(R.id.progress_bar1));
showChart(anyChartView, data);
return rootView;
}
private void showChart(AnyChartView anyChartView, List<DataEntry> data) {
APIlib.getInstance().setActiveAnyChartView(anyChartView);
pie = AnyChart.pie();
pie.data(data);
pie.title("2nd Anychart Title");
//pie.labels().position("outside");
pie.innerRadius(50);
pie.legend().title().enabled(true);
pie.legend().title(false);
pie.legend()
.position("center-bottom")
.itemsLayout(LegendLayout.HORIZONTAL_EXPANDABLE)
.align(Align.CENTER);
//pie.fill("aquastyle");
pie.labels().format("{%x}\\n{%value}");
anyChartView.setChart(pie);
pie.tooltip(false);
pie.setOnClickListener(new ListenersInterface.OnClickListener(new String[]{"x", "value"}) {
#Override
public void onClick(Event event) {
Toast.makeText(getActivity(), "Fragment2==>"+event.getData().get("x") + ":" + event.getData().get("value"), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
fragment1.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">
<Button
android:id="#+id/btn_back"
android:enabled="false"
android:layout_width="60dp"
android:layout_height="40dp"
android:text="BACK" />
<com.anychart.AnyChartView
android:id="#+id/any_chart_view1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="#+id/progress_bar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
Here is my code link: https://drive.google.com/file/d/1YnIL1fE52W_Gy4yuc2rYb4fh4Y1hGNuG/view?usp=sharing
Unfortunately, now we have no idea what exactly happens with event dispatching in Fragments. But I would like to bring to your attention that there's a possible workaround.
Click on a chart returns correct point name and value. Only the fragment name is wrong. The name is hardcoded in the click event handler.
So if the fragment name is not required in output, you can just drop it. If the name is required you can apply a specific ID to the Fragment and then get that ID from active fragment view. This should solve the issue as a temporary workaround.

Swipe Left Swipe Right textview in fragment - Android app

Please suggest me how implement Swipe left or right in my app? Is page viewer or gesture can be used. I get content for text view from string array when item clicked. I am new to app development.
My MainActivity xml
import android.app.FragmentTransaction;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener
{
private ActionBarDrawerToggle actionBarDrawerToggle;
private DrawerLayout drawerLayout;
private ListView navList;
private FragmentManager fragmentManager;
boolean nightmode=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = (DrawerLayout)findViewById(R.id.drawerlayout);
navList = (ListView)findViewById(R.id.navlist);
String[] versionName = getResources().getStringArray(R.array.version_names);
navList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, versionName);
navList.setAdapter(adapter);
navList.setOnItemClickListener(this);
actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,R.string.opendrawer,R.string.closedrawer);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
fragmentManager = getSupportFragmentManager();
OnSelectionChanged(0);
}
public void OnSelectionChanged(int position) {
DescriptionFragment descriptionFragment = (DescriptionFragment) getFragmentManager()
.findFragmentById(R.id.description_fragment);
if (descriptionFragment != null){
// If description is available, we are in two pane layout
// so we call the method in DescriptionFragment to update its content
descriptionFragment.setDescription(position);
} else {
DescriptionFragment newDesriptionFragment = new DescriptionFragment();
Bundle args = new Bundle();
args.putInt(DescriptionFragment.KEY_POSITION,position);
newDesriptionFragment.setArguments(args);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the backStack so the User can navigate back
fragmentTransaction.replace(R.id.fragment_container,newDesriptionFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
#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) {
TextView textElement = (TextView) findViewById(R.id.version_description);
FrameLayout mainLayout = (FrameLayout) findViewById(R.id.fragment_container);
if(nightmode) textElement.setTextColor(Color.WHITE);
switch(item.getItemId()){
case R.id.action_settings:
if (nightmode) {
mainLayout.setBackgroundResource(R.color.white);
textElement.setTextColor(Color.BLACK);
nightmode=false;
}else {
mainLayout.setBackgroundResource(R.color.background_color);
textElement.setTextColor(Color.WHITE);
nightmode=true;
}
break;
case android.R.id.home:
if (drawerLayout.isDrawerOpen(navList)){
drawerLayout.closeDrawer(navList);
}else{
drawerLayout.openDrawer(navList);
}
break;
case R.id.action_share:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
OnSelectionChanged(position);
drawerLayout.closeDrawer(navList);
}
}
My DescriptionFragment
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by sathi on 16-01-2016.
*/
public class DescriptionFragment extends Fragment {
final static String KEY_POSITION = "position";
int mCurrentPosition = -1;
String[] mVersionDescriptions;
TextView mVersionDescriptionTextView;
public DescriptionFragment(){
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mVersionDescriptions = getResources().getStringArray(R.array.version_descriptions);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/* DescriptionFragment descriptionFragment = new DescriptionFragment();
Object fromFragment = null;
Object toFragment=null;
descriptionFragment.addFragment(Fragment fromFragment, Fragment toFragment);*/
// If the Activity is recreated, the savedInstanceStare Bundle isn't empty
// we restore the previous version name selection set by the Bundle.
// This is necessary when in two pane layout
if (savedInstanceState != null) {
mCurrentPosition = savedInstanceState.getInt(KEY_POSITION);
}
// FragmentTransaction fragmentTransaction = null;
// fragmentTransaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left);
View view = inflater.inflate(R.layout.fragment_description, container, false);
mVersionDescriptionTextView = (TextView) view.findViewById(R.id.version_description);
return view;
/* DescriptionFragment fragment1 = new DescriptionFragment();
(getSupportFragmentManager().beginTransaction().add(R.id.description_fragment, fragment1)
.add(R.id.description_fragment, fragment1).commit()){
}*/
}
public void addFragment(Fragment fromFragment, Fragment toFragment) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.fragment_container,toFragment, toFragment.getClass().getName());
transaction.hide(fromFragment);
transaction.addToBackStack(toFragment.getClass().getName());
transaction.commit();
}
public void replaceFragment(Fragment fromFragment, Fragment toFragment) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_container,toFragment, toFragment.getClass().getName());
transaction.hide(fromFragment);
transaction.addToBackStack(toFragment.getClass().getName());
transaction.commit();
}
private FragmentManager getSupportFragmentManager() {
return null;
}
#Override
public void onStart() {
super.onStart();
// During the startup, we check if there are any arguments passed to the fragment.
// onStart() is a good place to do this because the layout has already been
// applied to the fragment at this point so we can safely call the method below
// that sets the description text
Bundle args = getArguments();
if (args != null){
// Set description based on argument passed in
setDescription(args.getInt(KEY_POSITION));
} else if(mCurrentPosition != -1){
// Set description based on savedInstanceState defined during onCreateView()
setDescription(mCurrentPosition);
}
}
public void setDescription(int descriptionIndex){
mVersionDescriptionTextView.setText(mVersionDescriptions[descriptionIndex]);
mCurrentPosition = descriptionIndex;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save the current description selection in case we need to recreate the fragment
outState.putInt(KEY_POSITION,mCurrentPosition);
}
}
I didn't understand if that actually what you trying to do but as i understood if you want the TextView moves automatically in one line to show the rest of it make this:
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:freezesText="true"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true" />
and in code after defining it's view make this:
textView.setChecked(true);

Android sliding tabs, Fragment_Collection_Object Error

am following the Android Developers website to add sliding tabs to my Android app for my project, I am stuck with this one error and do not understand the problem, I know it has something to do with calling the correct Fragment layout, I am doing exactly what the tutorial tells me too, have any of you guys got any information to solve this, thank you.
package com.test.finalproject;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends FragmentActivity implements View.OnClickListener {
DemoCollectionPagerAdapter mCollectionPagerAdapter;
ViewPager mViewPager;
Button buttonLogin;
Button buttonRegister;
Button buttonTheme;
Button buttonMaps;
#Override
protected void onCreate(Bundle savedInstanceState) {
Utils.setThemeToActivity(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final android.app.ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create a tab listener that is called when the user changes tabs.
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
// show the given tab
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
// hide the given tab
}
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
// probably ignore this event
}
};
// Add 3 tabs, specifying the tab's text and TabListener
for (int i = 0; i < 3; i++) {
actionBar.addTab(
actionBar.newTab()
.setText("Tab " + (i + 1))
.setTabListener(tabListener));
}
buttonLogin = (Button)findViewById(R.id.buttonLogin);
buttonLogin.setOnClickListener(this);
buttonRegister = (Button)findViewById(R.id.buttonRegister);
buttonRegister.setOnClickListener(this);
buttonTheme = (Button)findViewById(R.id.buttonTheme);
buttonTheme.setOnClickListener(this);
buttonMaps = (Button)findViewById(R.id.buttonMaps);
buttonMaps.setOnClickListener(this);
mCollectionPagerAdapter =
new DemoCollectionPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCollectionPagerAdapter);
}
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
// Our object is just an integer :-P
args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 100;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
Integer.toString(args.getInt(ARG_OBJECT)));
return rootView;
}
}
public void onCreate1(Bundle savedInstanceState) {
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between pages, select the
// corresponding tab.
getActionBar().setSelectedNavigationItem(position);
}
});
}
private void buttonLoginClick()
{
startActivity (new Intent("MainApp"));
}
private void buttonRegisterClick()
{
startActivity (new Intent("TextToo"));
}
private void buttonThemeClick()
{
startActivity (new Intent("SettingsTheme"));
}
private void buttonMapsClick()
{
startActivity (new Intent("GoogleMaps"));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.buttonLogin:
buttonLoginClick();
break;
}
switch (v.getId())
{
case R.id.buttonRegister:
buttonRegisterClick();
break;
}
switch (v.getId())
{
case R.id.buttonTheme:
buttonThemeClick();
break;
}
switch (v.getId())
{
case R.id.buttonMaps:
buttonMapsClick();
break;
}
}
}
The Error is on line 126.
The Error is: Description Resource Path Location Type
fragment_collection_object cannot be resolved or is not a field MainActivity.java /Login/src/com/test/finalproject line 126 Java Problem
The problem you are facing is because of the missing xml file in the layout folder of project/res
Go to http://developer.android.com/training/implementing-navigation/lateral.html
Click on "download the sample app" and unzip it. Add the EffectiveNavigation\res\layout\fragment_collection_object.xml to you project\res\layout. This,I guess will solve the problem.

Android Swipe tabs Issue: Can't seem to update the UI and the result comes repeated n times

I'm using two classes. One for the background service where i'm doing several of gatherings of information, and the other I decided to use a swipe tab view to manage and organize my information/data. In the background service (like I said) i'm retrieving information (mostly string types) and sending them via intent to the Main Activity, this activity receives it via a broadcastreceiver (this part works fine). Now the problem i'm having is that when i try to distribute the information the the diferent tabs, it comes repeated and doesn't seem to refresh now my most crucial problem is the reapeating information part. Going to place my code and see if any one of you brilliant minds :D can help me. I hope you can.
import java.util.Locale;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class ActivityMain extends FragmentActivity implements
ActionBar.TabListener {
int NUM_TAB = 3;
static TextView InfoView1;
static TextView InfoView2;
static TextView InfoView3;
static String infoData1 = "";
static String infoData2 = "";
static String infoData3 = "";
Fragment frag;
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
Defining the intent
intent = new Intent(this, BroadcastService.class);
}
Starting the broadcastreceiver to call the Background service
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateUI(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.activity_main, menu);
return true;
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
switch (position)
{
case 0:
frag = new Information1();
Bundle arg0 = new Bundle();
arg0.putString(Information1.ARG_SECTION, infoData1);
frag.setArguments(arg0);
break;
case 1:
frag = new Information2();
Bundle arg1 = new Bundle();
arg1.putString(Information2.ARG_SECTION, infoData2);
frag.setArguments(arg1);
break;
case 2:
frag = new Information3();
Bundle arg2 = new Bundle();
arg2.putString(BatteryStatus.ARG_SECTION, infoData3);
frag.Information3(arg2);
break;
default:
frag = null;
break;
}
return frag;
}
#Override
public int getCount() {
// Show 3 total pages.
return NUM_TAB;
}
#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;
}
}
private void updateUI(Intent intent) {
String stuff1 = intent.getStringExtra("stuff");
String stuff2 = intent.getStringExtra("stuff2");
String stuff3 = intent.getStringExtra("stuff3");
String stuff4 = intent.getStringExtra("stuff4");
String stuff5 = intent.getStringExtra("stuff5");
String stuff6 = intent.getStringExtra("stuff6");
so on...
And storing them in a string
infoData1 += ("Stuff1: " + stuff1 + "\n");
infoData1 += ("Stuff2: " + stuff2 + "\n");
infoData2 += ("Stuff3: " + Stuff3 + "\n");
infoData2 += ("Stuff4: " + Stuff4 + "\n");
infoData3 += ("Stuff5: " + Stuff5 + "\n");
infoData3 += ("Stuff6: " + Stuff6 + "\n");
}
public static class Information1 extends Fragment {
public static final String ARG_SECTION = "section_number";
public Information1(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View info1View = inflater.inflate(
R.layout.information1, container, false);
InfoView1 = (TextView) info1View
.findViewById(R.id.info1);
InfoView1.setText(getArguments().getString(ARG_SECTION));
Log.d("InfoView1", infoData1);
return info1View;
}
}
public static class Information2 extends Fragment {
public static final String ARG_SECTION = "section_number";
public Information2(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View info2View = inflater.inflate(
R.layout.Information2, container, false);
InfoView2 = (TextView) info2View
.findViewById(R.id.info2);
InfoView2.setText(getArguments().getString(ARG_SECTION));
Log.d("InfoView2", infoData2);
return info2View;
}
}
public static class Information3 extends Fragment {
public static final String ARG_SECTION = "section_number";
public Information3() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View info3View = inflater.inflate(
R.layout.Information3, container, false);
InfoView3 = (TextView) info3View
.findViewById(R.id.info3);
InfoView3.setText(getArguments().getString(ARG_SECTION));
Log.d("BatteryStatView", infoData3);
return info3View;
}
}
#Override
public void onResume() {
super.onResume();
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(BroadcastService.BROADCAST_ACTION));
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
stopService(intent);
}
}
Any ideas?! =D

Update a TextView in a ViewPager from another Fragment

I am trying to update a TextView in a Fragment clicking on a button on another Fragment.
Actually I implemented the callback function to the Activity and it does work, since the Logcat reports that the text in the TextView has been changed. The problem is the Textview shown in the first fragment is not updated to the new value! It's like the Fragment needs to be updated or something...
Here's the ActionBarTabsPager activity code:
import java.util.ArrayList;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentManager.OnBackStackChangedListener;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ActionBar.Tab;
import android.support.v4.app.SupportActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.TextView;
/**
* Demonstrates combining the action bar with a ViewPager to implement a tab UI
* that switches between tabs and also allows the user to perform horizontal
* flicks to move between the tabs.
*/
public class ActionBarTabsPager extends FragmentActivity implements SecondFragment.OnButtonClickedXListener{
ViewPager mViewPager;
TabsAdapter mTabsAdapter;
FragmentManager fm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actionbar_tabs_pager);
if (savedInstanceState == null) {
Fragment newFragment = new FirstFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.abs__custom, newFragment, "FirstFragment").commit();
Fragment newFragment2 = new FirstFragment();
FragmentTransaction ft2 = getSupportFragmentManager().beginTransaction();
ft2.add(R.id.abs__custom, newFragment2, "SecondFragment").commit();
}
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tab1 = getSupportActionBar().newTab().setText("Fragment 1");
ActionBar.Tab tab2 = getSupportActionBar().newTab().setText("Fragment 2");
//ActionBar.Tab tab3 = getSupportActionBar().newTab().setText("Fragment 1");
//ActionBar.Tab tab4 = getSupportActionBar().newTab().setText("Fragment 2");
mViewPager = (ViewPager)findViewById(R.id.pager);
mTabsAdapter = new TabsAdapter(this, getSupportActionBar(), mViewPager);
mTabsAdapter.addTab(tab1, FirstFragment.class);
mTabsAdapter.addTab(tab2, SecondFragment.class);//LoaderCursorSupport.CursorLoaderListFragment.class);
//mTabsAdapter.addTab(tab3, FirstFragment.class);//LoaderCustomSupport.AppListFragment.class);
//mTabsAdapter.addTab(tab4, SecondFragment.class);//LoaderThrottleSupport.ThrottledLoaderListFragment.class);
if (savedInstanceState != null) {
getSupportActionBar().setSelectedNavigationItem(savedInstanceState.getInt("index"));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("index", getSupportActionBar().getSelectedNavigationIndex());
}
/**
* This is a helper class that implements the management of tabs and all
* details of connecting a ViewPager with associated TabHost. It relies on a
* trick. Normally a tab host has a simple API for supplying a View or
* Intent that each tab will show. This is not sufficient for switching
* between pages. So instead we make the content part of the tab host
* 0dp high (it is not shown) and the TabsAdapter supplies its own dummy
* view to show as the tab content. It listens to changes in tabs, and takes
* care of switch to the correct paged in the ViewPager whenever the selected
* tab changes.
*/
public class TabsAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener, ActionBar.TabListener {
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<String> mTabs = new ArrayList<String>();
public TabsAdapter(FragmentActivity activity, ActionBar actionBar, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = actionBar;
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss) {
mTabs.add(clss.getName());
mActionBar.addTab(tab.setTabListener(this));
notifyDataSetChanged();
}
#Override
public int getCount() {
return mTabs.size();
}
#Override
public Fragment getItem(int position) {
return Fragment.instantiate(mContext, mTabs.get(position), null);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
#Override
public void OnButtonClickedX(View v) {
if (v==findViewById(R.id.button1)){
Log.i("TRIGGERED","TRIGGERED");
FirstFragment ff = (FirstFragment) getSupportFragmentManager().findFragmentByTag("FirstFragment");
View root = ff.getView();
TextView tv = (TextView) root.findViewById(R.id.textView1);
Log.i("Text before Edit",""+tv.getText());
tv.setText("MODIFIED");
Log.i("Text after Edit",""+tv.getText());
}
// TODO Auto-generated method stub
}
}
FirstFragment:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FirstFragment extends Fragment {
int mNum;
/**
* Create a new instance of FirstFragment, providing "num"
* as an argument.
*/
static FirstFragment newInstance(int num) {
FirstFragment f = new FirstFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
/**
* When creating, retrieve this instance's number from its arguments.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
/**
* The Fragment's UI is just a simple text view showing its
* instance number.
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.myfrag1, container, false);
return v;
}
}
SecondFragment:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.SupportActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
public class SecondFragment extends Fragment {
int mNum;
OnButtonClickedXListener mListener;
/**
* Create a new instance of CountingFragment, providing "num"
* as an argument.
*/
static SecondFragment newInstance(int num) {
SecondFragment f = new SecondFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
/**
* When creating, retrieve this instance's number from its arguments.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
/**
* The Fragment's UI is just a simple text view showing its
* instance number.
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.myfrag2, container, false);
View button1 = v.findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mListener.OnButtonClickedX(v);
// TODO Auto-generated method stub
}
});
return v;
}
public interface OnButtonClickedXListener{
public void OnButtonClickedX(View v);
}
#Override
public void onAttach(SupportActivity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
try {
mListener = (OnButtonClickedXListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnButtonClickedXListener");
}
}
}
myfrag1.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="No String"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
myfrag2.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="Button" />
</LinearLayout>
EDIT:
Even changing to 0 the ContainerViewId in ft.add() doesn't impact at all in final rendering. SO I guess the rendering is managed by
mTabsAdapter.addTab(tab1, FirstFragment.class);
mTabsAdapter.addTab(tab2, SecondFragment.class);
The issue is still the same, anyway.
Here's actionbar_tabs_pager.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
SOLVED!
Overriding instantiateItem() in TabsAdapter and adding the ViewPager as ContainerViewID in the FragmentTransaction made it!
Here's the functioning whole FragmentActivity!
import java.util.ArrayList;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentManager.OnBackStackChangedListener;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ActionBar.Tab;
import android.support.v4.app.SupportActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.TextView;
/**
* Demonstrates combining the action bar with a ViewPager to implement a tab UI
* that switches between tabs and also allows the user to perform horizontal
* flicks to move between the tabs.
*/
public class ActionBarTabsPager extends FragmentActivity implements SecondFragment.OnButtonClickedXListener{
ViewPager mViewPager;
TabsAdapter mTabsAdapter;
FragmentManager fm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("ONCREATE START","ONCREATE START");
setContentView(R.layout.actionbar_tabs_pager);
if (savedInstanceState == null) {
Fragment newFragment = new FirstFragment();
Fragment newFragment2 = new SecondFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.pager, newFragment, "FirstFragment");
ft.add(R.id.pager, newFragment2, "SecondFragment");
ft.commit();
}
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tab1 = getSupportActionBar().newTab().setText("Fragment 1");
ActionBar.Tab tab2 = getSupportActionBar().newTab().setText("Fragment 2");
//ActionBar.Tab tab3 = getSupportActionBar().newTab().setText("Fragment 1");
//ActionBar.Tab tab4 = getSupportActionBar().newTab().setText("Fragment 2");
mViewPager = (ViewPager)findViewById(R.id.pager);
mTabsAdapter = new TabsAdapter(this, getSupportActionBar(), mViewPager);
mTabsAdapter.addTab(tab1, FirstFragment.class);
mTabsAdapter.addTab(tab2, SecondFragment.class);//LoaderCursorSupport.CursorLoaderListFragment.class);
//mTabsAdapter.addTab(tab3, FirstFragment.class);//LoaderCustomSupport.AppListFragment.class);
//mTabsAdapter.addTab(tab4, SecondFragment.class);//LoaderThrottleSupport.ThrottledLoaderListFragment.class);
if (savedInstanceState != null) {
getSupportActionBar().setSelectedNavigationItem(savedInstanceState.getInt("index"));
}
Log.i("ONCREATE END","ONCREATE END");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
Log.i("onSaveInstanceState START","onSaveInstanceState START");
super.onSaveInstanceState(outState);
outState.putInt("index", getSupportActionBar().getSelectedNavigationIndex());
Log.i("onSaveInstanceState END","onSaveInstanceState END");
}
/**
* This is a helper class that implements the management of tabs and all
* details of connecting a ViewPager with associated TabHost. It relies on a
* trick. Normally a tab host has a simple API for supplying a View or
* Intent that each tab will show. This is not sufficient for switching
* between pages. So instead we make the content part of the tab host
* 0dp high (it is not shown) and the TabsAdapter supplies its own dummy
* view to show as the tab content. It listens to changes in tabs, and takes
* care of switch to the correct paged in the ViewPager whenever the selected
* tab changes.
*/
public class TabsAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener, ActionBar.TabListener {
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<String> mTabs = new ArrayList<String>();
private FragmentTransaction mCurTransaction = null;
public TabsAdapter(FragmentActivity activity, ActionBar actionBar, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = actionBar;
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss) {
Log.i("addTab","addTab");
mTabs.add(clss.getName());
mActionBar.addTab(tab.setTabListener(this));
notifyDataSetChanged();
}
#Override
public int getCount() {
return mTabs.size();
}
#Override
public Object instantiateItem(View container, int position) {
if (mCurTransaction == null) {
mCurTransaction = getSupportFragmentManager().beginTransaction();
}
// TODO Auto-generated method stub
Fragment fragment = getItem(position);
if (fragment!=null){
Log.i("Fragment Found!","Fragment Found! "+fragment.getTag());
mCurTransaction.attach(fragment);
}
return fragment;//super.instantiateItem(container, position);
}
#Override
public Fragment getItem(int position) {
Log.i("getItem","getItem");
if (position==0)
{Log.i("position=0","position=0");
return getSupportFragmentManager().findFragmentByTag("FirstFragment");}
else if (position==1)
{Log.i("position=1","position=1");
return getSupportFragmentManager().findFragmentByTag("SecondFragment");}
else return null;//Fragment.instantiate(mContext, mTabs.get(position), null);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
#Override
public void OnButtonClickedX(View v) {
if (v==findViewById(R.id.button1)){
Log.i("TRIGGERED","TRIGGERED");
FirstFragment ff = (FirstFragment) getSupportFragmentManager().findFragmentByTag("FirstFragment");
View root = ff.getView();
TextView tv = (TextView) root.findViewById(R.id.textView1);
Log.i("Text before Edit",""+tv.getText());
tv.setText("MODIFIED");
Log.i("Text after Edit",""+tv.getText());
}
// TODO Auto-generated method stub
}
}
Thanks to vbsteven!
I assume the Fragments you are seeing on screen are not the Fragments you manually add with the tags "FirstFragment" and "SecondFragment" but instead the fragments that are added by the getItem method of your TabsAdapter.
If you look at its implementation, it instantiates new Fragments.
#Override
public Fragment getItem(int position) {
return Fragment.instantiate(mContext, mTabs.get(position), null);
}
These newly created Fragments are added to the FragmentManager with custom tags generated in FragmentPagerAdapter (which TabsAdapter extends)
My guess is that this is case of "overlapping" fragments - not uncommon to those trying out Fragments for the first time. Everytime you re-display a Fragment (display a Fragment, show another, then go back to the first fragment you displayed), you're creating a new Fragment behind the visible fragment. The "mirror fragment" remains on top, blocking your view to the fragment behind it. Only by scrolling that fragment will you see that the fragment behind really does get updated.
Most of the time it's just a case of you repeating what you did in XML in your FragmentActivity. Post your layout xml's so the fragment pros can diagnose your problem better.
Please post actionbar_tabs_pager.xml as well.
Don't know if it solves your issues but in this part of your code you add FirstFragment() for both fragments...
Fragment newFragment = new FirstFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.abs__custom, newFragment, "FirstFragment").commit();
Fragment newFragment2 = new FirstFragment();
FragmentTransaction ft2 = getSupportFragmentManager().beginTransaction();
ft2.add(R.id.abs__custom, newFragment2, "SecondFragment").commit();
...and you could write it more simple like that:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.abs__custom, newFragment, "FirstFragment");
ft.add(R.id.abs__custom, newFragment2, "SecondFragment");
ft.commit();

Categories

Resources