Updating ui in a fragment - android

I can't seem to update the ui in one of my fragments, I'm not sure why. I have a main activity which should send some json to the fragment and update the UI with the data from the JSON object. I'm sending the json over successfully and I can log the data in the Fragment which I have sent over. I am just not able to update the textbox value in the UI.
In my mainactivity
MainPageFragment myFragment = new MainPageFragment();
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Create adapter that will return a fragment for each section of app
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public void onSuccess(JSONObject user) {
//This seems to be all I need
myFragment.grabJSON(user);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle (int position) {
return titles[position];
}
#Override
public Fragment getItem(int position) {
if (position == 1) {
return new PreferenceFragment() {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.settings_preferances);
}
};
}
else {
return myFragment;
}
}
}
In my MainFragment.java
public void grabJSON(JSONObject object){
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
TextView usernameTextView = (TextView) getView().findViewById(R.id.usernameview);
CharSequence val = usernameTextView.getText();
Log.d("value", val.toString());
usernameTextView.setText("NEW TEXT");//Set the Text
val = usernameTextView.getText();
Log.d("value", val.toString());
}
});
}
The fact that it sends the json is irrelevant, according to the log, my value of the textbox is changing but the actual UI is not changing.
I'm adding here the xml for the mainactivity
<?xml version="1.0" encoding="utf-8"?>
<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=".MainActivity" >
<android.support.v4.view.PagerTabStrip
android:id="#+id/pager_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:textColor="#fff"/>
<FrameLayout
android:id="#+id/fragment_placeholder"
android:layout_width="fill_parent"
android:layout_height="fill_parent" ></FrameLayout>
</android.support.v4.view.ViewPager>
This has been updated with correct code, turns out I was defining the fragment twice
Thank you all,
Tom

Your fragment is getting added twice.
It's added via the layout XML file, and then you do a fragment transaction to add it aw well. Adding fragments via layout doesn't work as well as it should, so you should put in a placeholder view and then add the fragment via the fragment manager. That should clear everything up.

I'm guessing you dont add the fragment in the activity?
FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MainPageFragment fragment = new MainPageFragment ();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();

Related

findFragmentById returns null always

I have one MainActivity and two fragments FGames and FGameDetail. I am trying to communicate between them so that when an item is clicked in the FGames it passes GameEntity to MainActivity and it updates the FGameDetail. I have separate layout created for phone and tablet.
In my MainActivity where I am controlling if the FGameDetail fragment exists in the layout update the view. but findFragmentById always returns null for both FGames and FGameDetails.
Here is my layout for Phones and Tablets
layout\activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/games_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.rao.igttest.MainActivity">
<fragment
android:id="#+id/fragment_fGames"
android:name="com.example.rao.igttest.Games.View.FGames"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
layout-large-land\activity_main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/fragment_fGames"
android:name="com.example.rao.igttest.Games.View.FGames"
android:layout_width="400dp"
android:layout_height="wrap_content" />
<fragment
android:id="#+id/fragment_fGameDetail"
android:name="com.example.rao.igttest.Games.View.FGameDetail"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity
public class MainActivity extends AppCompatActivity implements FGames.OnGameSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//FGames fGames = new FGames();
//getSupportFragmentManager().beginTransaction().add(R.id.games_container, fGames).commit();
}
#Override
public void onGameSelected(GameEntity gameEntity) {
FragmentManager fragmentManager = getSupportFragmentManager();
FGameDetail gameDetailFrag = (FGameDetail) fragmentManager
.findFragmentById(R.id.fragment_fGameDetail);
Fragment gameFrag = fragmentManager.findFragmentById(R.id.fragment_fGames);
if (gameDetailFrag == null) {
//TODO Open a new intent
} else {
// DisplayFragment (Fragment B) is in the layout (tablet layout),
// so tell the fragment to update
FGameDetail fGameDetail = new FGameDetail();
fGameDetail.updateContent(gameEntity);
}
}
}
Your help and suggestions is much appreciated.
EDIT
FGAMES
#Override
public void initRecyclerView(List<GameEntity> gameEntities) {
gamesAdapter = new GamesAdapter(getActivity(), gameEntities);
rvGames.setAdapter(gamesAdapter);
rvGames.setLayoutManager(new LinearLayoutManager(getActivity()));
}
GamesAdapter
//Constructor
public GamesAdapter(Context context, List<GameEntity> gameEntities) {
layoutInflater = LayoutInflater.from(context);
this.data = gameEntities;
this.context = context;
}
#OnClick(R.id.row_container)
void rowClick(){
//I think as I am creating a new instance here as I dont have referencec to GamesPresenter in adapter as I am calling it directly from FGames
GamesPresenter gamesPresenter = new GamesPresenterImpl();
gamesPresenter.showGameDetail(data.get(getLayoutPosition()));
Toast.makeText(context, "itemClicked " + data.get(getLayoutPosition()), Toast.LENGTH_SHORT).show();
}
GamesPresenterImpl
#Override
public void showGameDetail(GameEntity gameEntity) {
GamesView gamesView = new FGames();
gamesView.onListItemClick(gameEntity);
}
FGames
#Override
public void onListItemClick(GameEntity gameEntity) {
OnGameSelectedListener mListener = new MainActivity();
mListener.onGameSelected(gameEntity);
}
public interface OnGameSelectedListener{
public void onGameSelected(GameEntity gameEntity);
}
MainActivity - OnGameSelected.
#Override
public void onGameSelected(GameEntity gameEntity) {
FragmentManager fragmentManager = getSupportFragmentManager();
FGameDetail gameDetailFrag = (FGameDetail) fragmentManager
.findFragmentById(R.id.fragment_fGameDetail);
Fragment gameFrag = fragmentManager.findFragmentById(R.id.fragment_fGames);
if (gameDetailFrag == null) {
} else {
// DisplayFragment (Fragment B) is in the layout (tablet layout),
// so tell the fragment to update
FGameDetail fGameDetail = new FGameDetail();
fGameDetail.updateContent(gameEntity);
}
}
Are you sure you are not doing new MainActivity().onGameSelected(object)?
If you using the Interactor fragment pattern, you must use the instance of the Activity you already have in the class.
Also, this line dont update the screen cause you creating a new instance of the fragment that will never be added:
FGameDetail fGameDetail = new FGameDetail();
fGameDetail.updateContent(gameEntity);
There is a instance already in screen so:
gameDetailFrag.updateContent(gameEntity);

