How can I connect fragment in Activity? - android

I want to go to Fragment when Click button event. but I have issues about it.
Here's my code.
#OnClick(R.id.Main_Bottom_Bar_Summary)
public void onBottomBarClicked()
{
loadFragment(new AddItemFragment());
}
private void loadFragment(android.support.v4.app.Fragment fragment) {
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.frameLayout, fragment);
fragmentTransaction.commit(); // save the changes
}
and top of the acitivity. import files.
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
And My Fragment:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.and.dmt.R;
public class AddItemFragment extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_additemdialog,container, false);}
}
And I can see this issue.
What's this issue? How can I solve it?
If I change loadFragment parameter "Fragment" to "android.support.v4.app.Fragment"
then This issue appear.

loadFragment() takes android.app.Fragment as argument whereas your fragment extends android.support.v4.app.Fragment.
Change the argument for loadFragment() to take v4 Fragment and use getSupportFragmentManager().

if you use support fragment, try this code :
private void loadFragment(android.support.v4.app.Fragment fragment) {
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frameLayout, fragment);
fragmentTransaction.commit(); // save the changes
}

Add below code to calling Activity.
addFragment(R.id.fragment_container, NewFragment.newInstance());
and add below method in the fragment class which will return new Instance of that very fragment.
public static NewFragment newInstance() {
return new NewFragment();
}

Related

Replacing a fragment from inside a fragment

I read online, that to call another fragment, to take up the FrameLayout, you need to create an interface that talks to the activity and when the button clicked the function inside the interface that is defined in the activity replaces the Fragment with another fragment, but instead of creating the interface, i tried doing it directly from inside the fragment and it worked. So any reasons why i should not be doing this ?
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class FragmentOne extends Fragment {
public FragmentOne() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fragment_one, container, false);
Button btnONe = view.findViewById(R.id.btnOne);
btnONe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onButtonPressed();
}
});
return view;
}
public void onButtonPressed() {
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragmentContainer, new FragmentTwo("Femin Dharamshi did it!"));
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
Fragments are part of the Activity and fragment should be hosted through their parent activities as stated by google in Android developers docs.
You can refer this link:-
https://developer.android.com/training/basics/fragments/communicating
You should call getFragmentManager().beginTransaction().replace(int id, Fragment fr).commit(); in onViewCreated() method, not onCreateView() method.
Just move your code in onCreateView() into onViewCreated() method.

How Can I move from one fragment to new fragment?

I am trying to move to another fragment by clicking on a button. the current fragment named as FirstFragment and the target fragment named as AttendanceFragment. When I run the app it just crashed.
This is the code of the current fragment
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
* A simple {#link Fragment} subclass.
*/
public class FirstFragment extends Fragment {
public FirstFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_first, container, false);
Button btn1 = (Button) v.findViewById(R.id.btn1);
btn1.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
AttendanceFragment fragment = new AttendanceFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.register_attendance, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
);
return v;
}
}
Make an interface.
public interface FragmentChangeListener{
public void replaceFragment(Fragment fragment);
}
Implements your parent activity with this interface.
public class MainActivity extends Activity implements FragmentChangeListener {
#Override
public void replaceFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();;
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
fragmentTransaction.replace(mContainerId, fragment);
fragmentTransaction.addToBackStack(fragment.toString());
fragmentTransaction.commit();
}
}
Call this method from Fragments like this.
//In your fragment - call this method from onClickListener
public void showOtherFragment(){
Fragment fragment=new NewFragmentName();
FragmentChangeListener listener = (FragmentChangeListener)getActivity();
listener.replaceFragment(fragment);
}
Please read Communicating with other Fragments
There you can find elegant version of solution posted by #Sanjog Shrestha. You should register you callback in onAttach(Activity activity) and unregister it in onDetach(). You better be sure that Activity implements interface defined by yourself.

Communication between fragments via interfaces

