How to replace fragment , which already has some view? - java

I have this fragment_settings.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearlayout_settings_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textview_my_account"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="My Account" />
<TextView
android:id="#+id/textview_my_account_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="List" />
</LinearLayout>
with following code:
public class SettingsFragment extends Fragment implements Constants, OnClickListener{
public static SettingsFragment newInstance() {
SettingsFragment f = new SettingsFragment();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
container.setPadding(0, 0, 0, 0);
final View view = inflater.inflate(R.layout.fragment_settings, container,
false);
initViews(view);
return view;
}
private void initViews(View view) {
// TODO Auto-generated method stub
TextView textView = (TextView)view.findViewById(R.id.textview_my_account);
textView.setOnClickListener(this);
TextView textView1 = (TextView)view.findViewById(R.id.textview_my_account_1);
textView1.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
FragmentManager fragmentManager = getChildFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
switch (v.getId()) {
case R.id.textview_my_account:
SettingsContactDetailFragment settingsContactDetailFragment = SettingsContactDetailFragment.newInstance();
settingsContactDetailFragment.setRetainInstance(true);
fragmentTransaction.replace(R.id.linearlayout_settings_fragment, settingsContactDetailFragment);
fragmentTransaction.addToBackStack(FragmentEnum.SETTINGS_CONTACT_DETAIL_FRAGMENT);
fragmentTransaction.commit();
break;
case R.id.textview_my_account_1:
SettingsContactListFragment settingsContactListFragment = SettingsContactListFragment.newInstance();
settingsContactListFragment.setRetainInstance(true);
fragmentTransaction.replace(R.id.linearlayout_settings_fragment, settingsContactListFragment);
fragmentTransaction.addToBackStack(FragmentEnum.SETTINGS_CONTACT_LIST_FRAGMENT);
fragmentTransaction.commit();
break;
}
}
}
i tried this working. But when i use fragmentTransaction.replace then fragment is added with views which are already in fragment_settings.xml
LinearLayout linearLayout = (LinearLayout)view.findViewById(R.id.linearlayout_settings_fragment);
linearLayout.removeAllViews();
but why below not work ?
fragmentTransaction.replace(R.id.linearlayout_settings_fragment, settingsContactListFragment);

FragmentTransaction.replace method removes only the previously added Fragment's view from the container. It does not remove all the views belonging to the container. That's why it gets appended to the other 2 TextViews.
If you want to replace the TextView, then they should be part of another Fragment, which can be added to R.id.linearlayout_settings_fragment initially and latter replace it with SettingsContactDetailFragment or SettingsContactListFragment fragments.

Related

Android Fragment Always NULL When Accessing From ViewPagerAdapter

The Problem:
In my onCreate() on my main activity, I am trying to set the text value of a TextView in my fragment which is displayed by a viewpager. When I try to get my fragment instance, It always returns null.
Solutions I Tried:
Almost every solution related to this problem on SO gives me the same result(NPE).
My Code is below as well as some explanation...
Home.java Activity (My Main Activity):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Show the home layout
setContentView(R.layout.home);
// Setup the toolbar
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Now setup our tab bar
TabLayout tabLayout = (TabLayout)findViewById(R.id.homeTabs);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
// Setup the view pager
ViewPager viewPager = (ViewPager)findViewById(R.id.viewPager);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager);
// Start our service controller
Intent startServiceController = new Intent(this, ServiceController.class);
startService(startServiceController);
Fragment viewFragment = pagerAdapter.getRegisteredFragment(viewPager.getCurrentItem());
if(viewFragment == null){
Log.v("Fragment", "NULL");
}
}
After setting up the pageAdapter and viewpager, I try to access the fragment thats being shown. The code for my PagerAdapter is below...
PagerAdapter:
public class PagerAdapter extends SmartFragmentStatePagerAdapter {
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ParkListFragment();
case 1:
return new MapFragment();
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
CharSequence title;
switch (position){
case 0:
title = "Spaces Near You";
break;
case 1:
title = "Map";
break;
default:
title = "N/A";
break;
}
return title;
}
}
SmartFragmentStatePagerAdapter:
public abstract class SmartFragmentStatePagerAdapter extends FragmentStatePagerAdapter {
// Sparse array to keep track of registered fragments in memory
private SparseArray<Fragment> registeredFragments = new SparseArray<>();
public SmartFragmentStatePagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Register the fragment when the item is instantiated
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
// Unregister when the item is inactive
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
// Returns the fragment for the position (if instantiated)
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
I really don't understand what the issue is. I have tried many things. What I don't want to use is this:
String tag="android:switcher:" + viewId + ":" + index;
ParkListFragment.java:
public class ParkListFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.park_list_fragment, container, false);
}
}
ParkList Fragment Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerInParent="true">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/confidenceText"
android:textAlignment="center"
android:textSize="24sp"
android:textColor="#android:color/primary_text_light"
android:padding="10dp"/>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerInParent="true">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/activityText"
android:textAlignment="center"
android:textSize="24sp"
android:textColor="#android:color/primary_text_light"
android:padding="10dp"/>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
Stack Trace: Pastebin
So after hours of trial and error, the only thing that worked for me was this SO post:
ViewPager Fragments are not initiated in onCreate