Open fragment from Fragment on button click

I am having trouble opening a fragment from within another fragment on the click of a button. Everything seems to make sense (to me) and I have tried playing about with my code (changing the layouts, replacing fragments etc) but nothing is working.
Here is my RoleFragment.java (The fragment which contains the button)
public class RolesFragment extends Fragment implements View.OnClickListener {
GridView gridView;
ArrayList<Players> playersList;
MyAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_viewroles, container, false);
gridView = (GridView) view.findViewById(R.id.gv_players);
Button nightround = (Button) view.findViewById(R.id.buttonNightRound);
nightround.setOnClickListener(this);
DatabaseHelper databaseHelper = new DatabaseHelper(getActivity());
playersList = new ArrayList<Players>();
playersList = databaseHelper.getPlayers();
adapter = new MyAdapter(getActivity(), playersList);
gridView.setAdapter(adapter);
return view;
}
#Override
public void onClick(View v) {
Fragment fragment = null;
switch (v.getId()) {
case R.id.buttonNightRound:
fragment = new NightRound();
replaceFragment(fragment);
break;
}
}
public void replaceFragment(Fragment someFragment) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, someFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
And this is my fragment_viewroles.xml file.
<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.tuss.mafia.GameActivity" >
<Button
android:id="#+id/buttonNightRound"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Night Round"
android:onClick="FragmentNightRoundClick"
android:clickable="true"
android:layout_weight="2"/>
<GridView
android:id="#+id/gv_players"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:columnWidth="150dp"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:gravity="center"
android:layout_below="#id/buttonNightRound">
</GridView>
</RelativeLayout>
The trouble is, when I click the button nothing happens.
There some problems here.
First, you have to add a container with the id R.id.fragment_container inside your fragment like FrameLayout
which will store your new fragment.
If your want to open a fragment as a new screen, you have to put it inside a new activity. Fragments are piece of screens and should not be used without activities or view pagers.
Have a look at the Android deverlopers page: http://developer.android.com/training/basics/fragments/communicating.html#DefineInterface
Basically, you define an interface in your Fragment A, and let your Activity implement that Interface. Now you can call the interface method in your Fragment, and your Activity will receive the event. Now in your activity, you can call your second Fragment to update the textview with the received value
// You Activity implements your interface
public class YourActivity implements FragmentA.TextClicked{
#Override
public void sendText(String text){
// Get Fragment B
FraB frag = (FragB)
getSupportFragmentManager().findFragmentById(R.id.fragment_b);
frag.updateText(text);
}
}
// Fragment A defines an Interface, and calls the method when needed
public class FragA extends Fragment{
TextClicked mCallback;
public interface TextClicked{
public void sendText(String text);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (TextClicked) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement TextClicked");
}
}
public void someMethod(){
mCallback.sendText("YOUR TEXT");
}
#Override
public void onDetach() {
mCallback = null; // => avoid leaking, thanks #Deepscorn
super.onDetach();
}
}
// Fragment B has a public method to do something with the text
public class FragB extends Fragment{
public void updateText(String text){
// Here you have it
}
}
Try something like the following:
Fragment fragment = OtherFragment.newInstance();
android.support.v4.app.FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container_layout, fragment, "OtherFragment");// give your fragment container id in first parameter
transaction.addToBackStack(null); // if written, this transaction will be added to backstack
transaction.commit();