The fragments are a part of the bottom navigation bar, so far so good on the navigation part. But when i try to pass data from fragment1 to fragment2 the app is crashing. Also I am using the example given by google at this following link
When I use the following code android studio gives me deprecated warning!
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
So I am using CONTEXT instead of ACTIVITY below is my code that crashes :
MainActivity
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.br.tron.bottombar.RadioFragment;
import com.br.tron.bottombar.StreamFragment;
import com.br.tron.bottombar.InfoFragment;
public class MainActivity extends AppCompatActivity implements RadioFragment.OnNameSetListener {
BottomNavigationView bottomNavigationView;
private Fragment fragment;
private FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
fragment = new RadioFragment();
final FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.main_container, fragment).commit();
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationBar);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener(){
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_button_one:
fragment = new RadioFragment();
break;
case R.id.nav_button_two:
fragment = new StreamFragment();
break;
case R.id.nav_button_three:
fragment = new InfoFragment();
break;
}
final FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_container, fragment).commit();
return true;
}
});
}
public void performStreamClick(){
View view = bottomNavigationView.findViewById(R.id.nav_button_two);
view.performClick();
}
#Override
public void setUrl(String url) {
StreamFragment frag=(StreamFragment) getSupportFragmentManager().findFragmentByTag("frag");
frag.getUrl(url);
}
}
RadioFragment(Fragment1 where the data exist)
import android.app.Activity;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class RadioFragment extends Fragment implements Button.OnClickListener {
Button buttonman;
View rootView;
String url;
Activity a;
OnNameSetListener onNameSetListener;
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Activity) {
a = (Activity) context;
try{
onNameSetListener=(OnNameSetListener) context;
}
catch (Exception e){}
}
}
public RadioFragment(){
};
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_player, container, false);
buttonman = (Button)rootView.findViewById(R.id.buttonman);
buttonman.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
/*Fragment fragment = new StreamFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.main_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();*/
url="www.idontknow.com";
onNameSetListener.setUrl(url);
((MainActivity)a).performStreamClick();
}
public interface OnNameSetListener
{
public void setUrl(String url);
}
}
StreamFragment(fragment2 where I want to send the data -from fragment1)
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class StreamFragment extends Fragment {
TextView textViewStream;
public StreamFragment(){};
#Override
public View onCreateView(final LayoutInflater inflater,final ViewGroup container,final Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_stream, container, false);
}
public void getUrl(String url)
{
textViewStream.setText(url);
}
}
LOGCAT
01-06 20:10:23.023 3744-3744/com.br.tron.bottombar E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.br.tron.bottombar, PID: 3744
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.br.tron.bottombar.StreamFragment.getUrl(java.lang.String)' on a null object reference
at com.br.tron.bottombar.MainActivity.setUrl(MainActivity.java:64)
at com.br.tron.bottombar.RadioFragment.onClick(RadioFragment.java:61)
at android.view.View.performClick(View.java:5201)
at android.view.View$PerformClick.run(View.java:21209)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5525)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
01-06 20:10:24.663 3744-3744/? I/Process: Sending signal. PID: 3744 SIG: 9
You never register the frag tag you later search for.
In your MainActivity modify:
final FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.main_container, fragment, "frag").commit();
...
final FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_container, fragment, "frag").commit();
...
In addition to that within your StreamFragment class you never set the TextViewStream variable after you inflate your layout.
#Override
public View onCreateView(final LayoutInflater inflater,final ViewGroup container,final Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_stream, container, false);
textViewStream = (TextView) view.findViewById(R.id.ID_GOES_HERE);
return view;
}
Edit: Further Errors
You're getting a ClassCastException because you're not checking to see whether the fragment you get in MainActivity.setUrl is a StreamFragment. And it makes sense that it's failing because you register the frag tag for all three types of custom Fragments. Here's a further solution:
fragment = new RadioFragment();
final FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.main_container, fragment, "radio_fragment").commit();
...
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
String tag = "";
case R.id.nav_button_one:
fragment = new RadioFragment();
tag = "radio_fragment";
break;
case R.id.nav_button_two:
fragment = new StreamFragment();
tag = "stream_fragment";
break;
case R.id.nav_button_three:
fragment = new InfoFragment();
tag = "info_fragment";
break;
}
final FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_container, fragment, tag).commit();
return true;
}
Make the appropriate change in the Tag string in setUrl:
StreamFragment frag=(StreamFragment) getSupportFragmentManager().findFragmentByTag("stream_fragment");
if (frag != null) frag.getUrl(url);
Both of the current answers key in on your crash problem. I expect that will take care of your primary question. #asadmshah seems to have taken care of your next problem. Make sure to up vote his answer & accept it.
Regarding the warning from using Google's example code, here is what AS will currently give you if you tell it to create a new fragment.
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
The point of this is to make sure that the Activity you're attaching to implements the interface you've defined in your fragment.
And on the subject of the interface, all fragment to activity comms should be done through it. It would be better to find a way to call performStreamClick() through the interface as well. (I just realized I made this same mistake on an app I started several months ago but am just finishing up now :).
Lastly, just an FYI, you can get the attached activity of a fragment with getActivity().
EDIT:
1st, it might help to see your current code. I'm going to assume you have what Asad has put in his answer, more or less. Also, what is the expected behavior? I believe that you make a selection in RadioFragment then replace it with StreamFragment. That is, both fragments take the whole nav bar, they don't exist at the same time. If this is wrong, let me know.
If you're still calling setUrl() and performStreamClick() in the same order as before, you're getting null because you've never created a fragment by that name. You can't find a fragment you haven't already created.
Without actually setting this up to test it myself, I believe what you need to do would be to save the url in a global variable in setUrl(), then in your click listener, pass that to the StreamFragment when you create it.
See the "Deliver a Message to a Fragment" section of the link you've sited for doing that
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);
(obviously, handling your url string instead of the int in the example)
Also, it's not a bad idea to handle null when searching for a fragment that should exist already
StreamFragment frag=(StreamFragment) getSupportFragmentManager().findFragmentByTag("stream_frag");
if(frag == null) {
final FragmentTransaction transaction = fragmentManager.beginTransaction();
StreamFragment fragment = new StreamFragment();
transaction.replace(R.id.main_container, fragment, "stream_frag").commit();
}
You should initialize your textViewStream in the StreamFragment fragment.

