I have a fragment MyProfile (consists info about a logged user) which I want to be used by fragments Team (consists info about all team members). When I use MyProfile for Team fragment, I need up button. I read documentation guide, tried all from up navigation inside fragment and stopped on this example. The problem is instead of going back to the previous fragment in my case it just opens the options menu.
MainActivity
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
int id = item.getItemId();
if (id == R.id.nav_team) {
fragmentTransaction.replace(R.id.container, new TeamFragment())
.addToBackStack(null)
.commit();
}
TeamFragment
public class TeamFragment extends Fragment {
private String LOG_TAG = getClass().getSimpleName();
private ListView teamList;
private android.support.v4.app.FragmentManager fragmentManager;
public TeamFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragmentManager = getFragmentManager();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
((MainActivity) getActivity()).setActionBarTitle("Team");
View rootView = inflater.inflate(R.layout.fragment_announcement, container, false);
final SwipeRefreshLayout swipeToUpdate = rootView.findViewById(R.id.swiperefresh);
teamList = rootView.findViewById(R.id.announcements_list);
getTeamFromAPI(Contract.TEAM);
teamList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ImageView avatar = view.findViewById(R.id.team_img);
TextView fullname = view.findViewById(R.id.team_fullname);
TextView jobtitle = view.findViewById(R.id.team_jobtitle);
TextView email = view.findViewById(R.id.team_email);
avatar.buildDrawingCache();
Bitmap bitmap = avatar.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] bAvatar = baos.toByteArray();
//when team member i replace here current fragment with profile fragment
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragment = ProfileFragment.newInstance(String.valueOf(fullname.getText()),
String.valueOf(jobtitle.getText()),
String.valueOf(email.getText()), bAvatar);
fragmentTransaction.replace(R.id.container, fragment, "MEMBER_PROFILE")
.addToBackStack(null)
.commit();
}
});
return rootView;
}
private void getTeamFromAPI(String url) {
//fetch team members from database
}
}
Place where I try return back to TeamFragment
ProfileFragment
public class ProfileFragment extends Fragment{
private String LOG_TAG = getClass().getSimpleName();
private String mFullname;
private String mTitle;
private String mEmail;
private byte[] mAvatar;
private android.support.v4.app.FragmentManager fragmentManager;
private ActionBar actionBar;
private View rootView;
public ProfileFragment() {
// Required empty public constructor
}
public static ProfileFragment newInstance(String name, String title, String email, byte[] avatar) {
Bundle bundle = new Bundle();
bundle.putString("fullname", name);
bundle.putString("title", title);
bundle.putString("email",email);
bundle.putByteArray("avatar", avatar);
ProfileFragment fragment = new ProfileFragment();
fragment.setArguments(bundle);
return fragment;
}
private void readBundle(Bundle bundle) {
if (bundle != null) {
this.mFullname = bundle.getString("fullname");
this.mTitle = bundle.getString("title");
this.mEmail = bundle.getString("email");
this.mAvatar = bundle.getByteArray("avatar");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragmentManager = getFragmentManager();
// Sets "up navigation" for both phone/tablet configurations
actionBar = ((MainActivity)getActivity()).getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_announcement, container, false);
ListView listView = rootView.findViewById(R.id.announcements_list);
SwipeRefreshLayout swipe = rootView.findViewById(R.id.swiperefresh);
swipe.setEnabled(false);
readBundle(getArguments());
ArrayList<ProfileObject> list = new ArrayList<>();
list.add(new ProfileObject(mFullname, mTitle,mEmail,mAvatar));
ProfileAdapter adapter = new ProfileAdapter(getContext(), list);
listView.setAdapter(adapter);
return rootView;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Log.e(LOG_TAG+"/onOptionsItemSelected","Pressed: "+item.getItemId());
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ProfileFragment member_profile = (ProfileFragment)fragmentManager.findFragmentByTag("MEMBER_PROFILE");
fragmentTransaction.remove(member_profile).commit();
fragmentManager.popBackStack();
actionBar.setDisplayHomeAsUpEnabled(false);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
But as I already said it only the opens options menu. Did I make a somewhere conceptual mistake?
UPDATE: Problem inside onOptionsItemSelected. If add
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Log.e(LOG_TAG+"/onOptionsItemSelected","Pressed: "+item.getItemId());
return true;
default:
return super.onOptionsItemSelected(item);
}
}
and click on back arrow nothing will be in Logcat.
As per your code you have handled onOptionsItemSelected() for R.id.home but I see you are using ActionBar back button which is provided by Android UI itself
actionBar = ((MainActivity)getActivity()).getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
In this case Home Button is referenced as android.R.id.home and NOT R.id.home
This is the reason you are not getting any update in Logcat too (as you mentioned in comments).
Update your switch case as below and replace R.id.home with android.R.id.home
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: // <- Update this
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ProfileFragment member_profile = (ProfileFragment)fragmentManager.findFragmentByTag("MEMBER_PROFILE");
fragmentTransaction.remove(member_profile).commit();
fragmentManager.popBackStack();
actionBar.setDisplayHomeAsUpEnabled(false);
return true;
default:
return super.onOptionsItemSelected(item);
}
Related
This question already has answers here:
how to pass string data from activity to fragment?
(5 answers)
Closed 5 years ago.
My problem is passing string from activity to fragment. I researched for a whole day and my problem isn't solved.
activity :
if(email.matches(users.user1)&&password.matches(users.pass1)){
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
Bundle bundle = new Bundle();
bundle.putString("user", users.name);
ProfileFragment fragobj = new ProfileFragment();
fragobj.setArguments(bundle);
startActivity(intent);
}
fragment :
public class ProfileFragment extends Fragment {
public static ProfileFragment newInstance() {
return new ProfileFragment();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profile, container, false);
String user = getArguments().getString("user");
TextView textView = v.findViewById(R.id.namef1);
textView.setText(user);
return inflater.inflate(R.layout.fragment_profile, container, false);
}
}
MainActivity
public class MainActivity extends Activity {
private BottomNavigationView mBottomNavigationView;
private Toolbar supportActionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupBottomNavigation();
if (savedInstanceState == null) {
loadHomeFragment();
}
}
private void setupBottomNavigation() {
mBottomNavigationView =findViewById(R.id.bottom_navigation);
mBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_home:
loadHomeFragment();
return true;
case R.id.action_profile:
loadProfileFragment();
return true;
case R.id.action_settings:
loadSettingsFragment();
return true;
}
return false;
}
});
}
private void loadHomeFragment() {
HomeFragment fragment = HomeFragment.newInstance();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame, fragment);
ft.commit();
}
private void loadProfileFragment() {
ProfileFragment fragment = ProfileFragment.newInstance();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame, fragment);
ft.commit();
}
private void loadSettingsFragment() {
SettingsFragment fragment = SettingsFragment.newInstance();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame, fragment);
ft.commit();
}
public void setSupportActionBar(Toolbar supportActionBar) {
this.supportActionBar=supportActionBar;
}
}
as it shown in code user has login and one of his data display in a profile fragment . I wanna display this string as Textview in profilefragment .
anybody have an idea?
Move below part of code to the place where you are adding the ProfileFragment to Activity.
Bundle bundle = new Bundle();
bundle.putString("user", users.name);
ProfileFragment fragobj = new ProfileFragment();
fragobj.setArguments(bundle);
I have a problem with my Bottom bar in android. when i click on the bottom menu options it goes blank. Please help me out to fine what is the basic problem. Where is am I wrong.
It shows no error or exception in logcat.
Here is my code
public class BottomBarActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom_bar);
final BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.action_library:
FragmentLibrary fragmentLibrary = new FragmentLibrary();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.frame_layout1, fragmentLibrary);
fragmentTransaction.commit();
Toast.makeText(BottomBarActivity.this, "Library", Toast.LENGTH_SHORT).show();
break;
case R.id.action_notification:
//002
Fragment selectedFragmentNotification = FragmentNotification.newInstance();
FragmentTransaction fragmentTransactionNotification = getSupportFragmentManager().beginTransaction();
fragmentTransactionNotification.replace(R.id.frame_layout1, selectedFragmentNotification);
fragmentTransactionNotification.commit();
Toast.makeText(BottomBarActivity.this, "Notifications", Toast.LENGTH_SHORT).show();
break;
case R.id.action_more:
Fragment selectedFragmentMore = FragmentMore.newInstance();
FragmentTransaction fragmentTransactionMore = getSupportFragmentManager().beginTransaction();
fragmentTransactionMore.replace(R.id.frame_layout1, selectedFragmentMore);
fragmentTransactionMore.commit();
Toast.makeText(BottomBarActivity.this, "More", Toast.LENGTH_SHORT).show();
break;
case R.id.action_discovered:
Fragment selectedFragmentMain = FragmentMain.newInstance();
FragmentTransaction fragmentTransactionMain = getSupportFragmentManager().beginTransaction();
fragmentTransactionMain.replace(R.id.frame_layout1, selectedFragmentMain);
fragmentTransactionMain.commit();
Toast.makeText(BottomBarActivity.this, "Discover", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
});
//Manually displaying the first fragment
Fragment selectedFragment = FragmentMain.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout1, selectedFragment);
fragmentTransaction.commit();
}
}
Here is the Fragment Class Code.
This fragment is called when I click one of the menu item.
public class FragmentLibrary extends Fragment {
private static final String ARG_POSITION = "position";
private int position;
private PagerSlidingTabStrip tabs_L;
private ViewPager pager_L;
public FragmentLibrary() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_library, container, false);
pager_L = (ViewPager) view.findViewById(R.id.pagerL);
pager_L.setAdapter(new MyAdapterLibrary(getFragmentManager()));
tabs_L = (PagerSlidingTabStrip) view.findViewById(R.id.tabsL);
tabs_L.setViewPager(pager_L);
return view;
}
// ADAPTER CLASS
public class MyAdapterLibrary extends FragmentPagerAdapter {
private String[] titles = {
getString(R.string.tab_title_current_reading),
getString(R.string.tab_title_reading_lists),
getString(R.string.tab_title_history)
};
public MyAdapterLibrary(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return FragmentCurrentReading.newInstance(position);
case 1:
return FragmentReadingLists.newInstance(position);
case 2:
return FragmentHistory.newInstance(position);
}
return null;
}
#Override
public int getCount() {
return titles.length;
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
}
The Main Activity having bottom navigation and contains 5 fragments in it. Each fragments having multiple fragment inside. how to handle the onbackpressed in it.
Homepage.java
public class Homepage extends AppCompatActivity {
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.home:
selectedFragment = Fragment_home.newInstance();
break;
case R.id.eventsfeed:
selectedFragment = Fragment_eventsfeed.newInstance();
break;
case R.id.events:
selectedFragment = Fragment_events.newInstance();
break;
case R.id.messages:
selectedFragment = Fragment_messages.newInstance();
break;
case R.id.settings:
selectedFragment = Fragment_settings.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content, selectedFragment);
transaction.commit();
return true;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
Fragment fragmentnewview = new Fragment_home();
FragmentManager frMan = getSupportFragmentManager();
FragmentTransaction frTr = frMan.beginTransaction();
frTr.add(R.id.content,fragmentnewview);
frTr.commit();
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
BottomNavigationViewHelper.disableShiftMode(navigation);
}}
Fragment_home.java
public class Fragment_home extends Fragment {
public static Fragment_home newInstance(){
Fragment_home fragment=new Fragment_home();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view=inflater.inflate(R.layout.fragment_home, container, false);
CardView card=(CardView)view.findViewById(R.id.next_page_home_card);
card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
view.setVisibility(View.GONE);
Fragment fragmentnewview = new Event_details();
FragmentManager frMan = getActivity().getSupportFragmentManager();
FragmentTransaction frTr = frMan.beginTransaction();
frTr.add(R.id.content,fragmentnewview);
frTr.commit();
}
});
return view;
}
}
Inside that Fragment_home.java i have a card view when it clicked it goes to next fragment Event_Details.java
Event_Details.java
public class Event_details extends Fragment {
Button add_comments;
ImageButton back;
public static Event_details newInstance(){
Event_details fragment=new Event_details();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view=inflater.inflate(R.layout.event_details, container, false);
add_comments=(Button)view.findViewById(R.id.add_comment);
back=(ImageButton)view.findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
view.setVisibility(View.GONE);
Fragment fragmentnewview = new Fragment_home();
FragmentManager frMan = getActivity().getSupportFragmentManager();
FragmentTransaction frTr = frMan.beginTransaction();
frTr.add(R.id.content,fragmentnewview);
frTr.commit();
}
});
add_comments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
view.setVisibility(View.GONE);
Fragment fragmentnewview = new Comments();
FragmentManager frMan = getActivity().getSupportFragmentManager();
FragmentTransaction frTr = frMan.beginTransaction();
frTr.add(R.id.content,fragmentnewview);
frTr.commit();
}
});
return view;
}
}
i have a button in Event_Details.java when clicked that it calls another fragment Comments.java
Comments.java
public class Comments extends Fragment {
ImageButton back;
public static Comments newInstance(){
Comments fragment=new Comments();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view=inflater.inflate(R.layout.add_your_comments, container, false);
back=(ImageButton)view.findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
view.setVisibility(View.GONE);
Fragment fragmentnewview = new Event_details();
FragmentManager frMan = getActivity().getSupportFragmentManager();
FragmentTransaction frTr = frMan.beginTransaction();
frTr.add(R.id.content,fragmentnewview);
frTr.commit();
}
});
return view;
}
}
back.setOnClickListener is the image button to go back but i can't implement in the hardware back button.
You need to #Override your activity onBackPressed() method !!!
There are many good information and answers about your question ! if you want to become good programmer you need good research skills!!! :))
Try to research and solve the problem yourself . Write some code, and after all of it if you still can't resolve your problem i'll give you code for copy and paste :)
When you load a fragment, use addToBackStack(null) on the FragmentTransaction. If you do that, the back button will reverse the transaction.
#Override onBackPressed()
method as #L.Petrosyan told,
insideonBackPressed()get the current position of your viewpager usingviewPager.getCurrentItem();
it will return you anint` value. use that value to manage your code.
In this function on click of nav_manage I want to open ViewTasks that extends ListFragment. Can someone please suggest some code example?
This is a function in my MainActivity.
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
displaySelectedScreen(item.getItemId());
return true;
}
private void displaySelectedScreen(int itemId)
{
Fragment fragment = null;
//initializing the fragment object which is selected
switch (itemId) {
case R.id.nav_send:
fragment = new Invitation();
break;
case R.id.nav_camera:
fragment=new Home();
break;
case R.id.nav_manage:
fragment=new ViewTasks();
break;
default:
Toast.makeText(MainActivity2.this,"Choose Something",Toast.LENGTH_LONG).show();
}
//replacing the fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
My ViewTasks class:
public class ViewTasks extends ListFragment {
private Button addButton;
private TaskManagerApplication app;
private TaskListAdapter adapter;
private Button removeButton;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.home_fragment, container, false);
}
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("Task Scheduler");
app = (TaskManagerApplication)getActivity().getApplication();
adapter = new TaskListAdapter(this.getActivity(), app.getCurrentTasks());
setListAdapter(adapter);
setUpViews();
}
#Override
public void onResume() {
super.onResume();
adapter.forceReload();
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
adapter.toggleTaskCompleteAtPosition(position);
Task t = adapter.getItem(position);
app.saveTask(t);
}
protected void removeCompletedTasks() {
Long[] ids = adapter.removeCompletedTasks();
app.deleteTasks(ids);
}
private void setUpViews() {
addButton = (Button)getView().findViewById(R.id.add_button);
removeButton = (Button)getView().findViewById(R.id.remove_button);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, new AddTaskActivity())
.commit();
}
});
removeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
removeCompletedTasks();
}
});
}
}
I want this function to open the ViewTasks fragment which has listview of tasks scheduled.
When I follow the same pattern as my above case it shows this error:
Incompatible types:
Required: android.app.Fragment
Found: com.happy.taskmanager.ViewTasks
I have a FragmentTabHost and have some problems with it on fragment switching. After attempting a fragment switch and then I click on another tab, the tab contents overlap. I then try to override the onTabChanged method (don't know whether it could be a solution though....), however I discover the onTabChanged does not be run!
--Update--
onTabChanged is now runnable but the overlap problem is still here.
here is my code:
MainActivity
public class MainActivity extends FragmentActivity implements OnTabChangeListener{
private static final String TAB = "MainActivity";
private FragmentTabHost tabMenu;
public static final String NEWS_TAB = "news";
public static final String SHARE_TAB = "share";
public static final String CAMERA_TAB = "camera";
public static final String STATUS_TAB = "status";
public static final String OTHER_TAB = "other";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabMenu = (FragmentTabHost)findViewById(R.id.main_tabhost);
tabMenu.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
String[] tabTitle = getResources().getStringArray(R.array.tab_title);
for (int i=0; i<tabTitle.length; i++){
String tagId = "";
int tabIconDrawable = 0;
Class tabClass = BlankTab.class;
switch(tabTitle[i]){
case "最新消息":
tabIconDrawable = R.drawable.ic_action_view_as_list;
tagId = this.NEWS_TAB;
tabClass = News.class;
break;
case "貨件分享":
tabIconDrawable = R.drawable.ic_action_important;
tagId = this.SHARE_TAB;
tabClass = GoodsShare.class;
break;
case "":
tabIconDrawable = R.drawable.ic_action_camera;
tagId = this.CAMERA_TAB;
break;
case "物流狀態":
tabIconDrawable = R.drawable.ic_action_airplane_mode_on;
tagId = this.STATUS_TAB;
tabClass = LogisticStatus.class;
break;
case "其他":
tabIconDrawable = R.drawable.ic_action_overflow;
tagId = this.OTHER_TAB;
tabClass = Others.class;
break;
}
View tabView = getLayoutInflater().inflate(R.layout.tab_layout, null, false);
ImageView tabIcon = (ImageView)tabView.findViewById(R.id.tab_icon);
TextView tabText = (TextView)tabView.findViewById(R.id.tab_title);
tabIcon.setImageDrawable(getResources().getDrawable(tabIconDrawable));
tabText.setText(tabTitle[i]);
TabSpec spec = tabMenu.newTabSpec(tagId).setIndicator(tabView);
tabMenu.addTab(spec, tabClass, null);
tabMenu.getTabWidget().getChildAt(i).setBackground(getResources().getDrawable(R.drawable.main_tab_selector));
}
tabMenu.setOnTabChangedListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return super.onOptionsItemSelected(item);
}
#Override
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
Log.d(TAB, tabId);
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
Fragment fragment = null;
if (tabId.equals(this.NEWS_TAB)){
fragment = new News();
} else if (tabId.equals(this.SHARE_TAB)){
fragment = new GoodsShare();
} else if (tabId.equals(this.CAMERA_TAB)){
fragment = new Camera();
} else if (tabId.equals(this.STATUS_TAB)){
fragment = new LogisticStatus();
} else if (tabId.equals(this.OTHER_TAB)){
fragment = new Others();
}
if (fragment != null){
t.replace(android.R.id.tabcontent, fragment);
} else {
Log.e(TAB, "fragment creation error");
}
}
}
Others<---the one has fragment switching
public class Others extends Fragment{
private View view;
private Controller controller;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
controller = (Controller)this.getActivity().getApplication();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
view = inflater.inflate(R.layout.others, container, false);
setLayout();
return view;
}
private void setLayout(){
ListView othersMenu = (ListView)view.findViewById(R.id.others_menu);
String[] othersItem = getResources().getStringArray(R.array.others);
ArrayAdapter<String> adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, othersItem);
othersMenu.setAdapter(adapter);
othersMenu.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String item = (String)parent.getItemAtPosition(position);
Fragment fragment = null;
switch(item){
case "貨倉地址":
fragment = new WarehouseAddress();
break;
case "托運流程":
fragment = new TransProcess();
break;
case "常見問題":
fragment = new FAQ();
break;
case "聯絡我們":
fragment = new ContactUs();
break;
case "運費計算器":
fragment = new FeeCalculater();
break;
default:
fragment = new BlankTab();
}
controller.fragmentSwitch(getActivity(), fragment);
}
});
}
}
fragmentSwitch method
public void fragmentSwitch(Fragment fragment){
FragmentManager fragmentManager = slideMenuActivity.getSupportFragmentManager();
fragmentManager.beginTransaction()
//.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right)
.replace(android.R.id.tabcontent, fragment)
.commit();
fragmentManager.executePendingTransactions();
}
Finally, I found it. A commit() is missed in onTabChanged.
#Override
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
Log.d(TAB, tabId);
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
Fragment fragment = null;
if (tabId.equals(this.NEWS_TAB)){
fragment = new News();
} else if (tabId.equals(this.SHARE_TAB)){
fragment = new GoodsShare();
} else if (tabId.equals(this.CAMERA_TAB)){
fragment = new Camera();
} else if (tabId.equals(this.STATUS_TAB)){
fragment = new LogisticStatus();
} else if (tabId.equals(this.OTHER_TAB)){
fragment = new Others();
}
if (fragment != null){
t.replace(android.R.id.tabcontent, fragment).commit(); //missing commit() here
} else {
Log.e(TAB, "fragment creation error");
}
}