OnDetach/onAttach fragment recreate fragment activity - android

I want to detach/attach my fragments, but how to set, that fragment not recreate, after I attach.
In fragment I have WebView; when I select and unselect tabs, webview load startpage.
There is my code:
public class MainActivity extends Activity implements OnClickListener, OnMenuItemClickListener {
ActionBar bar;
View v;
public static TextView tilt;
LayoutInflater inflater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
onAddTab();
View v=getLayoutInflater().inflate(R.layout.action_bar, null);
ImageButton im = (ImageButton)v.findViewById(R.id.tab_toggle);
im.setOnClickListener(this);
getActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_layout));
getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getActionBar().setCustomView(v);
onToggleTabs();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.tab_toggle:
onAddTab();
break;
}
}
public void onAddTab() {
final ActionBar bar = getActionBar();
View v=getLayoutInflater().inflate(R.layout.layout_tab, null);
tilt = (TextView)v.findViewById(R.id.tit_le);
ActionBar.LayoutParams lp = new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER;
v.setLayoutParams(lp);
closetab = (ImageButton)v.findViewById(R.id.close);
closetab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
onRemoveTab();
}
});
bar.addTab(bar.newTab()
.setCustomView(v)
.setTabListener(new TabListener<Web>(this, "Tag A", Web.class)));
}
public void onRemoveTab() {
final ActionBar bar = getActionBar();
Tab tab = bar.getSelectedTab();
bar.removeTab(tab);
}
public void onToggleTabs() {
final ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
public void onRemoveAllTabs(View v) {
getActionBar().removeAllTabs();
}
public static class TabListener<T extends Fragment> implements ActionBar.TabListener{
private final Activity myActivity;
private final String myTag;
private final Class<T> myClass;
public TabListener(Activity activity, String tag, Class<T> cls) {
myActivity = activity;
myTag = tag;
myClass = cls;
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Fragment myFragment = myActivity.getFragmentManager().findFragmentByTag(myTag);
// Check if the fragment is already initialized
if (myFragment == null) {
// If not, instantiate and add it to the activity
myFragment = Fragment.instantiate(myActivity, myClass.getName());
ft.add(R.id.fragment0, myFragment, myTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(myFragment);
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
Fragment myFragment = myActivity.getFragmentManager().findFragmentByTag(myTag);
if (myFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(myFragment);
}
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
There is Fragment:
public class Web extends Fragment implements OnLongClickListener, OnClickListener{
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
c=this.getActivity();
v = inflater.inflate(R.layout.activity_main, container, false);
return v;
}
#SuppressWarnings("deprecation")
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
wv = (WebView)v.findViewById(R.id.wv);
wv.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int progress) {
// TODO Auto-generated method stub
super.onProgressChanged(view, progress);
if(progress < 100 && pr.getVisibility() == ProgressBar.GONE){
pr.setVisibility(ProgressBar.VISIBLE);
}
pr.setProgress(progress);
if(progress == 100) {
pr.setVisibility(ProgressBar.GONE);
}
}
});
wv.setWebViewClient(new MyWebViewClient());
wv.loadUrl("http://www.google.com");
wv.setOnLongClickListener(this);}

Try setRetainInstance(boolean)
Also check this posts:
Android fragments setRetainInstance(true) not works (Android support library)
Fragment setRetainInstance not works (Android support lib)
Understanding Fragment's setRetainInstance(boolean)

Related

tabs in viewpager not responding in a sequence android

In my android app I am using a tab swipe view having 4 tabs first tab displays data on the UI and is calling a WS via AsyncTask, data returned by the WS is populating a pojo and this pojo is passed to other tab(fragments)
The problem I face is Tabs are not executed in a sequence when I click on first tab, first and 2 tab are executing before calling WS due to this strange behaviour I cant get data in my second tab
Activity:
public class TabSwipeActivity extends FragmentActivity implements ActionBar.TabListener, DetailsFoeFragment.ExistingFeatureDataInt
{
ActionBar actionbar;
ViewPager viewpager;
FragmentPageAdapter ft;
ExistingData existingData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabswipe);
ArrayList<String> detailList =this.getIntent().getStringArrayListExtra("FeatureData");
viewpager = (ViewPager) findViewById(R.id.pager1);
ft = new FragmentPageAdapter(getSupportFragmentManager());
if(detailList!=null)
ft.setDetailList(detailList);
// ft.setExistingData(getExistingData());
actionbar = getActionBar();
viewpager.setAdapter(ft);
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionbar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
actionbar.addTab(actionbar.newTab().setText("Details").setTabListener(this),0,true);
actionbar.addTab(actionbar.newTab().setText("Action Taken").setTabListener(this),1,false);
actionbar.addTab(actionbar.newTab().setText("Before Photos").setTabListener(this),2,false);
actionbar.addTab(actionbar.newTab().setText("After Photos").setTabListener(this),3,false);
viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
public void onPageSelected(int arg0) {
actionbar.setSelectedNavigationItem(arg0);
}
});
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewpager.setCurrentItem(tab.getPosition());
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
////
Adapter:
/////
public class FragmentPageAdapter extends FragmentPagerAdapter {
Bundle bundle= new Bundle();
ExistingData existingData = new ExistingData();;
public FragmentPageAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
Fragment fragment;
#Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
switch (arg0) {
case 0:
fragment = new DetailsFoeFragment();
bundle.putStringArrayList("details",detailList);
fragment.setArguments(this.bundle);
return fragment;
case 1:
fragment= new ActionFoeFragment();
bundle.putParcelableArrayList("actions",(ArrayList)existingData.getActionList());
// bundle.putParcelableArrayList("actions",(ArrayList)existingData.getActionList());
// bundle.putString("featureId",detailList.get(2));
fragment.setArguments(this.bundle);
return fragment;
case 2:
fragment = new PhotoBeforeFoeFragment();
// bundle.putStringArrayList("beforeImage",null);
bundle.putStringArrayList("beforeImage",(ArrayList<String>)existingData.getBeforeImagePath());
fragment.setArguments(this.bundle);
return fragment;
case 3:
fragment = new PhotoAfterFoeFragment();
bundle.putStringArrayList("afterImage",(ArrayList<String>)existingData.getAfterImagePath());
fragment.setArguments(this.bundle);
return fragment;
default:
break;
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 4;
}
ArrayList<String> detailList;
public void setDetailList(ArrayList<String> detailList) {
this.detailList = detailList;
}
public void setExistingData(ExistingData existingData) {
this.existingData = existingData;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
Please provide inputs
thanks
One solution:
In your activity, run WS with Asynctask, and then call the fragments that need data to update view
class yourActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
... ...
//set up your tabs with fragments
... ...
//WS: Your asynctask requesting data from server
(new AsyncTask<... ...>() {
... ...
#Override
protected void onPostExecute(dataSet) {
//here you have got your data set from server then inform tabs to update
YourFragment frag = (YourFragment)getSupportFragmentManager().findFragmentById(R.id.your_fragment);
frag.updateView(dataSet);
}
}).execute();
}
}
In each tab/fragment that needs shared data set, define a method to update view with the data set
class YourFragment extebds Fragment{
... ...
public void updateView(dataSet)
{
//update this fragment view with dataSet
//and stop your waiting dialog
}
}
Hope this solution works for you.