Moving from one fragment to another in a custom listview in android

I have created a navigation drawer for my app from androidhive.info. In that navigation drawer, in one fragment, I have created a custom listview which shows the elements with a name and image. Now upon clicking an item of the custom listview, I need to show the details of the clicked list element. For that I have created another fragment. Now upon clicking the listview element, I should move onto the details of the selected element. The code which I have used for moving from one fragment to another is this:
Fragment fragment=new ImportantNumbersFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
But the getSupportFragmentManager() is showing an error in eclipse like this: The method getSupportFragmentManager() is undefined for the type PagesFragment. This is the code of my custom listview fragment.
PagesFragment.class
public class PagesFragment extends ListFragment implements OnItemClickListener{
Typeface tf;
ListView lv;
List<SimpleRow>rowItems;
public PagesFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pages, container, false);
Helper help=new Helper(getActivity().getApplicationContext());
String choice1="സര്‍ക്കാര്‍ സ്ഥാപനങ്ങള്‍";
String choice1new=help.changemalayalam(new Data(choice1));
String choice2="പത്രം";
String choice2new=help.changemalayalam(new Data(choice2));
String choice3="ന്യൂസ് ചാനല്‍";
String choice3new=help.changemalayalam(new Data(choice3));
String choice4="യൂണിവേഴ്സിറ്റികള്‍";
String choice4new=help.changemalayalam(new Data(choice4));
String choice5="പഞ്ചായത്ത് ഓഫീസ്";
String choice5new=help.changemalayalam(new Data(choice5));
String choice6="ഇന്‍ഷുറന്‍സ്";
String choice6new=help.changemalayalam(new Data(choice6));
String choice7="പോലീസ് സ്റ്റേഷന്‍";
String choice7new=help.changemalayalam(new Data(choice7));
String choice8="ഫയര്‍ സ്റ്റേഷന്‍";
String choice8new=help.changemalayalam(new Data(choice8));
ArrayList<String>choice=new ArrayList<String>();
choice.add(choice1new);
choice.add(choice2new);
choice.add(choice3new);
choice.add(choice4new);
choice.add(choice5new);
choice.add(choice6new);
choice.add(choice7new);
choice.add(choice8new);
lv=(ListView)rootView.findViewById(R.id.list1);
rowItems=new ArrayList<SimpleRow>();
for (int i = 0; i < choice.size(); i++) {
SimpleRow item = new SimpleRow(choice.get(i));
rowItems.add(item);
CustomSimpleListAdapter adapter = new CustomSimpleListAdapter(getActivity().getApplicationContext(),R.layout.list_single, rowItems);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
}
return rootView;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Toast.makeText(getActivity().getApplicationContext(), "You clicked on position "+position,Toast.LENGTH_LONG).show();
//Here upon clicking the list element, I need to go to ImportantNubersFragment
Fragment fragment=new ImportantNumbersFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(getActivity().getApplicationContext(), "You clicked on position "+arg2,Toast.LENGTH_LONG).show();
}
}
ImportantNumbersFragment.class
public class ImportantNumbersFragment extends Fragment {
public ImportantNumbersFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_container, container, false);
return rootView;
}
}
fragment_important_numbers.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout android:name="fragments.YourInitialFragment"
android:id="#+id/fragment_container"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dip" />
</LinearLayout>
I want to move from PagesFragment to ImportantNumbersFragment upon clicking the list element in the custom listview. So in the OnListItemClick, I have given the code for moving from fragment to another. I have to do this in the sameway as that of moving from one activity to another activity using intents like:
Intent i=new Intent(First.this,Second.class);
startActivity(i);.
Since I'm new to fragments, I don't know how this can be achieved in fragments. That's why I have asked here. Can someone please point out the errors in this code. Thanks in advance..
Are you using Support package for fragment in all extended Fragment
Classes, Check !
.
I myself have used the code from AndroidHive and it works perfectly
.
There it does not uses Support package for extended fragment classes
.
Somewhere in code you are using a Support import, Make sure you
maintain uniformity among imports
.
Programatically Speaking for ex::
If you are using support package use codes like these
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
If you are not using support package use codes imports ::
import android.app.ActionBarDrawerToggle;
import android.app.Fragment;
import android.app.FragmentActivity;
import android.app.FragmentTransaction;
import android.widget.DrawerLayout;
{EDIT - Sample on how one of the way to perform fragment transaction}
MainActivity.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
public class MainActivity extends FragmentActivity {
Fragment fragment;
String className;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("MainActivity", "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Store the name of the class
className=MainActivity.class.getSimpleName();
//First fragment should be mounted on oncreate of main activity
if (savedInstanceState == null) {
/*fragment=FragmentOne.newInstance();
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).addToBackStack(className).commit();
*/
Fragment newFragment = FragmentOne.newInstance();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, newFragment).addToBackStack(null).commit();
Log.d("FRAGMENT-A", "fragment added to backstack");
}
}
}
FragmentOne.java
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Spinner;
import com.sample.screennavigation.UtilRangeSeekBar.OnRangeSeekBarChangeListener;
public class FragmentOne extends Fragment{
//Declare variables that hold the data for configuration change
public static FragmentOne newInstance(){
Log.d("FragmentOne", "newInstance");
FragmentOne fragment = new FragmentOne();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("FragmentOne", "onCreateView");
View view=inflater.inflate(R.layout.fragment_one, container, false);
return view;
}
}
{EDIT-2}
PagesFragment ... is using a support package somewhere, check
it !
Check imports of pagefragment
But the getSupportFragmentManager() is showing an error in eclipse like this: The method getSupportFragmentManager() is undefined for the type PagesFragment.
Error in your code clearly says you are using a supportpackage import
and it is conflicting the execution
Rememmber you cannot mix the imports
Hope it helps !, let me know if you need any additional info

