I am developing an android Application ,In which i am using FragmentTabHost, I am maintaining a container for each tab, But i am getting problem to reload Tabcontent when i reclick on tabs.
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TabWidget;
import android.widget.TextView;
import com.eDeftsoft.FragmentsContainer.AboutContainerFragment;
import com.eDeftsoft.FragmentsContainer.BaseContainerFragment;
import com.eDeftsoft.FragmentsContainer.CityContainerFragment;
import com.eDeftsoft.FragmentsContainer.HomeContainerFragment;
import com.eDeftsoft.FragmentsContainer.PhotosContainerFragment;
import com.eDeftsoft.Utility.CommonDialogues;
public class HomeScreen extends FragmentActivity {
private static final String TAB_1_TAG = "Home";
private static final String TAB_2_TAG = "Photos";
private static final String TAB_3_TAG = "City";
private static final String TAB_4_TAG = "About";
private FragmentTabHost mTabHost;
TabWidget tbwidget;
HomeContainerFragment homeFragment;
PhotosContainerFragment photosFragment;
CityContainerFragment cityFragment;
AboutContainerFragment aboutFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_screen);
initView();
homeFragment = new HomeContainerFragment();
photosFragment = new PhotosContainerFragment();
cityFragment = new CityContainerFragment();
aboutFragment = new AboutContainerFragment();
}
private void initView() {
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(setMyCustomIndicator(this, TAB_1_TAG, "Home"),
HomeContainerFragment.class, null);
mTabHost.addTab(setMyCustomIndicator(this, TAB_2_TAG, "Photos"),
PhotosContainerFragment.class, null);
mTabHost.addTab(setMyCustomIndicator(this, TAB_3_TAG, "City"),
CityContainerFragment.class, null);
mTabHost.addTab(setMyCustomIndicator(this, TAB_4_TAG, "About"),
AboutContainerFragment.class, null);
setTabHostColors();
mTabHost.setCurrentTabByTag("TAB_1_TAG");
mTabHost.setCurrentTab(0);
mTabHost.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE);
mTabHost.getTabWidget().setStripEnabled(false);
tbwidget = mTabHost.getTabWidget();
/*I had Also used This But getting error when i reclick on sametabs*/
// mTabHost.setOnTabChangedListener(new OnTabChangeListener() {
//
// #Override
// public void onTabChanged(String tabId) {
// // TODO Auto-generated method stub
// if (tabId.equals(TAB_1_TAG)) {
// pushFragments(TAB_1_TAG, homeFragment);
// } else if (tabId.equals(TAB_2_TAG)) {
// pushFragments(TAB_1_TAG, photosFragment);
//
// } else if (tabId.equals(TAB_3_TAG)) {
// pushFragments(TAB_1_TAG, cityFragment);
// } else {
// pushFragments(TAB_1_TAG, aboutFragment);
// }
//
// }
// });
}
/*
* insert the fragment into the FrameLayout
*/
// public void pushFragments(String tag, Fragment class1) {
//
// FragmentManager manager = getSupportFragmentManager();
// FragmentTransaction ft = manager.beginTransaction();
//
// ft.replace(R.id.realtabcontent, class1);
// ft.commit();
// }
public TabSpec setMyCustomIndicator(Context con, String tag,
String labeltext) {
TabHost.TabSpec spec = mTabHost.newTabSpec(tag);
View tabIndicator = LayoutInflater.from(this).inflate(
R.layout.tab_indicator, null, false);
((TextView) tabIndicator.findViewById(R.id.title)).setText(labeltext);
// ((ImageView) tabIndicator.findViewById(R.id.icon))
// .setImageResource(resid);
return spec.setIndicator(tabIndicator);
}
#Override
public void onBackPressed() {
boolean isPopFragment = false;
String currentTabTag = mTabHost.getCurrentTabTag();
FragmentManager fm = getSupportFragmentManager();
if (currentTabTag.equals(TAB_1_TAG)) {
for (int entry = 0; entry < fm.getBackStackEntryCount(); entry++) {
String ide = fm.getBackStackEntryAt(entry).getName();
Log.i("TAG" + TAB_1_TAG, "Found fragment: " + ide);
}
isPopFragment = ((BaseContainerFragment) getSupportFragmentManager()
.findFragmentByTag(TAB_1_TAG)).popFragment();
}
else if (currentTabTag.equals(TAB_2_TAG)) {
for (int entry = 0; entry < fm.getBackStackEntryCount(); entry++) {
String ide = fm.getBackStackEntryAt(entry).getName();
Log.i("TAG" + TAB_2_TAG, "Found fragment: " + ide);
}
isPopFragment = ((BaseContainerFragment) getSupportFragmentManager()
.findFragmentByTag(TAB_2_TAG)).popFragment();
}
else if (currentTabTag.equals(TAB_3_TAG)) {
for (int entry = 0; entry < fm.getBackStackEntryCount(); entry++) {
String ide = fm.getBackStackEntryAt(entry).getName();
Log.i("TAG" + TAB_3_TAG, "Found fragment: " + ide);
}
isPopFragment = ((BaseContainerFragment) getSupportFragmentManager()
.findFragmentByTag(TAB_3_TAG)).popFragment();
}
else if (currentTabTag.equals(TAB_4_TAG)) {
for (int entry = 0; entry < fm.getBackStackEntryCount(); entry++) {
String ide = fm.getBackStackEntryAt(entry).getName();
Log.i("TAG" + TAB_4_TAG, "Found fragment: " + ide);
}
isPopFragment = ((BaseContainerFragment) getSupportFragmentManager()
.findFragmentByTag(TAB_4_TAG)).popFragment();
}
if (!isPopFragment) {
CommonDialogues.showAlertDialog(HomeScreen.this,
"Application Will Exit", "Do you Want to Exit");
}
}
private void setTabHostColors() {
for (int i = 0; i < mTabHost.getTabWidget().getChildCount(); i++) {
mTabHost.getTabWidget().getChildAt(i)
.setBackgroundColor(Color.TRANSPARENT);
final TextView tv = (TextView) mTabHost.getTabWidget()
.getChildAt(i).findViewById(android.R.id.title);
if (tv == null)
continue;
else
tv.setTextSize(12);
}
}
#Override
public void onDestroy() {
super.onDestroy();
mTabHost = null;
}
}
When i go in inner fragments of tab1 , like from fragmentA -> Fragment B and From FragmentB -> fragmentC (and finally i am at fragmentC) , When i select Tab1 again i want to reload tabs and FragmentA should Apper.
Any help will be appreciated. I had gone through some of tutorials and coderepository but couldn`t found solution to my problem.
How Can i reload The content Of First tab when first tab is clicked again.
I had asked a question
When i go in inner fragments of tab1 , like from fragmentA -> Fragment B and From FragmentB -> fragmentC (and finally i am at fragmentC) , When i select Tab1 again i want to reload tabs and FragmentA should Apper.
I searched a lot and come to the conclusion , We can implement OnTabChangeListner and when any tab is clicked again we can reset it.(I was having need to reload tab when it is clicked 2nd time)
<!--Layout for Tabs -->
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TabHost
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:baselineAligned="false"
android:orientation="vertical" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<!-- android:background="#drawable/footer" -->
<FrameLayout
android:id="#+id/tabframeLayout"
android:layout_width="fill_parent"
android:layout_height="#dimen/tabframe_height"
android:layout_marginTop="1dp"
android:background="#FBFAFA" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="#dimen/tab_height"
android:background="#F2F0F0" >
</TabWidget>
</FrameLayout>
</LinearLayout>
</TabHost>
</RelativeLayout>
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import com.abc.Fragments.FragmentA;
import com.abc.Fragments.FragmentA1;
import com.abc.Fragments.FragmentA2;
import com.abc.Fragments.FragmentA3;
import com.abc.Utility.CommonDialogues;
public class MyHomeScreen extends FragmentActivity implements
OnTabChangeListener {
private TabHost tabHost;
private String currentSelectedTab;
private HashMap<String, ArrayList<Fragment>> hMapTabs;
final int TEXT_ID = 100;
final String arrTabLabel[] = { "FragmentA", "FragmentA1", "FragmentA2",
"FragmentA3" };
final static int arrIcons[] = { R.drawable.homee, R.drawable.photoi,
R.drawable.cityi, R.drawable.abouti };
private MyTabView arrTabs[] = new MyTabView[4];
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_home_screen);
hMapTabs = new HashMap<String, ArrayList<Fragment>>();
hMapTabs.put(AppConstant.TAB_1_TAG, new ArrayList<Fragment>());
hMapTabs.put(AppConstant.TAB_2_TAG, new ArrayList<Fragment>());
hMapTabs.put(AppConstant.TAB_3_TAG, new ArrayList<Fragment>());
hMapTabs.put(AppConstant.TAB_4_TAG, new ArrayList<Fragment>());
tabHost = (TabHost) findViewById(android.R.id.tabhost);
tabHost.setOnTabChangedListener(this);
tabHost.setup();
TabHost.TabSpec spec = tabHost.newTabSpec(AppConstant.TAB_1_TAG);
tabHost.setCurrentTab(0);
arrTabs[0] = new MyTabView(this, 0, arrTabLabel[0]);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(android.R.id.tabcontent);
}
});
spec.setIndicator(arrTabs[0]);
tabHost.addTab(spec);
spec = tabHost.newTabSpec(AppConstant.TAB_2_TAG);
arrTabs[1] = new MyTabView(this, 1, arrTabLabel[1]);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(android.R.id.tabcontent);
}
});
spec.setIndicator(arrTabs[1]);
tabHost.addTab(spec);
spec = tabHost.newTabSpec(AppConstant.TAB_3_TAG);
arrTabs[2] = new MyTabView(this, 2, arrTabLabel[2]);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(android.R.id.tabcontent);
}
});
spec.setIndicator(arrTabs[2]);
tabHost.addTab(spec);
spec = tabHost.newTabSpec(AppConstant.TAB_4_TAG);
arrTabs[3] = new MyTabView(this, 3, arrTabLabel[3]);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(android.R.id.tabcontent);
}
});
spec.setIndicator(arrTabs[3]);
tabHost.addTab(spec);
// set background for Selected Tab
TextView tv = (TextView) tabHost.getCurrentTabView().findViewById(
TEXT_ID);
// tv.setTextColor(Color.parseColor("#2882C6"));
View iv = (View) tabHost.getCurrentTabView();
// iv.setBackgroundResource(R.color.green);
// Listner for Tab 1//
tabHost.getTabWidget().getChildAt(0)
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (hMapTabs.size() > 0) {
if (tabHost.getTabWidget().getChildAt(0)
.isSelected()) {
if (hMapTabs.get(AppConstant.TAB_1_TAG).size() > 1) {
resetFragment();
}
}
tabHost.getTabWidget().setCurrentTab(0);
tabHost.setCurrentTab(0);
}
}
});
/* Listner for Tab 2 */
tabHost.getTabWidget().getChildAt(1)
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (hMapTabs.size() > 0) {
if (tabHost.getTabWidget().getChildAt(1)
.isSelected()) {
if (hMapTabs.get(AppConstant.TAB_2_TAG).size() > 1) {
resetFragment();
}
}
tabHost.getTabWidget().setCurrentTab(1);
tabHost.setCurrentTab(1);
}
}
});
/* Listner for Tab 3 */
tabHost.getTabWidget().getChildAt(2)
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (hMapTabs.size() > 0) {
if (tabHost.getTabWidget().getChildAt(2)
.isSelected()) {
if (hMapTabs.get(AppConstant.TAB_3_TAG).size() > 1) {
resetFragment();
}
}
tabHost.getTabWidget().setCurrentTab(2);
tabHost.setCurrentTab(2);
}
}
});
/* Listner for Tab 4 */
tabHost.getTabWidget().getChildAt(3)
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (hMapTabs.size() > 0) {
if (tabHost.getTabWidget().getChildAt(3)
.isSelected()) {
if (hMapTabs.get(AppConstant.TAB_4_TAG).size() > 1) {
resetFragment();
}
}
tabHost.getTabWidget().setCurrentTab(3);
tabHost.setCurrentTab(3);
}
}
});
}
/* Method for adding fragment */
public void addFragments(String tabName, Fragment fragment,
boolean animate, boolean add) {
if (add) {
hMapTabs.get(tabName).add(fragment);
}
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
if (animate) {
ft.setCustomAnimations(R.animator.slide_in_right,
R.animator.slide_out_left);
}
ft.replace(android.R.id.tabcontent, fragment);
ft.commit();
}
/* Method for remove fragment */
public void removeFragment() {
Fragment fragment = hMapTabs.get(currentSelectedTab).get(
hMapTabs.get(currentSelectedTab).size() - 2);
hMapTabs.get(currentSelectedTab).remove(
hMapTabs.get(currentSelectedTab).size() - 1);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.setCustomAnimations(R.animator.slide_in_left,
R.animator.slide_out_right);
ft.replace(android.R.id.tabcontent, fragment);
ft.commit();
}
// reset frgment used when clicked on same tab
private void resetFragment() {
Fragment fragment = hMapTabs.get(currentSelectedTab).get(0);
hMapTabs.get(currentSelectedTab).clear();
hMapTabs.get(currentSelectedTab).add(fragment);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.setCustomAnimations(R.animator.slide_in_left,
R.animator.slide_out_right);
ft.replace(android.R.id.tabcontent, fragment);
ft.commit();
}
#Override
public void onBackPressed() {
if (hMapTabs.get(currentSelectedTab).size() <= 1) {
// super.onBackPressed();
CommonDialogues.showAlertDialog(MyHomeScreen.this,
"Application Will Exit", "Do you Want to Exit");
} else {
removeFragment();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (hMapTabs.get(currentSelectedTab).size() == 0) {
return;
}
hMapTabs.get(currentSelectedTab)
.get(hMapTabs.get(currentSelectedTab).size() - 1)
.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onTabChanged(String tabName) {
// TODO Auto-generated method stub
currentSelectedTab = tabName;
// make iteration for unselected tab and make normal background
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
TextView tv = (TextView) tabHost.getTabWidget().getChildAt(i)
.findViewById(TEXT_ID);
tv.setTextColor(Color.parseColor("#BDBDBD"));
View iv = (View) tabHost.getTabWidget().getChildAt(i);
iv.setBackgroundColor(0x00000000);
}
TextView tv = (TextView) tabHost.getCurrentTabView().findViewById(
TEXT_ID); // for Selected Tab
tv.setTextColor(Color.parseColor("#2882C6"));
View iv = (View) tabHost.getCurrentTabView();
if (hMapTabs.get(tabName).size() == 0) {
if (tabName.equals(AppConstant.TAB_1_TAG)) {
addFragments(tabName, new FragmentA(), false, true);
} else if (tabName.equals(AppConstant.TAB_2_TAG)) {
addFragments(tabName, new FragmentA1(), false, true);
} else if (tabName.equals(AppConstant.TAB_3_TAG)) {
addFragments(tabName, new FragmentA2(), false, true);
} else if (tabName.equals(AppConstant.TAB_4_TAG)) {
addFragments(tabName, new FragmentA3(), false, true);
}
} else {
addFragments(
tabName,
hMapTabs.get(tabName).get(hMapTabs.get(tabName).size() - 1),
false, false);
}
switch (tabHost.getCurrentTab()) {
case 0:
// we can also set background color of tabview
// iv.setBackgroundResource(R.color.green);
break;
case 1:
// iv.setBackgroundResource(R.color.red);
break;
case 2:
// iv.setBackgroundResource(R.color.yellow);
break;
case 3:
// iv.setBackgroundResource(R.color.twitter);
break;
}
}
private class MyTabView extends LinearLayout {
int nIdx = -1;
TextView tv;
public MyTabView(Context c, int drawableIdx, String label) {
super(c);
ImageView iv = new ImageView(c);
nIdx = drawableIdx;
// used for forground icons//
iv.setImageResource(arrIcons[nIdx]);
tv = new TextView(c);
tv.setText(label);
tv.setGravity(Gravity.BOTTOM);
tv.setTextSize(14.0f);
tv.setTypeface(null, Typeface.BOLD);
tv.setId(TEXT_ID);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT, 0.9f);
LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT, 0.3f);
layout.setMargins(0, 3, 0, 0);
iv.setLayoutParams(layout);
layout.setMargins(0, 3, 0, 2);
tv.setLayoutParams(param);
tv.setTextColor(Color.parseColor("#BDBDBD"));
setOrientation(LinearLayout.VERTICAL);
setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
addView(iv);
addView(tv);
}
}
}
<!--Layout for FragmenA -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00ff00"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="TAB 1 FIRST SCREEN"
android:textColor="#color/dark_blue"
android:textSize="30sp"
android:textStyle="bold" />
<Button
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dip"
android:text="Go to Next Screen" />
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" >
</EditText>
</LinearLayout>
code for fragment A ...it is extend By Basefragment
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class FirstScreen extends BaseFragment implements OnClickListener {
private Button btnNext;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "I am in onCreate", Toast.LENGTH_LONG).show();
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1_firstscreen,
container, false);
btnNext = (Button) view.findViewById(R.id.btnNext);
btnNext.setOnClickListener(this);
System.out.println("replace");
return view;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
fragmentTabActivity.addFragments(Const.TAB_FIRST,
new SecondScreen(), true, true);
}
}
Code for BaseFragment is
extend this class with all sub fragment which you are going to add on (While adding fragment use myhomescreenActivity(This object) and call add Function in MyHomeScreen ):
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
public class BaseFragment extends Fragment {
protected MyHomeScreen myhomescreenActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myhomescreenActivity = (MyHomeScreen) this.getActivity();
}
public boolean onBackPressed() {
return false;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
}
}
This is the link of repository on Github for further understanding.......
https://github.com/thankimanish/TabUsingFragment
1.You can try moving your code inside the onCreate method to the onResume method so that every time fragment comes to front the code inside the onResume gets executed and reloads the frament.
2.You can also try overriding the onHiddenChanged method of the fragment and reload the fragment as soon as fragment becomes visible
Related
Please suggest me how implement Swipe left or right in my app? Is page viewer or gesture can be used. I get content for text view from string array when item clicked. I am new to app development.
My MainActivity xml
import android.app.FragmentTransaction;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener
{
private ActionBarDrawerToggle actionBarDrawerToggle;
private DrawerLayout drawerLayout;
private ListView navList;
private FragmentManager fragmentManager;
boolean nightmode=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = (DrawerLayout)findViewById(R.id.drawerlayout);
navList = (ListView)findViewById(R.id.navlist);
String[] versionName = getResources().getStringArray(R.array.version_names);
navList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, versionName);
navList.setAdapter(adapter);
navList.setOnItemClickListener(this);
actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,R.string.opendrawer,R.string.closedrawer);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
fragmentManager = getSupportFragmentManager();
OnSelectionChanged(0);
}
public void OnSelectionChanged(int position) {
DescriptionFragment descriptionFragment = (DescriptionFragment) getFragmentManager()
.findFragmentById(R.id.description_fragment);
if (descriptionFragment != null){
// If description is available, we are in two pane layout
// so we call the method in DescriptionFragment to update its content
descriptionFragment.setDescription(position);
} else {
DescriptionFragment newDesriptionFragment = new DescriptionFragment();
Bundle args = new Bundle();
args.putInt(DescriptionFragment.KEY_POSITION,position);
newDesriptionFragment.setArguments(args);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the backStack so the User can navigate back
fragmentTransaction.replace(R.id.fragment_container,newDesriptionFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
TextView textElement = (TextView) findViewById(R.id.version_description);
FrameLayout mainLayout = (FrameLayout) findViewById(R.id.fragment_container);
if(nightmode) textElement.setTextColor(Color.WHITE);
switch(item.getItemId()){
case R.id.action_settings:
if (nightmode) {
mainLayout.setBackgroundResource(R.color.white);
textElement.setTextColor(Color.BLACK);
nightmode=false;
}else {
mainLayout.setBackgroundResource(R.color.background_color);
textElement.setTextColor(Color.WHITE);
nightmode=true;
}
break;
case android.R.id.home:
if (drawerLayout.isDrawerOpen(navList)){
drawerLayout.closeDrawer(navList);
}else{
drawerLayout.openDrawer(navList);
}
break;
case R.id.action_share:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
OnSelectionChanged(position);
drawerLayout.closeDrawer(navList);
}
}
My DescriptionFragment
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by sathi on 16-01-2016.
*/
public class DescriptionFragment extends Fragment {
final static String KEY_POSITION = "position";
int mCurrentPosition = -1;
String[] mVersionDescriptions;
TextView mVersionDescriptionTextView;
public DescriptionFragment(){
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mVersionDescriptions = getResources().getStringArray(R.array.version_descriptions);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/* DescriptionFragment descriptionFragment = new DescriptionFragment();
Object fromFragment = null;
Object toFragment=null;
descriptionFragment.addFragment(Fragment fromFragment, Fragment toFragment);*/
// If the Activity is recreated, the savedInstanceStare Bundle isn't empty
// we restore the previous version name selection set by the Bundle.
// This is necessary when in two pane layout
if (savedInstanceState != null) {
mCurrentPosition = savedInstanceState.getInt(KEY_POSITION);
}
// FragmentTransaction fragmentTransaction = null;
// fragmentTransaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left);
View view = inflater.inflate(R.layout.fragment_description, container, false);
mVersionDescriptionTextView = (TextView) view.findViewById(R.id.version_description);
return view;
/* DescriptionFragment fragment1 = new DescriptionFragment();
(getSupportFragmentManager().beginTransaction().add(R.id.description_fragment, fragment1)
.add(R.id.description_fragment, fragment1).commit()){
}*/
}
public void addFragment(Fragment fromFragment, Fragment toFragment) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.fragment_container,toFragment, toFragment.getClass().getName());
transaction.hide(fromFragment);
transaction.addToBackStack(toFragment.getClass().getName());
transaction.commit();
}
public void replaceFragment(Fragment fromFragment, Fragment toFragment) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_container,toFragment, toFragment.getClass().getName());
transaction.hide(fromFragment);
transaction.addToBackStack(toFragment.getClass().getName());
transaction.commit();
}
private FragmentManager getSupportFragmentManager() {
return null;
}
#Override
public void onStart() {
super.onStart();
// During the startup, we check if there are any arguments passed to the fragment.
// onStart() is a good place to do this because the layout has already been
// applied to the fragment at this point so we can safely call the method below
// that sets the description text
Bundle args = getArguments();
if (args != null){
// Set description based on argument passed in
setDescription(args.getInt(KEY_POSITION));
} else if(mCurrentPosition != -1){
// Set description based on savedInstanceState defined during onCreateView()
setDescription(mCurrentPosition);
}
}
public void setDescription(int descriptionIndex){
mVersionDescriptionTextView.setText(mVersionDescriptions[descriptionIndex]);
mCurrentPosition = descriptionIndex;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save the current description selection in case we need to recreate the fragment
outState.putInt(KEY_POSITION,mCurrentPosition);
}
}
I didn't understand if that actually what you trying to do but as i understood if you want the TextView moves automatically in one line to show the rest of it make this:
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:freezesText="true"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true" />
and in code after defining it's view make this:
textView.setChecked(true);
I want to change tab by swiping on the screen i am creating tabs using fragment tabhost but when i implement swiping feature in my project it doesn't open nested fragment in each tab means i am opening nested child fragment inside each tab.
Please tell me its very important for me.
here is my code.
this my Main activity.
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
public class Home extends FragmentActivity implements OnTabChangeListener,OnPageChangeListener {
private static final String TAB_1_TAG = "tab_1";
private static final String TAB_2_TAG = "tab_2";
private static final String TAB_3_TAG = "tab_3";
private static final String TAB_4_TAG = "tab_4";
private static final String TAB_5_TAG = "tab_5";
private FragmentTabHost mTabHost;
// ViewPager viewPager;
// TabsPagerAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
viewPager =(ViewPager)findViewById(R.id.viewpager);
initView();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
viewPager.setOnPageChangeListener(Home.this);
}
private void initView() {
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
// mTabHost.addTab(mTabHost.newTabSpec(TAB_1_TAG).setIndicator("Talk", getResources().getDrawable(R.drawable.ic_launcher)), TalkContainerFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec(TAB_1_TAG).setIndicator("Talk"), TalkContainerFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec(TAB_2_TAG).setIndicator("Map"), Map_fragment.class, null);
// mTabHost.addTab(mTabHost.newTabSpec(TAB_3_TAG).setIndicator("Go"), GoContainerFragment.class, null);
// mTabHost.addTab(mTabHost.newTabSpec(TAB_4_TAG).setIndicator("Watch"), WatchContainerFragment.class, null);
// mTabHost.addTab(mTabHost.newTabSpec(TAB_5_TAG).setIndicator("More"), MoreContainerFragment.class, null);
/* Increase tab height programatically
* tabs.getTabWidget().getChildAt(1).getLayoutParams().height = 150;
*/
for (int i = 0; i < mTabHost.getTabWidget().getChildCount(); i++) {
final TextView tv = (TextView) mTabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);
if (tv == null)
continue;
else
tv.setTextSize(10);
}
}
#Override
public void onBackPressed() {
boolean isPopFragment = false;
String currentTabTag = mTabHost.getCurrentTabTag();
if (currentTabTag.equals(TAB_1_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_1_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_2_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_2_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_3_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_3_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_4_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_4_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_5_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_5_TAG)).popFragment();
}
if (!isPopFragment) {
finish();
}
}
#Override
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
int pos = this.mTabHost.getCurrentTab();
this.viewPager.setCurrentItem(pos);
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
int pos = this.viewPager.getCurrentItem();
this.mTabHost.setCurrentTab(pos);
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
}
}
This Container fragment class
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
public class BaseContainerFragment extends Fragment {
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.replace(R.id.container_framelayout, fragment);
transaction.commit();
getChildFragmentManager().executePendingTransactions();
}
public boolean popFragment() {
Log.e("test", "pop fragment: " + getChildFragmentManager().getBackStackEntryCount());
boolean isPop = false;
if (getChildFragmentManager().getBackStackEntryCount() > 0) {
isPop = true;
getChildFragmentManager().popBackStack();
}
return isPop;
}
}
Created Container for each TAb
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TalkContainerFragment extends BaseContainerFragment {
private boolean mIsViewInited;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.e("test", "tab 1 oncreateview");
return inflater.inflate(R.layout.container_fragment, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.e("test", "tab 1 container on activity created");
if (!mIsViewInited) {
mIsViewInited = true;
initView();
}
}
TAlk.java file
import java.util.HashSet;
import java.util.Set;
import org.json.JSONObject;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
public class Talk extends Fragment {
/** Define global variables over here */
//private ProgressDialog pDialog;
// StaticApiList sal;
// TalkModelAll tma;
JSONObject myJasonObject = null;
private ListView lv;
// private ArrayList<TalkModelAll> m_ArrayList = null;
//ArrayList<String> stringArrayList = new ArrayList<String>();
// TalkArrayAdapter taa;
Set<String> uniqueValues = new HashSet<String>();
TextView rowTextView = null;
boolean vivek = false;
int postid;
String title;
String thumsrc;
String largeimg;
String excert;
String description;
String cat;
String myUrl;
String jsonString;
int mCurCheckPosition;
String check_state = null;
String ccc;
LinearLayout myLinearLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.talk, null);
Button btn = (Button) rootView.findViewById(R.id.your_btn_id);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Here TalkDetail is name of class that needs to open
TalkDetail talkfragment = new TalkDetail();
// if U need to pass some data
Bundle bundle = new Bundle();
//
// bundle.putString("title", m_ArrayList.get(arg2).title);
// bundle.putString("largeimg", m_ArrayList.get(arg2).largeimg);
// bundle.putString("excert", m_ArrayList.get(arg2).excert);
// bundle.putString("description", m_ArrayList.get(arg2).description);
// bundle.putString("cat", m_ArrayList.get(arg2).cat);
// //bundle.putInt("postid", m_ArrayList.get(arg2).postid);
talkfragment.setArguments(bundle);
((BaseContainerFragment)getParentFragment()).replaceFragment(talkfragment, true);
}
});
return rootView;
}
}
Talkddetail.class
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class TalkDetail extends android.support.v4.app.Fragment {
/* (non-Javadoc)
* #see android.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view=LayoutInflater.from(getActivity()).inflate(R.layout.activity_talk_detail, null);
return view;
}
}
You have to use a ViewPager. Read more at Android Developer website. You can find a lot of custom view pagers on Android Arsenal. This is the current standard, so you should use this over TabHost.
you can have a look at its demo in eclips go to
file->other->android Activity->tabbed activity
or learn the view Fliper from android developer website
package com.example.mystack;
import java.util.Locale;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a {#link FragmentPagerAdapter}
* derivative, which will keep every loaded fragment in memory. If this
* becomes too memory intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(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.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show FirstFragment
return new TalkContainerFragment(0, "Talk");
case 1: // Fragment # 0 - This will show FirstFragment different title
return new Map_fragment(1, "map");
//Rest of them add here
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
and xml is
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mystack.MainActivity" />
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.mystack.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Use this method in your activity for all fragment trancation
// For the Fragment Replace And AddtobackStack
void replaceFragment(Fragment fragment) {
String backStateName = fragment.getClass().getName();
String fragmentTag = backStateName;
FragmentManager manager = this.getSupportFragmentManager();
boolean fragmentPopped = manager
.popBackStackImmediate(backStateName, 0);
if (!fragmentPopped && manager.findFragmentByTag(fragmentTag) == null) {
// fragment not in back stack, create it.
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.container, fragment, fragmentTag);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(backStateName);
ft.commit();
}
}
and use it like this whenever you need to go for nested fragment from one fragmnet
if (DetailsFragment.this.getActivity() != null
&& DetailsFragment.this.getActivity() instanceof HomeActivity)
((HomeActivity) DetailsFragment.this.getActivity())
.replaceFragment(cartfragment);
in the above suppose i am in details fragment and from here i want to go to cartfragment
then get the activitiy instance and cast it like the above
I'm trying to learn how to use Fragments in android. I create the separate classes and layouts. I'm having trouble understanding how I'm supposed to link them all. What exactly goes in my Main class? Could someone please demonstrate exactly how to use fragments in a very basic way?
please read this first as, i think, i has the very basics. Below is an example:
MainActivity:
public class MainActivity extends Activity implements OnClickListener{
private final String TAG = "MainActivity";
private int btn00Clicks = 0;
private int btn01Clicks = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Fragment mSelectedFragment = null;
switch (v.getId()) {
case R.id.btn00:
Bundle mBundle00 = new Bundle();
String clicks00 = Integer.toString(btn00Clicks);
mBundle00.putString("btn00_clicks", clicks00);
mSelectedFragment = new Fragment00();
mSelectedFragment.setArguments(mBundle00);
if (mSelectedFragment != null) {
FragmentManager mFragmentManager = getFragmentManager();
mFragmentManager.beginTransaction()
.replace(R.id.fragment00ID, mSelectedFragment).commit();
}
btn00Clicks++;
break;
case R.id.btn01:
Bundle mBundle01 = new Bundle();
String clicks01 = Integer.toString(btn01Clicks);
mBundle01.putString("btn01_clicks", clicks01);
mSelectedFragment = new Fragment01();
mSelectedFragment.setArguments(mBundle01);
if (mSelectedFragment != null) {
FragmentManager mFragmentManager = getFragmentManager();
mFragmentManager.beginTransaction()
.replace(R.id.fragment00ID, mSelectedFragment).commit();
}
btn01Clicks++;
}
}
}
Fragment00.java:
public class Fragment00 extends Fragment {
private final String TAG = "Fragment00";
TextView mTv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment00, null);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
mTv = (TextView) getView().findViewById(R.id.fragment00Tv00);
if (getArguments() != null) {
String str = getArguments().getString("btn00_clicks").toString();
mTv.setText("the Button was clicked "+str+ " time(s)");
Log.i(TAG, "onActivityCreated(): "+str);
}else {
Log.i(TAG, "onActivityCreated(): getArguments() is NULL");
}
}
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
}
Fragment01.java:
public class Fragment01 extends Fragment {
private static final String TAG = "Fragment01";
TextView mTv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment01, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
mTv = (TextView) getView().findViewById(R.id.fragment01Tv00);
if (getArguments() != null) {
String str = getArguments().getString("btn01_clicks").toString();
mTv.setText("the Button was clicked "+str+ " time(s)");
Log.i(TAG, "onActivityCreated(): "+str);
}else {
Log.i(TAG, "onActivityCreated(): getArguments() is NULL");
}
}
}
MainActivity_layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="com.example.fragments01.MainActivity"
tools:ignore="MergeRootFrame">
<RelativeLayout
android:id="#+id/mainRelativeLayout00"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="top|center_vertical">
<Button
android:id="#+id/btn00"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="fragment_one"
android:onClick="onClick"></Button>
<Button
android:id="#+id/btn01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/btn00"
android:text="Fragment two"
android:onClick="onClick"></Button>
<fragment
android:name="com.example.fragments01.Fragment00"
android:id="#+id/fragment00ID"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/btn01">
</fragment>
</RelativeLayout>
Fragment00_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="com.example.fragments01.Fragment00"
tools:ignore="MergeRootFrame"
android:background="#00ffff">
<RelativeLayout
android:id="#+id/fragment00RelativeLayout00"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="top|center_vertical">
<TextView
android:id="#+id/fragment00Tv00"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</TextView>
</RelativeLayout>
Fragment01_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="com.example.fragments01.Fragment01"
tools:ignore="MergeRootFrame"
android:background="#ffff00">
<RelativeLayout
android:id="#+id/fragment01RelativeLayout00"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="top|center_vertical">
<TextView
android:id="#+id/fragment01Tv00"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Fragment two">
</TextView>
<Button
android:id="#+id/fragment01Btn00"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button of fragment two"
android:layout_below="#+id/fragment01Tv00">
</Button>
</RelativeLayout>
In your main class you produce one or more fragments... While you produce each fragment it's pretty similar to Activity,but has its own lifecircle(google it).
here's example on fragment:
public class DummySectionFragment3 extends Fragment
{
public DummySectionFragment3() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.exercise_layout,
container, false);
return rootView;
}
}
in OnCreateView() method you do what you usually do with activity.
My Main class contains SectionsPagerAdapter that switches between the fragments(A pager like in API samples)
create 2 or 3 fragments and just try it...
I didn't find any good example on it,so I just tried the above.
http://www.c-sharpcorner.com/UploadFile/2fd686/fragments/
Here's one good link with tabs and fragments.
You can also define your fragments in your xml.
Same as what LetsAmrIt posted, just another example:
Main Activity:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Comparator;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class MainActivity extends Activity implements MyListFragment.MovieSelectedListener
{
Movie movie;
ListView movieList;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getWindow().setFormat(PixelFormat.RGBA_8888);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DITHER);
setContentView(R.layout.activity_main);
try
{
FileInputStream fis = openFileInput("movies");
if (fis != null)
{
ObjectInputStream in = new ObjectInputStream(fis);
movie = (Movie) in.readObject();
in.close();
Toast.makeText(this, "Movies loaded.", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
Toast.makeText(this, "No movies to load.", Toast.LENGTH_SHORT).show();
}
if (movie == null)
{
movie = new Movie();
movie.addMovie("Harry Potter", "12 January", "Thriller", 4, "Some people", "Bad", "Someone", "Walmer Park");
}
loadFragments();
}
public void loadFragments()
{
if ((getResources().getConfiguration().screenLayout &Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE)
{
Log.d("Screen Size: ", "LARGE");
// obtain the fragment manager
FragmentManager fragmentManager = getFragmentManager();
// determine if the fragment has already been loaded (may have happened)
Fragment listfrag = fragmentManager.findFragmentById(R.id.fragment_container);
// place fragment into container if not already there
if (listfrag == null) {
// start a transaction that will handle the swapping in/out
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
// multiple additions to the transaction can be done so that they
// changes will be done simultaneously
MyListFragment fragment1 = new MyListFragment();
fragmentTransaction.add(R.id.fragment_container, fragment1);
ViewFragment fragment2 = new ViewFragment();
fragmentTransaction.add(R.id.details_container, fragment2);
Bundle args = new Bundle();
args.putSerializable("Movie", movie);
fragment1.setArguments(args);
// commit the changes, i.e. do it!
fragmentTransaction.commit();
}
}
else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {
Log.d("Screen Size: ", "NORMAL");
// obtain the fragment manager
FragmentManager fragmentManager = getFragmentManager();
// determine if the fragment has already been loaded (may have happened)
Fragment listfrag = fragmentManager.findFragmentById(R.id.fragment_container);
// place fragment into container if not already there
if (listfrag == null) {
// start a transaction that will handle the swapping in/out
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
// multiple additions to the transaction can be done so that they
// changes will be done simultaneously
MyListFragment fragment = new MyListFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
Bundle args = new Bundle();
args.putSerializable("Movie", movie);
fragment.setArguments(args);
// commit the changes, i.e. do it!
fragmentTransaction.commit();
}
}
else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {
Log.d("Screen Size: ", "SMALL");
}
else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
Log.d("Screen Size: ", "XLARGE");
Log.d("Screen Size: ", "LARGE");
// obtain the fragment manager
FragmentManager fragmentManager = getFragmentManager();
// determine if the fragment has already been loaded (may have happened)
Fragment listfrag = fragmentManager.findFragmentById(R.id.fragment_container);
// place fragment into container if not already there
if (listfrag == null) {
// start a transaction that will handle the swapping in/out
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
// multiple additions to the transaction can be done so that they
// changes will be done simultaneously
MyListFragment fragment1 = new MyListFragment();
fragmentTransaction.add(R.id.fragment_container, fragment1);
ViewFragment fragment2 = new ViewFragment();
fragmentTransaction.add(R.id.details_container, fragment2);
Bundle args = new Bundle();
args.putSerializable("Movie", movie);
fragment1.setArguments(args);
// commit the changes, i.e. do it!
fragmentTransaction.commit();
}
}
else {
Log.d("Screen Size: ","UNKNOWN_CATEGORY_SCREEN_SIZE");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
public void pushFragment(Movie curMovie) {
// obtain the fragment manager
FragmentManager fragmentManager = getFragmentManager();
// start a transaction that will handle the swapping in/out
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
// add new fragment, BUT remember previous one, so that BACK button
// returns to it
ViewFragment fragment = new ViewFragment();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack("view");
Bundle args = new Bundle();
args.putSerializable("curMovie", curMovie);
fragment.setArguments(args);
// commit the changes, i.e. do it!
fragmentTransaction.commit();
}
#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.
MyListFragment fragment = (MyListFragment) getFragmentManager().findFragmentById(R.id.fragment_container);
switch(item.getItemId())
{
case R.id.action_about:
About();
return true;
case R.id.action_add:
addMovie();
return true;
case R.id.sort_Title:
fragment.sortTitle();
return true;
case R.id.sort_Date:
fragment.sortDateViewed();
return true;
case R.id.sort_Rating:
fragment.sortRating();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == 1)
{
if (resultCode == RESULT_OK)
{
String title = data.getStringExtra("titleText");
String genre = data.getStringExtra("genreText");
String actors = data.getStringExtra("actorsText");
int rating = data.getIntExtra("ratingValue", 0);
String date = data.getStringExtra("dateWatched");
String watchedWith = data.getStringExtra("watchedWithText");
String watchedAt = data.getStringExtra("watchedAtText");
String comment = data.getStringExtra("commentText");
movie.addMovie(title, date, genre, rating, actors, comment, watchedWith, watchedAt);
write();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public void write()
{
try
{
FileOutputStream fos = openFileOutput("movies", Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(movie);
fos.close();
Toast.makeText(this, "Movies saved.", Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(this, "Movies could not be saved.", Toast.LENGTH_SHORT).show();
}
}
public void addMovie()
{
Intent intentAdd = new Intent(MainActivity.this, AddMovie.class);
startActivityForResult(intentAdd, 1);
}
public void About()
{
Intent intentAbout = new Intent(this, About.class);
startActivity(intentAbout);
}
public void addDetails(Movie curMovie)
{
// obtain the fragment manager
FragmentManager fragmentManager = getFragmentManager();
// start a transaction that will handle the swapping in/out
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
ViewFragment fragment = new ViewFragment();
// REPLACE the existing fragment with another one
fragmentTransaction.replace(R.id.details_container, fragment);
Bundle args = new Bundle();
args.putSerializable("curMovie", curMovie);
fragment.setArguments(args);
// commit the changes, i.e. do it!
fragmentTransaction.commit();
}
#Override
public void onMovieSelected(String movieName) {
// TODO Auto-generated method stub
if ((getResources().getConfiguration().screenLayout &Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE)
{
Log.d("Screen Size: ", "LARGE");
Movie current = movie.getMovie(movieName);
Context context = getApplicationContext();
CharSequence text = current.MovieTitle;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
addDetails(current);
}
else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {
Log.d("Screen Size: ", "NORMAL");
Movie current = movie.getMovie(movieName);
Context context = getApplicationContext();
CharSequence text = current.MovieTitle;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
pushFragment(current);
}
else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {
Log.d("Screen Size: ", "SMALL");
}
else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
Log.d("Screen Size: ", "XLARGE");
}
else {
Log.d("Screen Size: ","UNKNOWN_CATEGORY_SCREEN_SIZE");
}
}
#Override
public void onDeleteSelected(String movie, MovieAdapter adapter) {
// TODO Auto-generated method stub
this.movie.deleteMovie(movie);
adapter.notifyDataSetChanged();
write();
}
}
Movie Adapter:
import java.util.List;
import android.content.Context;
import android.view.*;
import android.widget.ArrayAdapter;
import android.widget.RatingBar;
import android.widget.TextView;
public class MovieAdapter extends ArrayAdapter<Movie> {
private Context context;
private List<Movie> movies;
public MovieAdapter(Context context, List<Movie> movies)
{
super(context, R.layout.movie_layout, movies);
this.context = context;
this.movies = movies;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View movieView = convertView;
if(movieView == null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
movieView = inflater.inflate(R.layout.movie_layout, parent, false);
}
movieView.setTag(movies.get(position));
TextView txtTitle = (TextView) movieView.findViewById(R.id.txtTitle);
TextView txtDate = (TextView) movieView.findViewById(R.id.txtDate);
RatingBar ratingBar = (RatingBar) movieView.findViewById(R.id.ratingBar);
txtTitle.setText(movies.get(position).MovieTitle);
txtDate.setText("Date Viewed: "+movies.get(position).dateViewed);
ratingBar.setIsIndicator(true);
ratingBar.setNumStars(movies.get(position).rating);
ratingBar.setRating(movies.get(position).rating);
return movieView;
}
}
List Fragment:
import java.util.Comparator;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.util.Log;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.TextView;
public class MyListFragment extends Fragment{
Movie movie;
MovieAdapter adapter;
MovieSelectedListener callBack;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.list_fragment, container, false);
ListView movieList = (ListView)view.findViewById(R.id.movieList);
movieList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
TextView movie = (TextView)view.findViewById(R.id.txtTitle);
String title = movie.getText().toString();
callBack.onMovieSelected(title);
}
});
if (getArguments() != null)
movie = (Movie)getArguments().getSerializable("Movie");
Log.v("PASSED","Got here");
adapter = new MovieAdapter(getActivity(), movie.movies);
movieList.setAdapter(adapter);
movieList.setLongClickable(true);
movieList.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, final View view,
int position, long id) {
// TODO Auto-generated method stub
AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
dialog.setMessage("Are you sure you want to delete this movie?");
dialog.setTitle("Alert Message");
dialog.setCancelable(false);
dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
TextView movie = (TextView)view.findViewById(R.id.txtTitle);
String title = movie.getText().toString();
callBack.onDeleteSelected(title, adapter);
}
});
dialog.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
dialog.show();
return false;
}
});
return view;
}
public interface MovieSelectedListener
{
public void onMovieSelected(String movie);
public void onDeleteSelected(String movie, MovieAdapter adapter);
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);;
try
{
callBack = (MovieSelectedListener) activity;
}
catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement MovieSelectedListener");
}
}
public void sortTitle()
{
adapter.sort(new Comparator<Movie>() {
public int compare(Movie lhs, Movie rhs) {
return lhs.MovieTitle.compareTo(rhs.MovieTitle);
}
});
adapter.notifyDataSetChanged();
}
public void sortDateViewed()
{
adapter.sort(new Comparator<Movie>() {
public int compare(Movie lhs, Movie rhs) {
return lhs.dateViewed.compareTo(rhs.dateViewed);
}
});
adapter.notifyDataSetChanged();
}
public void sortRating()
{
adapter.sort(new Comparator<Movie>() {
public int compare(Movie lhs, Movie rhs) {
return ((Integer)lhs.rating).compareTo(rhs.rating);
}
});
adapter.notifyDataSetChanged();
}
}
View Fragment
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RatingBar;
import android.widget.TextView;
public class ViewFragment extends Fragment {
Movie curMovie = new Movie("Empty", "Empty", "Empty", 5, "Empty", "Empty", "Empty", "Empty");
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.view_fragment, container, false);
if (getArguments() != null)
curMovie = (Movie)getArguments().getSerializable("curMovie");
TextView titleTxt = (TextView)view.findViewById(R.id.titleTxt);
titleTxt.setText(curMovie.MovieTitle);
TextView genreTxt = (TextView)view.findViewById(R.id.genreTxt);
genreTxt.setText(curMovie.genre);
TextView actorsTxt = (TextView)view.findViewById(R.id.actorsTxt);
actorsTxt.setText(curMovie.actors);
RatingBar ratingRes = (RatingBar)view.findViewById(R.id.ratingRes);
ratingRes.setIsIndicator(true);
ratingRes.setNumStars(curMovie.rating);
ratingRes.setRating(curMovie.rating);
TextView dateWatchedTxt = (TextView)view.findViewById(R.id.dateWatchedTxt);
dateWatchedTxt.setText(curMovie.dateViewed);
TextView watchedWithTxt = (TextView)view.findViewById(R.id.watchedWithTxt);
watchedWithTxt.setText(curMovie.viewedWith);
TextView watchedAtTxt = (TextView)view.findViewById(R.id.watchedAtTxt);
watchedAtTxt.setText(curMovie.viewedWhere);
TextView commentTxt = (TextView)view.findViewById(R.id.commentTxt);
commentTxt.setText(curMovie.comments);
// Inflate the layout for this fragment
return view;
}
}
Movie:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Movie implements Serializable
{
String MovieTitle, dateViewed, actors, genre, comments, viewedWith, viewedWhere;
int rating;
public Movie(String MovieTitle, String dateViewed, String genre, int rating, String actors, String comments, String viewedWith, String viewedWhere)
{
this.MovieTitle = MovieTitle;
this.dateViewed = dateViewed;
this.genre = genre;
this.rating = rating;
this.actors = actors;
this.comments = comments;
this.viewedWith = viewedWith;
this.viewedWhere = viewedWhere;
}
final List<Movie> movies = new ArrayList<Movie>();
public Movie(){
}
public void addMovie(String MovieTitle, String dateViewed, String genre, int rating, String actors, String comments, String viewedWith, String viewedWhere)
{
movies.add(new Movie(MovieTitle, dateViewed, genre, rating, actors, comments, viewedWith, viewedWhere));
}
public void deleteMovie(String movieTitle)
{
Movie toDelete = getMovie(movieTitle);
movies.remove(toDelete);
}
public Movie getMovie(String movie)
{
for(Movie mov:movies)
{
if(mov.MovieTitle.equals(movie))
{
return mov;
}
}
return null;
}
}
Add Movie:
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.Toast;
public class AddMovie extends Activity
{
EditText title2;
EditText genre2;
EditText actors2;
RatingBar rating2;
EditText date2;
EditText watchedWith2;
EditText watchedAt2;
EditText comment2;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_movie);
//savedInstance
title2 = (EditText)findViewById(R.id.title);
genre2 = (EditText)findViewById(R.id.genre);
actors2 = (EditText)findViewById(R.id.actors);
rating2 = (RatingBar)findViewById(R.id.rating);
date2 = (EditText)findViewById(R.id.dateWatched);
watchedWith2 = (EditText)findViewById(R.id.watchedWith);
watchedAt2 = (EditText)findViewById(R.id.watchedAt);
comment2 = (EditText)findViewById(R.id.comment);
if ((savedInstanceState != null) && (savedInstanceState.containsKey("TITLE_STATE_KEY")))
{
title2.setText(savedInstanceState.getString("TITLE_STATE_KEY"));
actors2.setText(savedInstanceState.getString("ACTORS_STATE_KEY"));
genre2.setText(savedInstanceState.getString("GENRE_STATE_KEY"));
comment2.setText(savedInstanceState.getString("GC_STATE_KEY"));
watchedWith2.setText(savedInstanceState.getString("WITH_STATE_KEY"));
watchedAt2.setText(savedInstanceState.getString("LOCATION_STATE_KEY"));
date2.setText(savedInstanceState.getString("DATE_STATE_KEY"));
rating2.setRating(savedInstanceState.getFloat("RATING_STATE_KEY"));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_movie, 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.
switch(item.getItemId())
{
case R.id.action_settings:
return true;
case R.id.action_done:
done();
default:
return super.onOptionsItemSelected(item);
}
}
public void done()
{
EditText title = (EditText)findViewById(R.id.title);
String titleText = title.getText().toString();
EditText genre = (EditText)findViewById(R.id.genre);
String genreText = genre.getText().toString();
EditText actors = (EditText)findViewById(R.id.actors);
String actorsText = actors.getText().toString();
RatingBar rating = (RatingBar)findViewById(R.id.rating);
int ratingValue = Math.round(rating.getRating());
EditText date = (EditText)findViewById(R.id.dateWatched);
String dateWatched = date.getText().toString();
EditText watchedWith = (EditText)findViewById(R.id.watchedWith);
String watchedWithText = watchedWith.getText().toString();
EditText watchedAt = (EditText)findViewById(R.id.watchedAt);
String watchedAtText = watchedAt.getText().toString();
EditText comment = (EditText)findViewById(R.id.comment);
String commentText = comment.getText().toString();
Intent intent = new Intent(AddMovie.this, MainActivity.class);
intent.putExtra("titleText", titleText);
intent.putExtra("genreText", genreText);
intent.putExtra("actorsText", actorsText);
intent.putExtra("ratingValue", ratingValue);
intent.putExtra("dateWatched", dateWatched);
intent.putExtra("watchedWithText", watchedWithText);
intent.putExtra("watchedAtText", watchedAtText);
intent.putExtra("commentText", commentText);
setResult(RESULT_OK, intent);
finish();
}
#Override
public void onSaveInstanceState(Bundle saveInstanceState)
{
saveInstanceState.putString("TITLE_STATE_KEY", title2.getText().toString());
saveInstanceState.putString("GENRE_STATE_KEY", genre2.getText().toString());
saveInstanceState.putString("GC_STATE_KEY", comment2.getText().toString());
saveInstanceState.putString("DATE_STATE_KEY", date2.getText().toString());
saveInstanceState.putString("ACTORS_STATE_KEY", actors2.getText().toString());
saveInstanceState.putString("WITH_STATE_KEY", watchedWith2.getText().toString());
saveInstanceState.putString("LOCATION_STATE_KEY", watchedAt2.getText().toString());
saveInstanceState.putFloat("RATING_STATE_KEY", rating2.getRating());
super.onSaveInstanceState(saveInstanceState);
}
}
The basic is like this:
Create one Activity and 2 Fragments.
If something happens in FragmantA something should change in fragmentB right. So the Activity links Fragment A and B together. What do you need for that: an Interface.
So create an Interface with a method which takes the right properties (don't forget the datatype). Now you can implement the interface in your activity.
After this you should initialize the interface in FragmentA in the onActivityCreated method. Perform the changes and send the data to the interfacemethod in the Activity. Create a reference to FragmentB using the FragmentManager. Now you can send the data/changes to FragmentB.
I hope you understand this ;). cheers
I made a sample project that doesn't use ViewPager and all the weird stuff, just the link between Activity and Fragment here on Stack Overflow and the same thing on Code Review to demonstrate it, click either links to see the project.
I used this link to get started
http://www.techotopia.com/index.php/Using_Fragments_in_Android_-_A_Worked_Example
This guy uses 2 different types of listeners and takes in the user input on the first fragment. The 2nd fragment outputs the data!
Goodluck!
I was reading the documentation on Fragment on the Developer site. I created a new project targeting api 8:android 2.2. I have the Android Support Library install, and I added the android support library to the project. I started implementing the helper method showDetails, and I get the red squiggly line saying that "a_item could not be resolved". I don't remember the instruction saying create an a_item variable or add a layout with a_item id.
In addition, in the detail activity, I am getting an error message too. (getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();) It says "The method add(int, Fragment) in the type FragmentTransaction is not applicable for the arguments (int, DetailsFragment)". Did I miss something in the instructions?
Here are my sample codes:
package com.example.fragmentlayout;
import android.app.Activity;
import android.app.Fragment;
import android.content.res.Configuration;
import android.os.Bundle;
public class DetailsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getResources().getConfiguration().ORIENTATION_LANDSCAPE == Configuration.ORIENTATION_LANDSCAPE )
{
finish();
return;
}
if(savedInstanceState == null)
{
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
}
}
}
Here is the Titles Fragment:
package com.example.fragmentlayout;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class TitlesFragment extends ListFragment {
boolean mDualPane;
int mCurCheckPosition =0;
String[] titles = {"Title 1", "Title 2", "Title 3"};
String[] Details = {"Details for one", "Details for two", "Details for Three"};
#SuppressLint("InlinedApi")
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_activated_1, titles));
View detailsFrame = getActivity().findViewById(R.id.fragment2);
mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
if(savedInstanceState != null)
{
mCurCheckPosition = savedInstanceState.getInt("curChoise", 0);
}
if(mDualPane)
{
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
showDetails(mCurCheckPosition);
}
}
private void showDetails(int index) {
mCurCheckPosition = index;
if(mDualPane)
{
getListView().setItemChecked(index, true);
DetailsFragment details = (DetailsFragment) getFragmentManager().findFragmentById(R.id.fragment2);
if(details == null || details.getShownIndex() != index)
{
details = DetailsFragment.newInstance(index);
FragmentTransaction ft = getFragmentManager().beginTransaction();
if(index ==0)
{
ft.replace(R.id.fragment2, details);
} else
{
ft.replace(R.id.a_item, details);
}
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
} else
{
Intent intent = new Intent();
intent.setClass(getActivity(), DetailsActivity.class);
intent.putExtra("index", index);
startActivity(intent);
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetails(position);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
}
Here is the detailsFragment:
package com.example.fragmentlayout;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView;
public class DetailsFragment extends Fragment {
String[] Details = {"Details for one", "Details for two", "Details for Three"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(container == null)
{
return null;
}
ScrollView scroller = new ScrollView(getActivity());
TextView text = new TextView(getActivity());
int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,4, getActivity().getResources().getDisplayMetrics());
text.setPadding(padding, padding, padding, padding);
scroller.addView(text);
text.setText(Details[getShownIndex()]);
return scroller;
// return super.onCreateView(inflater, container, savedInstanceState);
}
public static DetailsFragment newInstance(int index)
{
DetailsFragment f = new DetailsFragment();
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex()
{
return getArguments().getInt("index", 0);
}
}
Here is the land and portrait layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<fragment
android:id="#+id/fragment1"
android:name="com.example.fragmentlayout.TitlesFragment"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1" />
<fragment
android:id="#+id/fragment2"
android:name="com.example.fragmentlayout.DetailsFragment"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<fragment
android:id="#+id/fragment1"
android:name="com.example.fragmentlayout.TitlesFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
Perhaps, it's a mistake. The answer is here
https://code.google.com/p/android/issues/detail?id=54837
The author of linked message advises to replace code fragment
if (index == 0) {
ft.replace(R.id.details, details);
} else {
ft.replace(R.id.a_item, details);
}
with code fragment
if (index == 0) {
ft.add(R.id.details, details);
} else {
ft.replace(R.id.details, details);
}
or maybe just
ft.replace(R.id.details, details);
Your DetailsActivity should extend FragmentActivity
You should use getSupportFragmentManager()
If you nest fragments into other fragments consider using getChildFragmentManager()
(ok, i didn't look through all of the code, so not sure if 3 is applicable)
You need to use getSupportFragmentManager instead of getFragmentManager, because you are using support fragments.
The R.id.a_item references the id of the layout in your layout file. Instead of android:id="#+id/fragment1", make it android:id="#+id/a_item"
I'm working with tabs in android, according to my requirement I need to open a popup containing 5 tabs. That is, I have a Fragment where I have to open a DialogFragment and this DialogFragment need to show my 5 tabs. So far so quiet! Could enter each content on their respective tabs.
But the problem is that when I change the tab, the values that were entered in another tab are clean. example:
I go into tab1 fills any value in a text field and then when I switch to tab2 tab1 back to the value it had before entered is lost.
Given this scenario, how do I retain the values that were filled to the brim change? Follow the code below to explain further.
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import br.com.company.R;
import br.com.company.beans.Ordem;
import br.com.company.dispatcher.IDispacher;
import br.com.company.fragment.helper.IFragmentCo;
import br.com.company.bo.IClasseBO;
public class TabsFragment extends DialogFragment implements OnTabChangeListener {
private static final String TAG = "FragmentTabs";
public static final String TAB_DADOS_CLIENTE = "dadosCliente";
public static final String TAB_DEFEITO_FALHA = "defeitoFalha";
public static final String TAB_SERVICOS = "servico";
public static final String TAB_MATERIAIS = "material";
public static final String TAB_OBSERVACAO = "observacao";
private View mRoot;
private Button enviar;
private Button cancelar;
private Spinner classe;
private TabHost mTabHost;
private Ordem ordem;
private IClasseBO classeBO;
private IDispacher dispatch;
private IFragmentCo ifrag;
private int mCurrentTab;
public TabsFragment(IFragmentCo ifrag, Ordem ordem) {
this.ordem = ordem;
this.ifrag = ifrag;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRoot = inflater.inflate(R.layout.ordem_encerramento, null);
enviar = (Button) mRoot.findViewById(R.ordem_encerramento.enviar);
cancelar = (Button) mRoot.findViewById(R.ordem_encerramento.cancelar);
cancelar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TabsFragment.this.dismiss();
}
});
mTabHost = (TabHost) mRoot.findViewById(android.R.id.tabhost);
setupTabs();
return mRoot;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
mTabHost.setOnTabChangedListener(this);
mTabHost.setCurrentTab(mCurrentTab);
mTabHost.getTabContentView().addView(addView(R.layout.dados_cliente));
}
private void setupTabs() {
mTabHost.setup(); // importante!
mTabHost.addTab(newTab(TAB_DADOS_CLIENTE, R.string.tab_dados_cliente, R.ordem_encerramento.dados_cliente));
mTabHost.addTab(newTab(TAB_DEFEITO_FALHA, R.string.tab_defeito_falha, R.ordem_encerramento.defeito_falha));
mTabHost.addTab(newTab(TAB_SERVICOS, R.string.tab_servico, R.ordem_encerramento.servico));
mTabHost.addTab(newTab(TAB_MATERIAIS, R.string.tab_material, R.ordem_encerramento.material));
mTabHost.addTab(newTab(TAB_OBSERVACAO, R.string.tab_observacao, R.ordem_encerramento.observacao));
}
private View addView(int resource) {
LayoutInflater layoutInflater = (LayoutInflater)getActivity().getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(resource, null);
return view;
}
private TabSpec newTab(String tag, int labelId, int tabContentId) {
Log.d(TAG, "buildTab(): tag=" + tag);
View view = LayoutInflater.from(mTabHost.getContext()).inflate(R.layout.tabs_bg_view, null);
TextView tv = (TextView) view.findViewById(R.id.tabsText);
tv.setText(labelId);
TabSpec tabSpec = mTabHost.newTabSpec(tag);
tabSpec.setIndicator(view);
tabSpec.setContent(tabContentId);
return tabSpec;
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onTabChanged(String tabId) {
Log.d(TAG, "onTabChanged(): tabId=" + tabId);
View view = null;
if (TAB_DADOS_CLIENTE.equals(tabId)) {
mTabHost.getTabContentView().removeAllViews();
mTabHost.getTabContentView().addView(addView(R.layout.dados_cliente));
mTabHost.setCurrentTab(0);
} else if (TAB_DEFEITO_FALHA.equals(tabId)) {
view = new DefeitoFalhaView().createView(getActivity());
mTabHost.getTabContentView().addView(view);
mTabHost.setCurrentTab(1);
} else if (TAB_SERVICOS.equals(tabId)) {
mTabHost.getTabContentView().removeAllViews();
mTabHost.getTabContentView().addView(addView(R.layout.servico));
mCurrentTab = 2;
} else if (TAB_MATERIAIS.equals(tabId)) {
mTabHost.getTabContentView().removeAllViews();
mTabHost.getTabContentView().addView(addView(R.layout.materiais));
mCurrentTab = 3;
} else if (TAB_OBSERVACAO.equals(tabId)) {
mTabHost.getTabContentView().removeAllViews();
mTabHost.getTabContentView().addView(addView(R.layout.observacao));
mCurrentTab = 4;
}
}
public View getmRoot() {
return mRoot;
}
}
File xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/White"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="30dip"
android:layout_gravity="center_vertical"
android:orientation="horizontal"
android:paddingRight="10dip" >
<TextView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:paddingLeft="10dip"
android:text="Devolver OS"
android:textColor="#color/Black" />
<View
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
<Button
android:id="#+ordem_encerramento/cancelar"
style="#style/ButtonNovo"
android:layout_marginLeft="10dip"
android:text="Cancelar" />
<Button
android:id="#+ordem_encerramento/enviar"
style="#style/ButtonNovo"
android:layout_marginLeft="10dip"
android:text="Enviar" />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dip"
android:background="#xml/menu_bg" />
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="40dip" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dip" >
<TabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#EFEFEF" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<FrameLayout
android:id="#+ordem_encerramento/dados_cliente"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<FrameLayout
android:id="#+ordem_encerramento/defeito_falha"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<FrameLayout
android:id="#+ordem_encerramento/servico"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<FrameLayout
android:id="#+ordem_encerramento/material"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<FrameLayout
android:id="#+ordem_encerramento/observacao"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</FrameLayout>
</LinearLayout>
</TabHost>
</LinearLayout>
</ScrollView>
</LinearLayout>
Try storing those values somewhere e.g.SharedPreferences or static variable and setting them back in onTabChanged().
TabGroupActivity.java
import java.util.ArrayList;
import com.data.DataClass;
import android.app.Activity;
import android.app.ActivityGroup;
import android.app.LocalActivityManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
/**
* The purpose of this Activity is to manage the activities in a tab. Note:
* Child Activities can handle Key Presses before they are seen here.
*
* #author Eric Harlow
*/
public class TabGroupActivity extends ActivityGroup {
private ArrayList<String> mIdList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mIdList == null)
mIdList = new ArrayList<String>();
}
/**
* This is called when a child activity of this one calls its finish method.
* This implementation calls {#link LocalActivityManager#destroyActivity} on
* the child activity and starts the previous activity. If the last child
* activity just called finish(),this activity (the parent), calls finish to
* finish the entire group.
*/
#Override
public void finishFromChild(Activity child) {
LocalActivityManager manager = getLocalActivityManager();
int index = mIdList.size() - 1;
if (index < 1) {
finish();
return;
}
manager.destroyActivity(mIdList.get(index), true);
mIdList.remove(index);
index--;
String lastId = mIdList.get(index);
Intent lastIntent = manager.getActivity(lastId).getIntent();
Window newWindow = manager.startActivity(lastId, lastIntent);
setContentView(newWindow.getDecorView());
}
/**
* Starts an Activity as a child Activity to this.
*
* #param Id
* Unique identifier of the activity to be started.
* #param intent
* The Intent describing the activity to be started.
* #throws android.content.ActivityNotFoundException.
*/
public void startChildActivity(String Id, Intent intent) {
Window window = getLocalActivityManager().startActivity(Id,
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
if (window != null) {
mIdList.add(Id);
setContentView(window.getDecorView());
}
}
/**
* The primary purpose is to prevent systems before
* android.os.Build.VERSION_CODES.ECLAIR from calling their default
* KeyEvent.KEYCODE_BACK during onKeyDown.
*/
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// preventing default implementation previous to
// android.os.Build.VERSION_CODES.ECLAIR
// onBackPressed();//Added after
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* Overrides the default implementation for KeyEvent.KEYCODE_BACK so that
* all systems call onBackPressed().
*/
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
return true;
}
return super.onKeyUp(keyCode, event);
}
/**
* If a Child Activity handles KeyEvent.KEYCODE_BACK. Simply override and
* add this method.
*/
public void onBackPressed() {
int length = mIdList.size();
if (length > 1) {
Activity current = getLocalActivityManager().getActivity(
mIdList.get(length - 1));
if (DataClass.isTemp()) {
overridePendingTransition(R.anim.slide_in_up,
R.anim.slide_in_up);
}
current.finish();
}
}
}
MainTab.java
import com.data.DataClass;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.StateListDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.LinearLayout.LayoutParams;
public class MainTabInfoMe extends TabActivity {
public final static int HOME = 1;
public final static int DIARY = 2;
public final static int PROGRESS = 3;
long transactionID = -1;
public static TabHost tabHost;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mytabs);
MyView view = null;
tabHost = getTabHost();
TabHost.TabSpec spec;
Intent intent;
intent = new Intent().setClass(this, TabGroup1Activity.class);
view = new MyView(this, R.drawable.home_select, R.drawable.home, "");
view.setFocusable(true);
spec = tabHost.newTabSpec("Home").setIndicator(view).setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, TabGroup2Activity.class);
view = new MyView(this, R.drawable.prof_select, R.drawable.prof, "");
view.setFocusable(true);
spec = tabHost.newTabSpec("Diary").setIndicator(view)
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, TabGroup3Activity.class);
view = new MyView(this, R.drawable.bus_select, R.drawable.bus, "");
view.setFocusable(true);
spec = tabHost.newTabSpec("progress").setIndicator(view)
.setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTab(0);
tabHost.getTabWidget().getChildAt(0).getLayoutParams().height =
LayoutParams.WRAP_CONTENT;
tabHost.getTabWidget().getChildAt(1).getLayoutParams().height =
LayoutParams.WRAP_CONTENT;
tabHost.getTabWidget().getChildAt(2).getLayoutParams().height =
LayoutParams.WRAP_CONTENT;
if (MyApplication.getFrom().equals("Home")) {
tabHost.setCurrentTab(0);
} else if (MyApplication.getFrom().equals("Diary")) {
tabHost.setCurrentTab(1);
} else if (MyApplication.getFrom().equals("progress")) {
tabHost.setCurrentTab(2);
}
int type = 0;
if (getIntent().getExtras() != null) {
if (getIntent().getExtras().containsKey("from")) {
type = getIntent().getExtras().getInt("from");
switch (type) {
case HOME:
tabHost.setCurrentTab(0);
case DIARY:
tabHost.setCurrentTab(1);
case PROGRESS:
tabHost.setCurrentTab(2);
default:
tabHost.setCurrentTab(0);
}
}
}
}
public long getTransactionID() {
return transactionID;
}
public void setTransactionID(long l) {
transactionID = l;
}
public void switchTabSpecial(int tab) {
tabHost.setCurrentTab(tab);
}
class ChangeTabReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
tabHost = getTabHost();
tabHost.setCurrentTab(1);
}
}
private class MyView extends LinearLayout {
ImageView iv;
public MyView(Context c, int drawable, int drawableselec, String label) {
super(c);
iv = new ImageView(c);
StateListDrawable listDrawable = new StateListDrawable();
listDrawable.addState(SELECTED_STATE_SET, this.getResources()
.getDrawable(drawable));
listDrawable.addState(ENABLED_STATE_SET, this.getResources()
.getDrawable(drawableselec));
iv.setImageDrawable(listDrawable);
iv.setBackgroundColor(Color.TRANSPARENT);
iv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, (float) 0.0));
iv.setPadding(0, 0, 0, 5);
setGravity(Gravity.CENTER);
addView(iv);
}
}
#Override
protected void onPause() {
super.onPause();
if( DataClass.isTemp()){
overridePendingTransition(R.anim.slide_in_up, R.anim.slide_in_up);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
finish();
}
}
FirstTab of class
public class TabGroup1Activity extends TabGroupActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startChildActivity("OptionsActivity", new Intent(this,
MainActivity.class));
}
#Override
public void onBackPressed() {
super.onBackPressed();
DataClass.setTemp(false);
finish();
}
}
SecondTab of class
public class TabGroup2Activity extends TabGroupActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startChildActivity("OptionsActivity", new Intent(this,
MainActivity.class));
}
#Override
public void onBackPressed() {
super.onBackPressed();
DataClass.setTemp(false);
finish();
}
}
thirdTab of class
public class TabGroup1Activity extends TabGroupActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startChildActivity("OptionsActivity", new Intent(this,
MainActivity.class));
}
#Override
public void onBackPressed() {
super.onBackPressed();
DataClass.setTemp(false);
finish();
}
}
static variable class
import android.app.Application;
public class MyApplication extends Application {
private static String from = "Home";
public static String getFrom() {
return from;
}
public static void setFrom(String fromPage) {
from = fromPage;
}
}
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" >
<TabHost android:id="#android:id/tabhost" android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TabWidget android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#drawable/topbarbck"/>
</RelativeLayout>
</TabHost>
</LinearLayout>
put all file and check it
Thanks to all who tried to help me!
I do not have much experience with android but from what I saw, the classes must be executed according to the hierarchy proposed by android. That is, in my case I have a main activity which calls the mine fragments and through one of the fragments I had to call a DialogFragment and this would inflate DialogFragment several Views (my tabs), so I have the following structure:
Activity > Fragment > DialogFragment > Views
Based on this solution for my case was thus:
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
public class OrdemEncerramentoFragment extends DialogFragment implements OnTabChangeListener {
private static final String TAG = "FragmentTabs";
public static final String TAB_DADOS_CLIENTE = "dadosCliente";
public static final String TAB_DEFEITO_FALHA = "defeitoFalha";
public static final String TAB_SERVICOS = "servico";
public static final String TAB_MATERIAIS = "material";
public static final String TAB_OBSERVACAO = "observacao";
private View mRoot;
private Button enviar;
private Button cancelar;
private TabHost mTabHost;
private Ordem ordem;
private IClasseBO classeBO;
private IDispacher dispatch;
private IFragmentCo ifrag;
private int mCurrentTab;
public OrdemEncerramentoFragment(IFragmentCo ifrag, Ordem ordem) {
this.ordem = ordem;
this.ifrag = ifrag;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRoot = inflater.inflate(R.layout.ordem_encerramento, null);
enviar = (Button) mRoot.findViewById(R.ordem_encerramento.enviar);
cancelar = (Button) mRoot.findViewById(R.ordem_encerramento.cancelar);
cancelar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
OrdemEncerramentoFragment.this.dismiss();
}
});
enviar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View view = mTabHost.getChildAt(0);
new DefeitoFalhaView().getDadosDefeitoFalha(view);
}
});
mTabHost = (TabHost) mRoot.findViewById(android.R.id.tabhost);
setupTabs();
return mRoot;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
mTabHost.setOnTabChangedListener(this);
mTabHost.setCurrentTab(0);
}
private void setupTabs() {
mTabHost.setup(); // importante!
mTabHost.addTab(inserirAba(TAB_DADOS_CLIENTE, R.string.tab_dados_cliente, new DadosClienteView().createView(getActivity())));
mTabHost.addTab(inserirAba(TAB_DEFEITO_FALHA, R.string.tab_defeito_falha, new DefeitoFalhaView().createView(getActivity())));
mTabHost.addTab(inserirAba(TAB_SERVICOS, R.string.tab_servico, new ServicoView().createView(getActivity())));
mTabHost.addTab(inserirAba(TAB_MATERIAIS, R.string.tab_material, new MaterialView().createView(getActivity())));
mTabHost.addTab(inserirAba(TAB_OBSERVACAO, R.string.tab_observacao, new ObservacaoView().createView(getActivity())));
}
private TabSpec inserirAba(String tag, int labelId, final View view) {
TabHost.TabSpec spec = mTabHost.newTabSpec(tag);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return(view);
}
});
spec.setIndicator(buildTabIndicator(labelId));
return spec;
}
private View buildTabIndicator(int msg) {
View indicator=LayoutInflater.from(mTabHost.getContext()).inflate(R.layout.tabs_bg_view, null);
TextView tv=(TextView)indicator.findViewById(R.id.tabsText);
tv.setText(msg);
return(indicator);
}
#Override
public void onTabChanged(String tabId) {
Log.d(TAG, "onTabChanged(): tabId=" + tabId);
}
public View getmRoot() {
return mRoot;
}
}