How to go one Fragment to another when I will click on TextView Id?

How to go one Fragment to another when I will click on TextView Id?
Error shows:
java.lang.ClassCastException: com.example.tripigator.Overview cannot be cast to android.app.Activity.
and error comes from these lines :
TextView overview = (TextView) findViewById(R.id.txt_overview);
overview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProjectOverview.this, Overview.class);
startActivity(intent);
}
});
So please anybody help me how to move from one fragment to another by clicking text item.
ProjectOverview class :
public class ProjectOverview extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project_overview);
initialingpaging();
TextView overview = (TextView) findViewById(R.id.txt_overview);
overview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProjectOverview.this, Overview.class);
startActivity(intent);
}
});
}
private void initialingpaging() {
// TODO Auto-generated method stub
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, Overview.class.getName()));
fragments.add(Fragment.instantiate(this, Highlight.class.getName()));
mPageAdapter = new PageAdapter(this.getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager)findViewById(R.id.viewpager);
pager.setAdapter(mPageAdapter);
}
}
Two Fragment Classes:
public class Overview extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState)
{
if(container == null)
{
return null;
}
return (LinearLayout) inflater.inflate(R.layout.overview,container,false);
}
}
public class Highlight extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
if(container == null)
{
return null;
}
return (LinearLayout) inflater.inflate(R.layout.highlight,container,false);
}
}
Layout Interface:
<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" >
<LinearLayout
android:id="#+id/project_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="65dp"
android:gravity="center" >
<TextView
android:id="#+id/txt_overview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold"
android:layout_marginLeft="12dp"
android:text="Overview" />
<TextView
android:id="#+id/txt_highlite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold"
android:layout_marginLeft="12dp"
android:text="Highlight" />
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
You can't initiate the fragment using Intent.Try this it helps.
Fragment fragment = null;
FragmentManager frgManager;
FragmentTransaction ft;
fragment = new Overview();
ft = frgManager.beginTransaction();
ft.replace(R.id.frame_content, fragment);
ft.addToBackStack(null);
ft.commitAllowingStateLoss();
If you use View-Pager
your_ViewPager.setCurrentItem(position)
you should not use intent in fragment to move another fragment
and check this for whole example http://examples.javacodegeeks.com/android/core/app/fragment/android-fragments-example/
use this.
((yourfragmentActivity) getActivity()).setCurrentItem(1,//desired activity 0=first 1= second and so on
true);
insted
Intent intent = new Intent(ProjectOverview.this, Overview.class);
startActivity(intent);

Fragment move from one Fragment to another by sliding as well as button click

