I have used fragments here. But I cannot go back to the parent.
Swipeactivitydefault.java
package com.pokhara.nepal;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import com.pokhara.nepal.json.TabsPagerAdapter;
public class Swipeactivitydefault extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Tab1", "Tab2", "Tab3" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpager_news);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
Tab1.java
package com.pokhara.nepal;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;
public class Tab1 extends Fragment {
private WebView webView;
private Bundle webViewBundle;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout ll = (LinearLayout) inflater.inflate(
R.layout.news_activity_child, container, false);
webView = (WebView) ll.findViewById(R.id.webview);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new MyCustomWebViewClient());
if (webViewBundle == null) {
webView.loadUrl("http://www.tipfortechs.com/mobile");
} else {
webView.restoreState(webViewBundle);
}
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
return ll;
}
}
Tab2.java and Tab3.java are also same as Tab 1
Just wanted to make three tabs.
TabsPagerAdapter.java
package com.pokhara.nepal.json;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.pokhara.nepal.Ekantipur;
import com.pokhara.nepal.HimalayaTimes;
import com.pokhara.nepal.NepalNews;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new Tab1();
case 1:
// Games fragment activity
return new Tab2();
case 2:
// Movies fragment activity
return new Tab3();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
news_activity_child.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" >
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Help me Please!!! I want to go back to the parent fragment after opening the link from that webview.
I know there are many answer out there. The one was overiding the back button. But I donot know how to implement. I am new to this. So, can somebody help me with the code.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
}
#Override
public void onBackPressed() {
this.getParent().onBackPressed();
}
write onBackPressed() override method on tab1/tab2/tab3 fragment pages. It will help you.
I am unfamiliar with webview but I have worked with tabbed fragments.
From my experience with tabbed fragments, one way to go would be to implement a method on the main activity that "exposes your viewpager functionality" and swtiches to a desired fragment. For example:
public void showTab(int n) {
viewPager.setCurrentItem(n);
}
Then, within the fragment you want to trigger the transition to the other fragment, you just get the reference to the acitivy and tell it to show the tab you want.
Swipeactivitydefault m = (Swipeactivitydefault )getActivity();
m.showTab(1);
Related
i followed this article http://www.truiton.com/2015/06/android-tabs-example-fragments-viewpager/ to implement swipe view and it work nice. So now i want to add button on Tab1 and when clicked has to send data to Tab2.
I know there is the issue of using interface but honestly i don't know how to add it on these codes and work provide am completely new to the android.
so far i have tried my best on these links Communication between SlidingTabLayout tabs, How to pass data from one swipe tab to another? and How can I communicate/pass data through different Fragments with Swipe Tab? but i fail.
Any one help please to make it work on every stage , i mean from Tab1 ->Mainactivity->Tab2
thanks alot
Here are the codes after i edit the question
Fragment1
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TabFragment1 extends Fragment implements AdapterView.OnItemSelectedListener{
Button send;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.tab_fragment_1, container, false);
send=(Button)v.findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// value to be sent to the TabFragment2 on button click
String value=" My Data";
}
});
return v;
}
}
Fragment2
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TabFragment2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_fragment_2, container, false);
//Display value from TabFragment1
textview.setText(value);
}
}
Interface class
public Interface FragmentCommunication
{
public void printMessage(String message);
}
MainActivity
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity implements FragmentCommunication{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
public void printMessage(String message)
{
Toast.makeText(MainActivity.this,message,Toast.LENGTH_LONG).show();
}
}
Adapter Class
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
TabFragment1 tab1 = new TabFragment1();
return tab1;
case 1:
TabFragment2 tab2 = new TabFragment2();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
so after posting more code I'm answering:
Implement some FragmentCommunication for both your Fragments:
//public class TabFragment1 extends Fragment implements FragmentCommunication{
public class TabFragment2 extends Fragment implements FragmentCommunication{
//public static final String TAG="TabFragment1";
public static final String TAG="TabFragment2";
...
#Override
public void onActivityCreated (Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
if(getActivity() instanceOf MainActivity)
((MainActivity) getActivity()).registerFragmentCommunication(
TAG, this);
}
#Override
public void printMessage(String message){
Toast.makeText(getActivity(), TAG+" says: "+message,
Toast.LENGTH_SHORT).show();
}
}
note this line inside onActivityCreated:
((MainActivity) getActivity()).registerFragmentCommunication(TAG, this);
this means implemented FragmentCommunication, TAG will be unique key/name of Fragment and whole method is registration of your interface in Activity. so now you have to add registerFragmentCommunication method to your MainActivity and keep reference to passed interfaces, e.g. in HashMap:
HashMap<String, FragmentCommunication> fragmentCommunications =
new HashMap<String, FragmentCommunication>();
...
public void registerFragmentCommunication(String key, FragmentCommunication fc){
fragmentCommunications.put(key, fc);
}
so now you can access each FragmentCommunication of both fragments from your MainActivity, e.g by using method like this:
public void callFragmentCommunication(String key, String msg){
if(fragmentCommunications.get(key)!=null)
fragmentCommunications.get(key).printMessage();
}
callFragmentCommunication(TabFragment1.TAG, "hi!");
callFragmentCommunication(TabFragment2.TAG, "hi!");
method is public, so Fragments can call it simply like this:
//inside TabFragment1
if(isAdded() && getActivity()!=null &&
getActivity() instanceOf MainActivity &&
!getActivity().isFinishing())
((MainActivity) getActivity()).callFragmentCommunication(
TabFragment2.TAG, "hi!");
this will show Toast with text: "TabFragment2 says: hi!", which was called inside TabFragment1. now you may pass another kind of data as well :)
there is much more methods like communicating through FragmentStatePagerAdapter like here, passing Bundle arguments where fragments are initialized, additional feedback interfaces (e.g. returning true/false when message was passed) etc. Above is just very simplified way, good luck with improving it! :)
I want to create a viewpager which contains 2 tabs, I have 3 layout:
This is activity_chart.xml that contains paper:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
This is AccountsActivityChart.java:
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import com.rastari.salar.mymetarialbank.R;
import com.rastari.salar.mymetarialbank.adapter.TabsPagerAdapter;
/**
* Created by Salar on 9/5/2015.
*/
public class AccountsActivityChart extends FragmentActivity implements ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Accounts Activity", "Chart Activity" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chart);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
}
this is TabsPagerAdapter.java class:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
* Created by Salar on 26/4/2015.
*/
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Accounts Activity fragment activity
return new AccountsActivityFragment();
case 1:
// Chart Activity activity
return new ChartActivityFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 2;
}
}
this is AccountsActivityFragment.java:
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.rastari.salar.mymetarialbank.R;
/**
* Created by Salar on 25/4/2015.
*/
public class AccountsActivityFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_accounts_activity, container, false);
return rootView;
}
}
this is ChartActivityFragment.java:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.rastari.salar.mymetarialbank.R;
/**
* Created by Salar on 9/5/2015.
*/
public class ChartActivityFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_chart_activity, container, false);
return rootView;
}
}
this is manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rastari.salar.mymetarialbank" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/MyMetarialBank">
<activity
android:name=".activity.Login"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".activity.MainActivity"/>
<activity android:name=".activity.AccountsActivityChart"/>
</application>
</manifest>
When I run the app I get this Error:
Attempt to invoke virtual method 'void
android.app.ActionBar.setHomeButtonEnabled(boolean)' on a null object
reference
How can I fix this?
I think you have applied the theme which is having no action bar. This is why when you are getting the actionbar instance, it will be null and you are calling the setHomeButtonEnabled on on the null actionbar instance. That is why you are getting the error.
try actionBar = getSupportActionBar();
instead of actionBar = getActionBar();
In my app I need the possibility to create a dynamic listview populated by elements extracted from the db.
This in itself wouldn't be a big problem (there are a lot of tutorials about it, like this one), problem is, my activity is divided in tabs and, therefore, I have a Fragment for each tab (the code it's basically this).
There are lots of methods that I can't use in a Fragmentand I'm honestly pretty stuck.
How can I implement a dynamic layout solution inside a fragment?
Edit: code for clarity:
Fragment:
package it.sii.mywaiter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class AllerFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.aller_layout, container, false);
return rootView;
}
}
Activity:
package it.sii.mywaiter;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
//import android.widget.*;
import android.app.ActionBar;
public class UserPrefActivity extends FragmentActivity implements ActionBar.TabListener {
private ViewPager viewPager;
private PrefPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Ingredienti preferiti", "Allergie e Intolleranze" };
int tabsnum = tabs.length;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_pref_layout);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new PrefPagerAdapter(getSupportFragmentManager());
mAdapter.setCount(tabsnum);
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
Adapter
package it.sii.mywaiter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class PrefPagerAdapter extends FragmentPagerAdapter {
private int count = 0;
public PrefPagerAdapter(FragmentManager fm) {
super(fm);
}
public void setCount(int count){
this.count = count;
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new PrefFragment();
case 1:
return new AllerFragment();
}
return null;
}
#Override
public int getCount() {
return count;
}
}
Fragment's layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#fa6a6a" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="test test"
android:textSize="20sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
As you said, you have Fragments. Every Fragment has its own class so you can create a CustomArrayAdapter and the use it in the Fragments onCreate Method. Inside the Fragment get your ListView, which you defined in the xml File for this Fragment, with findViewByID and then set its Adapter with setAdapter(new YourCustomAdapterClass()); then you have your custom dynamic ListView in a Fragment.
i use "Actionbarsherlock" in my project
First i import "Actionbarsherlock" in my project then delete folder "libs"
But my question is how can I change the code below؟
mainactivity
package info.androidhive.tabsswipe;
import info.androidhive.tabsswipe.adapter.TabsPagerAdapter;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
#SuppressLint("NewApi")
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "water"," time" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}}
MoviesFragment
package info.androidhive.tabsswipe;
import info.androidhive.tabsswipe.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MoviesFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_movies,container,false);
return rootView;
}
}
GamesFragment
package info.androidhive.tabsswipe;
import info.androidhive.tabsswipe.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class GamesFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_games, container,false);
return rootView;
}}
TabsPagerAdapte
package info.androidhive.tabsswipe;
import info.androidhive.tabsswipe.GamesFragment;
import info.androidhive.tabsswipe.MoviesFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Games fragment activity
return new GamesFragment();
case 1:
// Movies fragment activity
return new MoviesFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 2;
}}
Please help me to solve this problem
bro remove your email adress from the question.Now coming to your question your actionbar should be an object of supportActionbar.Change the getActionBar() to getSupportActionBar()l.And secondly,your main activity should extend sherlockActivity.Lastly,change the importation from the android actionbar to the sherlock actionbar
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();