Passing Url to another WebView Tab and load

I'm new to programming .
I make an app that contains 3 Tabs with viewpager. 1st tab is a list of Button with their respective link. 2nd Tab is a WebView that will load url passed from the 1st tab when the users clicked on the link. 3rd tab is my Download Manager.
This is my MainActivity:
public class MainActivity extends SherlockFragmentActivity{
ActionBar mActionBar;
Button button;
ViewPager mPager;
Tab tab;
String TabFragmentB;
public void setTabFragmentB(String t){
TabFragmentB = t;
}
public String getTabFragmentB(){
return TabFragmentB;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mActionBar = getSupportActionBar();
// Hide Actionbar Icon
mActionBar.setDisplayShowHomeEnabled(false);
// Hide Actionbar Title
mActionBar.setDisplayShowTitleEnabled(false);
// Create Actionbar Tabs
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//For ViewPager
mPager = (ViewPager) findViewById(R.id.pager);
//Activate FragmentManger
FragmentManager fm= getSupportFragmentManager();
ViewPager.SimpleOnPageChangeListener ViewPagerListener = new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position){
super.onPageSelected(position);
mActionBar.setSelectedNavigationItem(position);//find the viewPager Potision
}
};
mPager.setOnPageChangeListener(ViewPagerListener);
// Locate the adapter class called ViewPagerAdapter.java
ViewPagerAdapter viewpageradapter = new ViewPagerAdapter(fm);
// Set the View Pager Adapter into ViewPager
mPager.setAdapter(viewpageradapter);
// Capture tab button clicks
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Pass the position on tab click to ViewPager
mPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
};
// Create first Tab
tab = mActionBar.newTab().setIcon(R.drawable.button_home).setTabListener(tabListener);
mActionBar.addTab(tab);
// Create second Tab
tab = mActionBar.newTab().setIcon(R.drawable.button_browse).setTabListener(tabListener);
mActionBar.addTab(tab);
// Create third Tab
tab = mActionBar.newTab().setIcon(R.drawable.button_downloads).setTabListener(tabListener);
mActionBar.addTab(tab);
}
}
My FragmentTab1:
public class FragmentTab1 extends SherlockFragment implements OnClickListener{
FragmentTab2 fTab2;
ViewPager viewPager;
WebView webview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home, container, false);
viewPager = (ViewPager) getActivity().findViewById(R.id.pager);
webview = (WebView) view.findViewById(R.id.webView1);
view.findViewById(R.id.Button01).setOnClickListener(this);
view.findViewById(R.id.Button02).setOnClickListener(this);
view.findViewById(R.id.Button03).setOnClickListener(this);
view.findViewById(R.id.Button04).setOnClickListener(this);
view.findViewById(R.id.Button05).setOnClickListener(this);
return view;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
setUserVisibleHint(true);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.Button01:
String urlToBeSend = " http://google.com";
String TabOfFragmentB = ((MainActivity)getActivity()).getTabFragmentB();
FragmentTab2 fragmentB = (FragmentTab2)getActivity().getSupportFragmentManager().findFragmentByTag(TabOfFragmentB);
fragmentB.b_updateText(urlToBeSend);
Toast.makeText(getSherlockActivity(), "url to be send = " +urlToBeSend, Toast.LENGTH_LONG).show();
viewPager.setCurrentItem(1);
break;
case R.id.Button02:
String urlToBeSend2 = " http://facebook.com";
String TabOfFragmentB2 = ((MainActivity)getActivity()).getTabFragmentB();
FragmentTab2 fragmentB2 = (FragmentTab2)getActivity().getSupportFragmentManager().findFragmentByTag(TabOfFragmentB2);
fragmentB2.b_updateText(urlToBeSend2);
Toast.makeText(getSherlockActivity(), "url to be send = " +urlToBeSend2, Toast.LENGTH_LONG).show();
viewPager.setCurrentItem(1);
break;
case R.id.Button03:
viewPager.setCurrentItem(1);
break;
case R.id.Button04:
viewPager.setCurrentItem(1);
break;
case R.id.Button05:
viewPager.setCurrentItem(1);
break;
default:
break;
}
}
}
For My FragmentTab2:
public class FragmentTab2 extends SherlockFragment {
private static WebView webview;
private ProgressBar progress;
String homeUrl="http://new3gpmovies.com/";
private int urlIndex=0;
String a_url;
TextView b_received;
ViewPager viewpager;
public void b_updateText(String t){
b_received.setText(t);
a_url = t;
}
public FragmentTab2(){
}
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.webview, container, false);
String myTag = getTag();
((MainActivity)getActivity()).setTabFragmentB(myTag);
b_received = (TextView) view.findViewById(R.id.textView1);
ImageView backward = (ImageView) view.findViewById(R.id.backward);
ImageView forward = (ImageView) view.findViewById(R.id.forward);
backward.setOnClickListener(new OnClickListener(){
public void onClick(View view){
if (webview.canGoBack()){
webview.goBack();
}
}
});
forward.setOnClickListener(new OnClickListener(){
public void onClick(View view){
if (webview.canGoForward()){
webview.goForward();
}
}
});
webview = (WebView) view.findViewById(R.id.webView1);
webview.setWebChromeClient(new MyWebChromeClient());
webview.setWebViewClient(new MyWebViewClient());
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
progress = (ProgressBar) view.findViewById(R.id.progressBar1);
progress.setMax(100);
if (a_url != null){
webview.loadUrl(a_url);
}else if (a_url == null){
webview.loadUrl(homeUrl);
}
if (progress.getProgress() == 100){
FragmentTab2.this.progress.setProgress(0);
}
return view;
}
private class MyWebViewClient extends WebViewClient{
#SuppressLint({ "InlinedApi", "NewApi" })
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
boolean value = true;
if (url.endsWith(".3gp") || url.endsWith(".mp4")){
Intent downloadIntent = new Intent("com.nanoidea.download.services.IDownloadService");
downloadIntent.putExtra(MyIntents.TYPE, MyIntents.Types.ADD);
downloadIntent.putExtra(MyIntents.URL, Utils.url[urlIndex]);
getActivity().startService(downloadIntent);
urlIndex++;
if (urlIndex >= Utils.url.length) {
urlIndex = 0;
}
value=false;
}
if(value){
view.loadUrl(url);
}
return value;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
webview.loadUrl("file:///android_asset/failedPage.html");
}
}
public String getFileName(String url) {
String filenameWithoutExtension = "";
if (url.endsWith("3gp")){
filenameWithoutExtension = String.valueOf(System.currentTimeMillis()
+ ".3gp");
}else if (url.endsWith(".mp4")){
filenameWithoutExtension = String.valueOf(System.currentTimeMillis()
+ ".mp4");
}
return filenameWithoutExtension;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
setUserVisibleHint(true);
}
private class MyWebChromeClient extends WebChromeClient{
#Override
public void onProgressChanged(WebView view, int newProgress){
FragmentTab2.this.setValue(newProgress);
super.onProgressChanged(view, newProgress);
}
}
public void setValue(int progress){
this.progress.setProgress(progress);
}
public static boolean canGoBack(){
return webview.canGoBack();
}
public static void goBack(){
webview.goBack();
}
}
Question:
Why when i click on the link from the 1st tab the second tab doesn't change? even if the 2nd tab received the string url from the 1st tab? any idea? Please guide me.