I have a view that consist of three buttons, a fragment and a ViewPager. If you press button1 then fragment one should be shown. If you press button two then fragment two is shown. If you press button three then fragment Three is shown. As well as sliding should happen from from fragment one to fragment tow and fragment two to fragment three. The problem is that If I execute separate fragment and ViewPager it runs. But I want both in single layout. Error show in this line : fragmentTransaction.replace(R.id.fragment_place, fr); and error is :The method replace(int, Fragment) in the type FragmentTransaction is not applicable for the arguments (int, Fragment);
so please anybody tell me how to fix this problem. I used both fragment as well as ViewPager. Can I use both in single layout.
How can I solve this problem so both will happen like sliding as well as fragment move by button click?
MainActivity.java class
public class MainActivity extends FragmentActivity {
private PageAdapter mPageAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpages_layout);
initialingpaging();
}
private void initialingpaging() {
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, Fragment1.class.getName()));
fragments.add(Fragment.instantiate(this, Fragment2.class.getName()));
fragments.add(Fragment.instantiate(this, Fragment3.class.getName()));
mPageAdapter = new PageAdapter(this.getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager)findViewById(R.id.viewpager);
pager.setAdapter(mPageAdapter);
}
public void selectFrag(View view) {
Fragment fr;
switch (view.getId()) {
case R.id.button1:
fr = new Fragment1();
break;
case R.id.button2:
fr = new Fragment2();
break;
case R.id.button3:
fr = new Fragment3();
break;
default:
break;
}
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();
}
}
// PageAdapter.java class
public final class PageAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public PageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
// TODO Auto-generated constructor stub
this.fragments = fragments;
}
#Override
public Fragment getItem(int arg0) {
return this.fragments.get(arg0);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
//Fragment1.java, Fragment2.java and Fragment3.java class are like below code:
public class Fragment3 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(container == null) {
return null;
}
return (LinearLayout) inflater.inflate(R.layout.fragment3_layout,container,false);
}
}
//fragment1_layout.xml, fragment2_layout.xml and fragment3_layout.xml are like similar code:
<?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:background="#FF0000"
android:orientation="vertical" >
</LinearLayout>
//viewpages_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="110dp"
android:layout_height="wrap_content"
android:onClick="selectFrag"
android:text="Fragment 1" />
<Button
android:id="#+id/button3"
android:layout_width="110dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:onClick="selectFrag"
android:text="Fragment 3" />
<Button
android:id="#+id/button2"
android:layout_width="110dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:onClick="selectFrag"
android:text="Fragment 2" />
<android.support.v4.view.ViewPager
android:id="#+android:id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="100dp"/>
<fragment
android:id="#+id/fragment_place"
android:name="com.example.viewpageexample1.Fragment1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="70dp" />
</RelativeLayout>
Make sure that you have imported the right Fragment class.
There is Fragment class in android.app and in android.support.v4.app.
I think you are using android.support.v4.app.Fragment and fragmentTransaction.replace(int, Fragment) method uses android.app.Fragment.
So to make it work, change getFragmentManager() to getSupportFragmentManager() and fix imports to use classes from android.support.v4.app.
I think instead of 3 buttons, you should try action bar tabs..here is the code for the same.
add implements clause to your class definition.
public class MainActivity extends FragmentActivity implements ActionBar.TabListener{
Initialize the following inside your class
ActionBar bar;
ViewPager viewpager;
PageAdapter ft;
In onCreate, replace your code with this.
viewpager = new ViewPager(this);
viewpager.setId(R.id.pager);
setContentView(viewpager);
ft = new FragmentPageAdapter(getSupportFragmentManager());
viewpager.setAdapter(ft);
final ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
bar.addTab(bar.newTab().setText("Fragment1").setTabListener(this));
bar.addTab(bar.newTab().setText("Fragment2").setTabListener(this));
bar.addTab(bar.newTab().setText("Fragment3").setTabListener(this));
viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
bar.setSelectedNavigationItem(arg0);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.start_screen, menu);
return true;
}
#Override
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
viewpager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
}
In viewpager_layout, only have this. Remove everything else.
<android.support.v4.view.ViewPager
android:id="#+android:id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="100dp"/>;
PageAdapter code should be like this.
public class PageAdapter extends FragmentPagerAdapter {
public PageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
switch (arg0)
{
case 0:
return new Fragment1();
case 1:
return new Fragment2();
case 2:
return new Fragment3();
default:
break;
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 3;
}
}
Your Fragment xml / change background color between 3 xmls to see results.
<?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:id="#+id/fragment1"
android:orientation="vertical"
android:background="#00FF33">
</LinearLayout>
Your Fragment1/2/3 code
public class Fragment1 extends Fragment {
View myFragmentView;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.fragment1, container, false);
return myFragmentView;
}
}
checkout http://semycolon.blogspot.in/2014/11/first-android-app-step-5-homescreen.html. It has a complete explanation with source code.

Open new Fragment from button in other Fragment