Different when write function in onCreateView and method in class extends from Fragment

In Main class, I declare a StartActivity type variable.StartActivity fragment1 = new StartActivity();
Here is StartActivity class. I call drawTab() method on onCreateView. And It runs OK.
package com.example.android.navigationdrawerexample;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class StartActivity extends Fragment {
public static Context appContext;
ActionBar actionbar;
int state = 0;
/** Called when the activity is first created. */
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main, container, false);
drawTab();
return rootView;
}
// call draw Tab method
public void drawTab() {
// ActionBar
actionbar = getActivity().getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab PlayerTab = actionbar.newTab().setText("Fragment A");
ActionBar.Tab StationsTab = actionbar.newTab().setText("Fragment B");
Fragment PlayerFragment = new AFragment();
Fragment StationsFragment = new BFragment();
PlayerTab.setTabListener(new MyTabsListener(PlayerFragment));
StationsTab.setTabListener(new MyTabsListener(StationsFragment));
actionbar.addTab(PlayerTab);
actionbar.addTab(StationsTab);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
}
return false;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getActivity().getActionBar()
.getSelectedNavigationIndex());
}
}
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);
}
}
However, it don't need so. I want when I declare a StartActivity type variable StartActivity fragment1 = new StartActivity();
it doesn't call drawTab() method. It only called, when I call:
fragment1.drawTab(). And I tried remove drawTab() method on onCreateView
And in Main class I have:
StartActivity fragment1 = new StartActivity();
fragment1.drawTab();
However ERROR happens. I dont know reason. What is different? I think error happens when I call: actionbar = getActivity().getActionBar(); on drawTab() not onCreateView
help me solve problem? Thanks you!

Categories

Resources