i have an action bar tab, it has two tabs, the first tabs has a fragment with a layout containing a button, wat i want to do is is when i click the button it will kinda switch the layout of the current fragment where that button belongs.. and is there any way to this stuff?.. i have an idea but it produces an nullexception on the other tab, anyway lets just concentrate on the 1st tab wherein i want to switch views when a button is clicked, here is my sample code:
MainActivity:
ActionBar acBar = getActionBar();
acBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tab1 = acBar.newTab().setText("Patient");
ActionBar.Tab tab2 = acBar.newTab().setText("Contact");
Fragment frag_a = new PatientFragment();
Fragment frag_b = new ContactFragment();
tab1.setTabListener(new MyTabListener(this, frag_a));
tab2.setTabListener(new MyTabListener(this, frag_b));
acBar.addTab(tab1);
acBar.addTab(tab2);
TabListener:
class MyTabListener implements ActionBar.TabListener{
private Fragment gFrag;
private Activity gAct;
public MyTabListener(Activity act, Fragment frag){
this.gFrag = frag;
this.gAct = act;
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(gAct, "Reselected!", Toast.LENGTH_LONG).show();
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.fragment_container, gFrag);
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(gFrag);
}
}
Fragment A:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.frag_a, container, false);
;
Button next = (Button) view.findViewById(R.id.prompt);
next.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getActivity(), "Next!",Toast.LENGTH_LONG).show();
}
});
return view;
}
Mainly i just want to switch views in the fragment, and if there is any other way that u guys know please do share tnx!
I suggest you to switch the whole Fragment. This API was designed for such purpoises.
Related
I put some tabs in the action bar with the following code. Everything looks fine. There are 5 tabs here. I coded each tab to open a new layout. But the problem is only the first tab works fine. Second tab opens the fifth layout and third, fouth, fifth tabs are not working. When I remove the fifth tab, then second tab opens the fourth layout and, other buttons are not woking, I couldn't silve this problem. Please help me. Thank you!
Here is my codings,
main class file;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android.app.ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
// show the given tab
}
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction ft) {
// hide the given tab
}
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction ft) {
// probably ignore this event
}
};
ActionBar.Tab baby = actionbar.newTab().setText("Baby")
.setTabListener(tabListener);
ActionBar.Tab books = actionbar.newTab().setText("Books")
.setTabListener(tabListener);
ActionBar.Tab electronics = actionbar.newTab().setText("Electronics")
.setTabListener(tabListener);
ActionBar.Tab health = actionbar.newTab().setText("Health and Beauty")
.setTabListener(tabListener);
ActionBar.Tab sports = actionbar.newTab().setText("Sports")
.setTabListener(tabListener);
Fragment babyFragment = new Baby();
Fragment booksFragment = new Books();
Fragment electronicsFragment = new Electronics();
Fragment healthFragment = new Health();
//Fragment sportsFragment = new Sports();
baby.setTabListener(new MyTabsListener(babyFragment));
books.setTabListener(new MyTabsListener(booksFragment));
books.setTabListener(new MyTabsListener(electronicsFragment));
books.setTabListener(new MyTabsListener(healthFragment));
//books.setTabListener(new MyTabsListener(sportsFragment));
actionbar.addTab(baby);
actionbar.addTab(books);
actionbar.addTab(electronics);
actionbar.addTab(health);
actionbar.addTab(sports);
}
class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.fragment_container, fragment);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(fragment);
}
}
every other other java file looks like this;
public class Baby extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.baby, container, false);
}
}
main xml file;
<?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:layout_gravity="center">
<LinearLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</LinearLayout>
</LinearLayout>
Pleease help me to solve this problem.
The error seems to be here:
baby.setTabListener(new MyTabsListener(babyFragment)); // OK
books.setTabListener(new MyTabsListener(booksFragment)); // OK
books.setTabListener(new MyTabsListener(electronicsFragment)); // !!
books.setTabListener(new MyTabsListener(healthFragment)); // !!
You are setting the different listeners to the same tab (that's why the "books" shows the "health" fragment, and the others do nothing).
I developed an android applicaion with acion bar that has 3 tabs with 3 difrrent fragments and I tried to pass a parameter from parent activity to fragments, I used the solution given in THIS qusetion and every thing is right, the only problem is that, now the activity sends this parameter to fragments just once at the start f applicaion, I need to get this parameter each time the user select the tabs, I think I should do this opration on onTabSelected method but have no idea how to do that, any suggestion?
Try this !!
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Pass the position on tab click to ViewPager
mPager.setCurrentItem(tab.getPosition());
Log.d("tab selected",""+tab.getPosition());
if(tab.getPosition==0)
{
Fragment fragA=new FrgmentA();
fragA.getData("data");
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
Log.d("tab Unselected",""+tab.getPosition());
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
Log.d("tab Reselected",""+tab.getPosition());
}
};
// Create first Tab
tab = mActionBar.newTab().setText("Profile").setTabListener(tabListener);
mActionBar.addTab(tab);
// Create second Tab
tab = mActionBar.newTab().setText("Picture").setTabListener(tabListener);
mActionBar.addTab(tab);
// Create third Tab
tab = mActionBar.newTab().setText("Help").setTabListener(tabListener);
mActionBar.addTab(tab);
FragmentA extends Fragment{
public FragmentA(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view =inflater.inflate(R.layout.fragment_image, container, false);
return view;
}
public void getData(String s)
{ // your implementation
}
}
hey please pass the value when the fragment instance is created ,please take a look on below codes
I just passwed an list once the fragment is loaded via viewpager
private void setupViewPager(ViewPager viewPager, List<AccountDetail> listAc) {
Homepage.ViewPagerAdapter adapter = new Homepage.ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new AllFragment("", listAc), "All");
adapter.addFrag(new AllFragment("1", listAc), "Credit");
adapter.addFrag(new AllFragment("2", listAc), "Debit");
viewPager.setAdapter(adapter);
}
And then write a constructor in your fragment be like this
public AFragment(String text, List<AccountDetail> manufactist) {
mText = text;
manufactureListAcoonut = manufactist;
}
I am developing an app in which there are two fragmenttabs.when pressing the tabs corresponding fragments will appear.that works fine.but what I want an activity inside the fragmenttabs. I am using ABS library for this.
ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tab1 = bar.newTab();
ActionBar.Tab tab2 = bar.newTab();
tab1.setText("Fragment A");
tab2.setText("Fragment B");
tab1.setTabListener(new MyTabListener<FragmentA>(this, "tab1",
FragmentA.class, null));
tab2.setTabListener(new MyTabListener<FragmentB>(this, "tab1",
FragmentB.class, null));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; go Location selection
Intent intent = new Intent(FragmentDemoActivity.this,
TestActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getSupportActionBar()
.getSelectedNavigationIndex());
}
listnerclass is
public class MyTabListener<T extends Fragment> implements ActionBar.TabListener {
private final FragmentActivity mActivity;
private final String mTag;
private final Class<T> mClass;
private final Bundle mArgs;
private Fragment mFragment;
public MyTabListener(FragmentActivity activity, String tag, Class<T> clz,
Bundle args) {
mActivity = activity;
mTag = tag;
mClass = clz;
mArgs = args;
FragmentTransaction ft = mActivity.getSupportFragmentManager()
.beginTransaction();
mFragment = mActivity.getSupportFragmentManager().findFragmentByTag(
mTag);
if (mFragment != null && !mFragment.isDetached()) {
ft.detach(mFragment);
}
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft = mActivity.getSupportFragmentManager().beginTransaction();
if (mFragment == null) {
mFragment = Fragment
.instantiate(mActivity, mClass.getName(), mArgs);
ft.add(android.R.id.content, mFragment, mTag);
ft.commit();
} else {
ft.attach(mFragment);
ft.commit();
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft = mActivity.getSupportFragmentManager().beginTransaction();
if (mFragment != null) {
ft.detach(mFragment);
ft.commitAllowingStateLoss();
}
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
Fragmentclass
public class FragmentB extends Fragment {
Button button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle saved)
{
return inflater.inflate(R.layout.frag_b, group, false);
}
#Override
public void onActivityCreated (Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
button = (Button) getActivity().findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Fragment B");
builder.setMessage("What would you like to do?");
builder.setPositiveButton("Nothing", null);
builder.setNegativeButton("Leave me alone!", null);
builder.show();
}
});
}
}
i wnt to include the following activity in the fragmentB
public class TestActivity extends Activity {
Button b1, b2;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.testactivity);
b1 = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);
tv = (TextView) findViewById(R.id.textView1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tv.setText("You Clicked on Button 1");
}
});
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tv.setText("You Clicked on Button 2");
}
});
}
}
I have lot of created activites to include in the fragment..its un imaginable to recreate in onActivityCreated of fragment class. according to this I have to modify my main application.
A Fragment can't host an activity. Instead of activity, you can use Nested Fragment.
A simple tutorial: http://xperiment-andro.blogspot.com/2013/02/nested-fragments.html
You cannot run an activity inside of a fragment. At best, you can have a fragment inside of a fragment.
so the best thing you can do in this situation is instead of creating an Activity you can create a Fragment and add it inside your FragmentB.
Like Faheem Said "
A Fragment can't host an activity. Instead of activity, you can use Nested Fragment"
Fragments are just like Activities if you read the Docs.Changing your activity to Fragment is easy
This is what developer.android says
To create a fragment, you must create a subclass of Fragment (or an existing subclass of it). The Fragment class has code that looks a lot like an Activity. It contains callback methods similar to an activity, such as onCreate(), onStart(), onPause(), and onStop(). In fact, if you're converting an existing Android application to use fragments, you might simply move code from your activity's callback methods into the respective callback methods of your fragment.
Usually, you should implement at least the following lifecycle methods:
onCreate()
The system calls this when creating the fragment. Within your implementation, you should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.
onCreateView()
The system calls this when it's time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View from this method that is the root of your fragment's layout. You can return null if the fragment does not provide a UI.
onPause()
The system calls this method as the first indication that the user is leaving the fragment (though it does not always mean the fragment is being destroyed). This is usually where you should commit any changes that should be persisted beyond the current user session (because the user might not come back).
This is the code activity inside Fragment.
YourActivityName.getSupportFragmentManager();
I want to display ListView in Tab (after selecting this tab I want ListView to appear),so I have created Fragment class and placed ListView code in it.The main problem now is to pass fragment object to tabListener. Please, post here example, or even better show how to do that in my code. Anyway, any help will be appreciated.
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");
tabOne.setTabListener(new tabListener());
tabTwo.setTabListener(new tabListener());
actionBar.addTab(tabOne);
actionBar.addTab(tabTwo);
}
protected class tabListener implements ActionBar.TabListener {
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
};
public class FirstFragment extends ListFragment {
private ArrayList<Cinemas> cinema;
private CinemasAdapter cinemaAdapter;
private ListView list;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
cinema = new Handler().handle();
cinemaAdapter = new CinemasAdapter(MainActivity.this, R.layout.movie_data_row, cinema);
setListAdapter(cinemaAdapter);
}
#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);
}
}
}
If you want to open up the list inside the tabTwo, you will need to create an instance of the FirstFragment class and add it to your view when you select the tab. Inside onTabSelected, create a new instance of FirstFragment if it isn't null, and add it to your view inside a container in your activity_main file. A container is a linear layout inside the view with the given amount of space that should be occupied by the fragment. In the case of a fullscreen fragment, the container is the root layout. You need only to specify an id to this layout. Once you create a new fragment, attach it by calling transaction.attach(); The final code block should be similar to this:
/** this example assumes that the fragment
* FirstFragment will be attached to tab 1
* which is at position = 0, and SecondFragment
* will be attached to tab 2, which is at
* position = 1. Also, the root layout of
* activity_main.xml has the id attribute of
* fragment_container
*/
FirstFragment firstFragment;
SecondFragment secondFragment;
#Override
public void onTabSelected(Tab tab, FragmentTransaction transaction) {
switch (tab.getPosition()) {
case 0:
if (firstFragment == null) {
firstFragment = new FirstFragment();
transaction.add(R.id.fragment_container,
firstFragment, "FIRST");
} else {
transaction.attach(firstFragment);
}
break;
case 1:
if (secondFragment == null) {
secondFragment = new SecondFragment();
transaction.add(R.id.fragment_container, secondFragment, "SECOND");
} else {
transaction.attach(secondFragment);
}
break;
}
}
I Want to dynamically add a view to the fragments from this mainActivity.
since, Fragment class does not have addView() API, what are the other options available for me.I tried fragment.getView() at line 1, but it gives nullpointer Exception. I am not well aware of the fragment api and dont have time to invest in going through it. Can anyone please provide a workaround for the problem.
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tabA = bar.newTab().setText("A Tab");
ActionBar.Tab tabB = bar.newTab().setText("B Tab");
ActionBar.Tab tabC = bar.newTab().setText("C Tab");
Fragment fragmentA = new AFragmentTab();
Fragment fragmentB = new BFragmentTab();
Fragment fragmentC = new CFragmentTab();
tabA.setTabListener(new MyTabsListener(fragmentA));
tabB.setTabListener(new MyTabsListener(fragmentB));
tabC.setTabListener(new MyTabsListener(fragmentC));
bar.addTab(tabA);
bar.addTab(tabB);
bar.addTab(tabC);
//Line 1
//How to add a view from here to any of these fragment
//Or how can i modify the content of that fragment
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
protected class MyTabsListener implements ActionBar.TabListener {
private Fragment fragment;
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.add(R.id.fragment_container, fragment, null);
// Or should the modification/addition of views be done here.
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// some people needed this line as well to make it work:
ft.remove(fragment);
}
}
}
BFagmentTab.java
public class BFragmentTab extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_b, container, false);
}
}
Try to call fragment.getView() in the onResume() or onStart() methods of the activity.
Please Look into this : One & Two