I have two fragments. In the first one, I have a button and I would like to change to another fragment by clicking button.
Here is my code:
FirstFragment
public class FirstFragement extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View ios = inflater.inflate(R.layout.activity_annuncio, container, false);
Button bottAnn = (Button) ios.findViewById(R.id.bNuovoAnnuncio);
bottAnn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
return ios;
}
}
the Firstxml code:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<Button
android:id="#+id/bNuovoAnnuncio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nuovo Annuncio"
android:background="#drawable/button"
android:textColor="#ffffff"
android:layout_marginTop="5dp"/>
<ListView
android:id="#+id/listView1"
android:layout_width="294dp"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
</ScrollView>
SECOND FRAGMENT
public class SecondFragement extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View ios = inflater.inflate(R.layout.activity_annuncio, container, false);
return ios;
}
}
the Secondxml code:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<ListView
android:id="#+id/listView1"
android:layout_width="294dp"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
</ScrollView>
How I can solve it?
You have to replace your new fragment in existing container.
Try this, in first fragment :
Button bottAnn = (Button) ios.findViewById(R.id.bNuovoAnnuncio);
bottAnn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SecondFragement frag = new SecondFragement();
getActivity().getFragmentManager().beginTransaction().replace(//Your container, frag).commit();
}
});
TextView textView_paydetails;
FragmentManager fragmentManager_payment;
Button button_placeorder;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_paymentdetails,
container, false);
textView_paydetails = (TextView) view.findViewById(R.id.txtsdid);
button_placeorder = (Button) view.findViewById(R.id.btnponid);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
fragmentManager_payment = getFragmentManager();
textView_paydetails.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/* // TODO Auto-generated method stub
PaymentShipping payment_shipping = new PaymentShipping();
FragmentTransaction fragmentTransaction = fragmentManager_payment
.beginTransaction();
// Locate Position
fragmentTransaction.replace(R.id.fsp, payment_shipping, "A");
fragmentTransaction.commit();*/
}
});
button_placeorder.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SecondFragement payment_shippingmethod = new SecondFragement();
FragmentTransaction fragmentTransaction = fragmentManager_payment
.beginTransaction();
// Locate Position
fragmentTransaction.replace(R.id.fsp, payment_shippingmethod,
"A");
//fragmentTransaction.addToBackStack("A");
fragmentTransaction.commit();
}
});
}

Click a button to open a Fragment?

I have a ViewPager in which I am able to view between 4 different tabs (which are fragments) I created. In one of my fragments, I want to have a button that will, after I click a button on that page, replace that view with another fragment. Now I don't want to swipe to another tab, I just merely want to replace the view of the current fragment when I press that button. Here is my attempt, but I'm not sure why when I click my button, nothing happens. If anyone could help me that would be great. Thanks!
This is the Fragment I call to create the view and the button I want to press.
ManualSelection.java
public class ManualSelection extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.activity_manual_selection, container, false);
intent = new Intent(getActivity(), ManualSelectionListView.class);
return rootView;
}
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button listViewGenerated = (Button) getActivity().findViewById(R.id.manual_generate);
listViewGenerated.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onClick(View v) {
FragmentManager fm = getActivity().getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.listView_manual, new ManualSelectionListView());
ft.commit();
}
});
}
}
And here is the Fragment I want to create
ManualSelectionListView.java
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class ManualSelectionListView extends Fragment {
static final String[] MOBILE_OS =
new String[] { "Android", "iOS", "WindowsMobile", "Blackberry"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.listview, container, false);
ListView lv = (ListView)rootView.findViewById(R.id.listview);
lv.setAdapter(new MobileArrayAdapter(getActivity(),MOBILE_OS));
return rootView;
}
}
And here are my XML files:
activity_manual_selection.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.ecs160.homestay.ManualSelection"
android:id="#+id/fragmentTest">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Generate"
android:id="#+id/manual_generate"
android:layout_centerHorizontal="true"
android:onClick="generateListView"/>
And here is the XML file called listview.xml that contains R.id.listView_manual
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/listView_manual">
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
I get nothing displayed when I hit "Generate." Any ideas? Thanks!
In your Activity you should create this:
public void generateListView(View v){
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.listView_manual, new ManualSelectionListView());
ft.commit();
}
The problem is that you are trying to get the Button id from your main activity which will return null
Button listViewGenerated = (Button) getActivity().findViewById(R.id.manual_generate);
Button manual_generate is located in your activity_manual_selection layout not in your Main activity's layout you cant get view from different layout or else it will return null
solution:
Get the Button's id from your fragment's layout
public class ManualSelection extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.activity_manual_selection, container, false);
intent = new Intent(getActivity(), ManualSelectionListView.class);
Button listViewGenerated = (Button) rootView.findViewById(R.id.manual_generate);
listViewGenerated.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onClick(View v) {
FragmentManager fm = getActivity().getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.listView_manual, new ManualSelectionListView());
ft.commit();
}
});
return rootView;
}
remove onActivityCreated

Categories

Resources