PagerSlidingTabStrip isn't working, but my code seems OK to me

I've tried to implement PagerSlidingTabStrip to my app but it just isn't working. I did everything that is done in the sample but it isn't working. The tab indicator just isn't moving as it is supposed to and the app isn't crashing. Basically nothing is happening. I have no idea what is wrong.
MainActivity code
public class MainActivity extends FragmentActivity implements TabListener {
ActionBar aBar;
ViewPager vPager;
PagerAdapter pAdapter;
PagerSlidingTabStrip slidingTabStrip;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Action Bar
aBar = getActionBar();
aBar.setTitle("Beautiful Voice Recorder");
aBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Variables
slidingTabStrip = (PagerSlidingTabStrip) findViewById(R.id.slidingTabs);
vPager = (ViewPager) findViewById(R.id.pager);
pAdapter = new PagerAdapter(getSupportFragmentManager());
// Tabs
vPager.setAdapter(pAdapter);
slidingTabStrip.setViewPager(vPager);
aBar.addTab(aBar.newTab().setText("Record").setTabListener(this));
aBar.addTab(aBar.newTab().setText("Library").setTabListener(this));
vPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
LibraryFragment listViewFragment = (LibraryFragment)pAdapter.instantiateItem(vPager, 1);
RecordFragment recordFragment = (RecordFragment)pAdapter.instantiateItem(vPager, 0);
listViewFragment.updateComponents();
// Pause mp if it's playing and tabs are switched just in case
if (listViewFragment.mp.isPlaying())
{
listViewFragment.mp.pause();
listViewFragment.playPause.setBackgroundResource(R.drawable.play_button_selector);
}
if (recordFragment.isRecording)
{
recordFragment.stopRecording();
}
aBar.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) {
vPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
class PagerAdapter extends FragmentPagerAdapter{
String[] pageTitles = { "Record", "Library" };
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
Fragment fragment = new Fragment();
if (arg0 == 0)
{
fragment = new RecordFragment();
}
if (arg0 == 1)
{
fragment = new LibraryFragment();
}
return fragment;
}
#Override
public int getCount() {
return pageTitles.length;
}
#Override
public CharSequence getPageTitle(int position) {
return pageTitles[position];
}
}
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/slidingTabs"
android:layout_width="match_parent"
android:layout_height="48dip" />
<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" />
</RelativeLayout>
Does anyone have any idea why my code is not working?
I think you didn't locate ViewPager even if it's RelativeLayout.
so try this code that i'm using. I hope it will be helpful for you.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip"
/>
<com.flitto.app.widgets.MainViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/tabs"
tools:context=".MainTabActivity"/>
</RelativeLayout>
I found where the problem was lying after I took a deeper look at the sample code. The problem was the fact that I still had the previous ActionBar tabs left in the code and those were overlapping the PagerSlidingTabStrip tabs so that I didn't see them.
All I had to do was to remove every reference to ActionBar tabs and it worked!

Google Maps MapFragment causing the app to crash