Android refresh a fragment list from its parent activity

I have a main activity which contains the action bar with 3 menu buttons in it.
I then have a fragment within this main activity which has a list.
I would like to be able to refresh the list in the fragment from the main activity, when one of the menu buttons is clicked, or preferably just removed all the rows from the list.
Any help is appreciated.
Thanks.
public class Favourite extends SherlockFragmentActivity {
ActionBar actionBar;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favourite);
actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(false);
BitmapDrawable bg = (BitmapDrawable)getResources().getDrawable(R.drawable.actionbar_bg);
bg.setTileModeX(TileMode.REPEAT);
getSupportActionBar().setBackgroundDrawable(bg);
getSupportActionBar().setIcon(R.drawable.favourite_title);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tabAll = actionBar.newTab();
ActionBar.Tab tabfavs = actionBar.newTab();
ActionBar.Tab tabhist = actionBar.newTab();
tabAll.setText("all");
tabfavs.setText("favs");
tabhist.setText("hist");
tabAll.setTabListener(new MyTabListener());
tabfavs.setTabListener(new MyTabListener());
tabhist.setTabListener(new MyTabListener());
actionBar.addTab(tabAll);
actionBar.addTab(tabfavs);
actionBar.addTab(tabhist);
try{
}
catch(Exception e)
{
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.actionbar_itemlist_favourite, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.history:
break;
case R.id.favourite:
Intent favAct = new Intent(this, Favourite.class);
startActivity(favAct);
break;
case R.id.delete:
///I WANT TO BE ABLE TO REFRESH FRAGMENTLIST FROM HERE
}
return true;
}
}
class MyTabListener implements ActionBar.TabListener {
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if(tab.getPosition()==0)
{
FavouriteAllWords frag = new FavouriteAllWords();
ft.replace(android.R.id.content, frag);
}
else if(tab.getPosition()==1)
{
FavouriteFavWords frag = new FavouriteFavWords();
ft.replace(android.R.id.content, frag);
}
else if(tab.getPosition()==2)
{
FavouriteHistWords frag = new FavouriteHistWords();
ft.replace(android.R.id.content, frag);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
////////////////////MY LIST FRAGMENT CLASS
public class FavouriteAllWords extends ListFragment {
ArrayAdapter<String> adapter;
List<String> stringOfFavWords;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle saved)
{
adapter = new ArrayAdapter<String>(
inflater.getContext(), R.layout.row, stringOfFavWords);
setListAdapter(adapter);
return super.onCreateView(inflater, group, saved);
}
#Override
public void onActivityCreated (Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
}
You can easily achieve this using INTERFACE
MainActivity.java
public class MainActivity extends Activity {
public FragmentRefreshListener getFragmentRefreshListener() {
return fragmentRefreshListener;
}
public void setFragmentRefreshListener(FragmentRefreshListener fragmentRefreshListener) {
this.fragmentRefreshListener = fragmentRefreshListener;
}
private FragmentRefreshListener fragmentRefreshListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button)findViewById(R.id.btnRefreshFragment);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(getFragmentRefreshListener()!=null){
getFragmentRefreshListener().onRefresh();
}
}
});
}
public interface FragmentRefreshListener{
void onRefresh();
}
}
MyFragment.java
public class MyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = null; // some view
/// Your Code
((MainActivity)getActivity()).setFragmentRefreshListener(new MainActivity.FragmentRefreshListener() {
#Override
public void onRefresh() {
// Refresh Your Fragment
}
});
return v;
}
}
Just make your update/refresh method public and call it from your Activity.
OR
Use LocalBroadcastManager or EventBus to send event from your Activity, and by subscribing to this event in a Fragment - react to it and call refresh/update method.
Your activity can call methods in the fragment by acquiring a reference to the Fragment.
(1) Provide a tag when you add your fragment.
transaction.add(R.id.fragment_container, myFragment, "myfragmentTag");
(2) In your hosting activity you can find the fragment and have access to it's methods.
FragmentManager fm = getSupportFragmentManager();
myFragment f = (myFragment) fm.findFragmentByTag("myfragmentTag");
f.refreshAdapter()
(3) refreshAdapter() could now call adapter.notifyDataSetChanged().
This is one of the recommended ways to communicate up to a fragment.
The interface implementation is mainly for communicating back to the activity.
Biraj Zalavadia's answer is 100% right, you will call nay fragment methods from using interface....
this interface methods is running without error...
use this in MainActivity above oncreate
private FragmentRefreshListener fragmentRefreshListener;
public FragmentRefreshListener getFragmentRefreshListener() {
return fragmentRefreshListener;
}
public void setFragmentRefreshListener(
FragmentRefreshListener fragmentRefreshListener) {
this.fragmentRefreshListener = fragmentRefreshListener;
}
inside of Activity
private void refreshcall(String result2) {
// TODO Auto-generated method stub
if (getFragmentRefreshListener() != null) {
getFragmentRefreshListener().onRefresh(result2);
}
}
and put this in needed Fragment
private FragmentRefreshListener fragmentRefreshListener;
public FragmentRefreshListener getFragmentRefreshListener() {
return fragmentRefreshListener;
}
public void setFragmentRefreshListener(
FragmentRefreshListener fragmentRefreshListener) {
this.fragmentRefreshListener = fragmentRefreshListener;
}
Communicating with Other Fragments
http://developer.android.com/training/basics/fragments/communicating.html
This can also be used to communicate between an Activity and a Fragment.
When you click on ActionBar any Button then call interface to refresh the ListFragment. Because in java interface is used for inter-communication.
In Kotlin
Get the list of Support Fragment from the activity and check Instance and then call fragment function
val fragments = supportFragmentManager.fragments
for (fragment in fragments) {
if (fragment is HomeCategoriesFragment) {
fragment.updateAdapter() // Define function in Fragment
}
}

