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
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).
Yesterday I downloaded new HoloEverywhere library.
Currently, I have problem with tab navigation after screen rotation.
My Home Activity:
public class MainActivity extends Activity implements TabListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setUpTabs();
}
private void setUpTabs() {
String[] titles = {
"First", "Second",
};
ActionBar supportActionBar = getSupportActionBar();
for (int i = 0; i < titles.length; i++) {
ActionBar.Tab tab = supportActionBar.newTab();
tab.setText(titles[i]);
tab.setTag(MyFragment.TAG);
tab.setTabListener(this);
supportActionBar.addTab(tab, false);
}
supportActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
supportActionBar.setSelectedNavigationItem(0);
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction fragmentTransaction) {
final String fragmentTag = tab.getTag().toString();
Fragment fragment = getSupportFragmentManager().findFragmentByTag(fragmentTag);
if (fragment == null) {
fragment = new MyFragment();
fragmentTransaction.add(android.R.id.content, fragment, fragmentTag);
} else {
fragmentTransaction.attach(fragment);
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction fragmentTransaction) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag((String) tab.getTag());
if (fragment != null) {
fragmentTransaction.detach(fragment);
}
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction fragmentTransaction) {
}
}
And my Fragment class.
public class MyFragment extends Fragment {
public static final String TAG = MyFragment.class.getCanonicalName();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = new View(getActivity());
view.setBackgroundColor(Color.BLACK);
return view;
}
}
When I rotate the screen fragment not displaying. It displays when i select tab (which is not currently selected) manually.
I just solve the problem.
I post my code here and see if those can help you :D
if (savedInstanceState == null){
TabHomeFragment homeFragment = new TabHomeFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, homeFragment, "home_fragment").commit();
}else{
TabHomeFragment homeFragment = (TabHomeFragment) getSupportFragmentManager().findFragmentByTag("home_fragment");
}
Those code are located in OnCreate method.
When the Device rotate and Ortiention change, the fragment will recreate again. So add a if clase to check if there is already one here.
But I am using normal Fragment in Android. Hope it can help you a little.
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've done stuff like this before and this is a super simple example but I can't seem to get it working using actionbarsherlock v4.1.
This is the main activity
public class VanityActivity extends SherlockFragmentActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
//restore
}
com.actionbarsherlock.app.ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setHomeButtonEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
com.actionbarsherlock.app.ActionBar.Tab tab1 = actionBar.newTab();
tab1.setText("Website");
tab1.setTabListener(new HeaderTabListener(getApplicationContext()));
tab1.setTag(1);
actionBar.addTab(tab1);
com.actionbarsherlock.app.ActionBar.Tab tab2 = actionBar.newTab();
tab2.setText("Portfolio");
tab2.setTabListener(new HeaderTabListener(getApplicationContext()));
tab2.setTag(2);
actionBar.addTab(tab2);
com.actionbarsherlock.app.ActionBar.Tab tab3 = actionBar.newTab();
tab3.setText("Team");
tab3.setTabListener(new HeaderTabListener(getApplicationContext()));
tab3.setTag(3);
actionBar.addTab(tab3);
}
}
And my HeaderTabListener class:
public class HeaderTabListener implements
com.actionbarsherlock.app.ActionBar.TabListener {
private Context context;
public HeaderTabListener(Context context){
this.context = context;
}
#Override
public void onTabSelected(com.actionbarsherlock.app.ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {
int i=((Integer)tab.getTag()).intValue();
if(tab.getPosition()==0){
ft.replace(android.R.id.content, CompanyFragment.newInstance(i));
}else if(tab.getPosition()==1){
ft.replace(android.R.id.content, PortfolioFragment.newInstance(i));
}
}
#Override
public void onTabUnselected(com.actionbarsherlock.app.ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {
Log.v("Tab selected", tab.getText().toString());
}
#Override
public void onTabReselected(com.actionbarsherlock.app.ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {
Log.v("Tab selected2", tab.getText().toString());
}
}
And finally one of the fragments (both fragments are the same but the text in each layout is different)
public class PortfolioFragment extends SherlockFragment {
private static final String KEY_POSITION="position";
private static final String KEY_TEXT="text";
static PortfolioFragment newInstance(int position) {
PortfolioFragment frag=new PortfolioFragment();
Bundle args=new Bundle();
args.putInt(KEY_POSITION, position);
frag.setArguments(args);
return(frag);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View result=inflater.inflate(R.layout.fragment_portfolio, container, false);
int position=getArguments().getInt(KEY_POSITION, -1);
return(result);
}
}
So when it first loads the the tabs are all displayed correctly, the first one his highlighted and the text in CompanyFragment layout displays. But then I am unable to click any of the other tabs to change the content and my logs inside of onTabSelected just never gets called. Any thoughts? Thanks for reading.
First off, let me tell you that I have no experience with ActionBarSherlock. I looked at your code to get a few ideas for my application. Seeing as it hasn't been answered since you posted it a few month ago, I would like to share my first impression.
As far as I know, ActionBarSherlock exposes the same functionality as the most recent Android APIs. Therefore, I do think that you are missing a simple method call. You would need to call commit() (Android Developer Guide reference) after you replace the fragment. Therefore, change the line, and all similar lines from;
ft.replace(android.R.id.content, PortfolioFragment.newInstance(i));
to
ft.replace(android.R.id.content, PortfolioFragment.newInstance(i)).commit();.
I hope this will solve your problem although I do realise you state that the ònTabSelected()` method is never called. Without debugging the difference between the problems would, however, seem transparent.
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.