I am fairly new to android programming but what I am trying to do seems fairly simple though. I have this setup with 4 different tabs in the action bar, the first should display a Fragment with the Google maps API and the others some other stuff i haven't done yet. Following some tutorials online I managed to get the functionality I wanted for the tabs and get the map to appear.
The app is working fine when changing from the initial tab with the map (tab 1) to any other, but when trying to come back it crashes. Weirdly enough when the map fragment is in one of the tabs it makes the second tab crash as well on some transitions, in the image bellow the transitions shown as blue arrows work fine, while the ones with yellow arrows make the app crash.
http://imageshack.com/a/img839/4796/kf7w.png
If I change the first tab fragment for one of the others all the transitions work fine again, therefore I think the problem must indeed be with the map fragment.
My code is as follows:
MainActivity.java
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
tabs = getResources().getStringArray(R.array.tab_names);
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 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 void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
TabsPagerAdapter.java
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index){
case 0:
return new GoogleMapsFragment();
case 1:
return new SampleFragment();
case 2:
return new ContactFragment();
case 3:
return new WhoFragment();
default:
Log.e("switch", "default");
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 4;
}
}
GoogleMapsFragment.java
public class GoogleMapsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_map, container, false);
return rootView;
}
#Override
public void onDestroyView() {
super.onDestroyView();
Fragment f = (Fragment) getFragmentManager().findFragmentById(R.id.map);
if (f != null) {
getFragmentManager().beginTransaction().remove(f).commit();
}
}
}
And the xml files:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="#ffff0000"
android:id="#+id/mainLayout"
android:tag="#+id/mainLayoutTag" >
<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:tag="pagerTag">
</android.support.v4.view.ViewPager>
</RelativeLayout>
activity_map.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/mapLayout"
android:tag="mapLayoutTag" >
<fragment android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"
android:tag="gMaps"/>
</RelativeLayout>
The other java classes are pretty much empty and the other xml files only contain the default RelativeLayout.
Any suggestion as to what I could do to fix this?
Thanks for your time reading all of that :)
EDIT:
Forgot to put the crash error:
02-10 23:42:01.723: E/AndroidRuntime(7221): Caused by:
java.lang.IllegalArgumentException: Binary XML file line #9:
Duplicate id 0x7f05000a, tag gMaps, or parent id 0x7f050009 with another
fragment for com.google.android.gms.maps.MapFragment
Well managed to solve this only by switching the position of the super call in the onDestroy() function. It seems I needed to first destroy or unassign the fragment from its parent to make it work. Heres the new onDestroy() code if anyone is still having the same problem:
#Override
public void onDestroyView() {
userMarker.remove();
Fragment f = (Fragment) getFragmentManager().findFragmentById(R.id.map);
if (f != null) {
getFragmentManager().beginTransaction().remove(f).commit();
}
super.onDestroyView();
}
After loads of search, finally I found this tutorial : Using an Android MapView inside of a Fragment
and it works awesome !!! hopefully it helps your guys !

how to set up ListFragment properly?

I try to create tabs with ListFragment in it. I've tried several different appoaches but neither of them works. I don't know how to set container for ListFragment obkect properly.
Here is java code.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tabOne = actionBar.newTab().setText("ONE");
ActionBar.Tab tabTwo = actionBar.newTab().setText("TWO");
tabParkCinema.setTabListener(new tabListener());
tab28Cinema.setTabListener(new tabListener());
actionBar.addTab(tabOne);
actionBar.addTab(tabTwo);
}
protected class tabListener implements ActionBar.TabListener {
ParkFragment firstFragment;
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
switch (tab.getPosition()){
case 0:
if (firstFragment == null){
firstFragment = new ParkFragment();
System.out.println("initialized");
ft.add(R.id.cont, firstFragment,"FIRST");
}
else{
ft.attach(firstFragment);
}
break;
case 1:
if (firstFragment == null){
firstFragment = new ParkFragment();
ft.add(R.id.cont,firstFragment,"SECOND");
}
else{
ft.attach(firstFragment);
}
break;
}
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
};
public class ParkFragment extends ListFragment {
private ArrayList<Cinemas> cinema;
private CinemasAdapter cinemaAdapter;
private View v;
//private ListView list;
#Override
public View onCreateView(LayoutInflater in, ViewGroup gr, Bundle savedInstanceState) {
v = in.inflate(R.id.listing1, gr,false);
super.onActivityCreated(savedInstanceState);
cinema = new Handler().handle();
cinemaAdapter = new CinemasAdapter(MainActivity.this, R.layout.movie_data_row, cinema);
setListAdapter(cinemaAdapter);
return gr;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Cinemas movie = cinemaAdapter.getItem(position);
Intent intent = new Intent (MainActivity.this, More.class);
intent.putExtra("Cinemas", movie);
intent.putExtra("data", movie.getBitmap());
Bundle translateBundle =
ActivityOptions.makeCustomAnimation(MainActivity.this,
R.anim.slide_in_left, R.anim.slide_out_left).toBundle();
startActivity (intent, translateBundle);
}
}
}
And activity_main.XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/cont"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id = "#+id/listing1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
Thank you for reading, any help will be appreciated!
1) Create a FragmentManager object.
2) Use method beginTransaction() on this object to create a FragmentTransaction object.
3) Add fragment with the method add(int containerViewId, Fragment fragment, String tag) on the FragmentTransaction object.
In this method, you put a reference to the id of the container, a new ListFragment (or the class you have writen) and a tag (to easily get a reference to the ListFragment if needed).
Note that you have to change your xml layout. You can add a FrameLayout with an id. And then, give this id to the method add() of your FragmentTransaction object.
EDIT
Example of code:
public class ContentActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
//your action bar stuff
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.parkfragment, new ParkFragment(), "locations");
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentTransaction.commit();
}
public class ParkFragment extends ListFragment {
//your methods
}
protected class tabListener implements ActionBar.TabListener {
//your methods
}
}
Your xml would look like:
<?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:baselineAligned="false"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/parkfragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>

Categories

Resources