Android : why custom action bar and action bar tabs combine?

I have problem with the custom actionbar and actionbar tabs for android 4.0.when my application run in the 4.4(in nexus 7.0 tabs)it works fine,but the problem with 4.0 device.the custom actionbar and tabbar are combined and it shown in the whole actionbar. like this
Class
package com.android.timeline;
#SuppressLint({ "SimpleDateFormat", "NewApi" })
public class MainActivity extends FragmentActivity implements ActionBar.TabListener
{
public int width;
private ActionBar actionBar;
private TextView actionBarTitle;
private TabPagerAdapter TabAdapter;
ArrayList<Fragment> fragmentlist = new ArrayList<Fragment>();
private ViewPager Tab;
private String[] tabs = { "About", "Watch Next", "Related" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentlist.add(new AboutDetail());
fragmentlist.add(new WatchNextDetail());
fragmentlist.add(new RelatedDetail());
currentAboutDetail = fragmentlist.get(0);
TabAdapter = new TabPagerAdapter(getSupportFragmentManager());
Tab = (ViewPager) findViewById(R.id.pager);
Tab.setOffscreenPageLimit(2);
pagerchangeListener();
setupActionBar();
}
private void pagerchangeListener() {
Tab.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
Tab.setAdapter(TabAdapter);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt("mMyCurrentPosition", Tab.getCurrentItem());
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mMyCurrentPosition = savedInstanceState.getInt("mMyCurrentPosition");
// where mMyCurrentPosition should be a public value in your activity.
}
private void setupActionBar() {
actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
View cView = getLayoutInflater().inflate(R.layout.actionbartitle, null);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_CUSTOM);
actionBarTitle = (TextView) cView.findViewById(R.id.timeline);
getActionBar().setIcon(R.drawable.log);
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#f16c81")));
actionBar.setCustomView(cView);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
final ImageView actionBarDropDownImg = (ImageView) cView
.findViewById(R.id.pageback);
final ImageView share = (ImageView) cView.findViewById(R.id.setting);
final ImageView font = (ImageView) cView.findViewById(R.id.font);
OnClickListener neww = new OnClickListener() {
#Override
public void onClick(View v) {
if (v == actionBarDropDownImg) {
finish();
overridePendingTransition(R.anim.anim_left,R.anim.anim_right);
}
if (v == font) {
((AboutDetail) currentAboutDetail).fontIncreament();
}
}
};
actionBarDropDownImg.setOnClickListener(neww);
share.setOnClickListener(neww);
font.setOnClickListener(neww);
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
}
public class TabPagerAdapter extends FragmentStatePagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int i) {
Log.e("LOG", "Position || " + i);
return fragmentlist.get(i);
}
#Override
public int getCount() {
return fragmentlist.size(); // No of Tabs
}
#Override
public void destroyItem(View container, int position, Object object) {
}
}
#Override
public void onTabSelected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
Tab.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
please help me ,thanks in advance.
I had same issues with landscape mode and I found the solution here:
http://andreimihu.com/blog/2013/10/17/android-always-embed-tabs-in-actionbar/
Basically, the writer wants the tab inside actionbar while you and I wants it outside. So, just change the method call to false (code from the above link, but a bit modified):
// This is where the magic happens!
public void forceTabs() {
try {
final ActionBar actionBar = getActionBar();
final Method setHasEmbeddedTabsMethod = actionBar.getClass()
.getDeclaredMethod("setHasEmbeddedTabs", boolean.class);
setHasEmbeddedTabsMethod.setAccessible(true);
setHasEmbeddedTabsMethod.invoke(actionBar, false);
}
catch(final Exception e) {
// Handle issues as needed: log, warn user, fallback etc
// This error is safe to ignore, standard tabs will appear.
}
}

Android tabs with ActionBarSherlock and fragments using newInstance

I've just set up a project using tabs + actionbarsherlock + fragments, and want to make sure my approach is correct before moving on - mainly the use of my onTabSelected calling newInstance, this example is derived from CommonsWare's https://github.com/commonsguy/cw-omnibus/tree/master/ActionBar/TabFragmentDemo sample code.
My TabFragmentActivity:
public class TabFragmentActivity extends SherlockFragmentActivity
implements TabListener {
private static final String KEY_POSITION="position";
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
ActionBar bar=getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
bar.addTab(bar.newTab().setText(R.string.tab1)
.setTabListener(this).setTag(0));
bar.addTab(bar.newTab().setText(R.string.tab2)
.setTabListener(this).setTag(1));
bar.addTab(bar.newTab().setText(R.string.tab3)
.setTabListener(this).setTag(2));
bar.addTab(bar.newTab().setText(R.string.tab4)
.setTabListener(this).setTag(3));
if (state != null) {
bar.setSelectedNavigationItem(state.getInt(KEY_POSITION));
}
}
#Override
public void onSaveInstanceState(Bundle state) {
state.putInt(KEY_POSITION,
getSupportActionBar().getSelectedNavigationIndex());
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
int i=((Integer)tab.getTag()).intValue();
if (i == 0){
ft.replace(android.R.id.content,
Tab1Fragment.newInstance(i));
}
else if (i == 1){
ft.replace(android.R.id.content,
Tab2Fragment.newInstance(i));
}
else if (i == 2){
ft.replace(android.R.id.content,
Tab3Fragment.newInstance(i));
}
else if (i == 3){
ft.replace(android.R.id.content,
Tab4Fragment.newInstance(i));
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
My Tab1Fragment:
public class Tab1Fragment extends SherlockFragment {
private static final String KEY_POSITION="position";
static Tab1Fragment newInstance(int position) {
Tab1Fragment frag=new Tab1Fragment();
Bundle args=new Bundle();
args.putInt(KEY_POSITION, position);
frag.setArguments(args);
return(frag);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View result=inflater.inflate(R.layout.tab1, container, false);
return(result);
}
}
Where my Tab1Fragment will eventually do a lot of AsyncTask heavy loading - is this ok as well?

Categories

Resources