Fragment Changes when Screen is rotated - android

I have two fragments, FragmentCity and Fragmentnumber1. When screen orientation changes on fragmentnumber1, it goes back to FragmentCity. Does anyone know how to solve this? I appreciate it if you could show me how to solve this issue
FragmentCity
public class FragmentCity extends Fragment {
final String[] items = new String[]{"FC1", "FC2", "FC3", "FC4","FC5"
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.haz, container, false);
ListView list = (ListView) view.findViewById(R.id.fir);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Fragment myFragment = null;
switch (arg2) {
case 0:
myFragment = new Fragmentnumber1();
break;
case 1:
myFragment = new Fragmentnumber2();
break;
case 2:
myFragment = new Fragmentnumber3();
break;
case 3:
myFragment = new Fragmentnumber4();
break;
case 4:
myFragment = new Fragmentnumber5();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentManager.beginTransaction().addToBackStack("frag")
.replace(R.id.container2, myFragment)
.commit();
}
});
return view;
}
}
Fragmentnumber1
public class Fragmentnumber1 extends Fragment {
final String[] items = new String[]{"num1", "num2", "num3"
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.haz, container, false);
ListView list = (ListView) view.findViewById(R.id.fir);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Fragment myFragment = null;
switch (arg2){
case 0:
myFragment = new num1();
break;
case 1:
myFragment = new num2();
break;
case 2:
myFragment = new num3();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getChildFragmentManager();
fragmentManager.beginTransaction().addToBackStack(null)
.replace(R.id.container2, myFragment)
.commit();
}
});
return view;
}
}

You have not posted code of activity class but i am guessing that you have loaded FragmentCity fragment in onCreate of your activity
So when you change orientation it again call onCreate and load FragmentCity fragment so by putting proper condition you can manage it.

Try adding the following line to your containing activity (probably MainActivity) in the manifest
<activity android:name=".MainActivity"
android:configChanges="keyboardHidden|orientation|screenSize"/>
This will allow the Activity to maintain it's state across orientation changes.

Related

BottomNavigation View back button on pressed change state

So let me try to explain this: I have a Bottom navigation view with three buttons, each one when pressed will load a fragment. However, when pressing the back button, i have programmed the back stack to go back to the fragment it was previously. However, the colour of the navigation button does not change after the back button is changed. I know this has something to do with the state checked thing but i do not know how to implement it on my codes. Here are the codes
This is the menu page, it sets the bottomnavigation view only in which the main_frame is where the fragments are going to be:
public class menuPage extends AppCompatActivity {
BottomNavigationView mainNav;
FrameLayout mainFrame;
private MoviesFragment moviesFragment;
private HomeFragment homeFragment;
private ProfileFragment profileFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_page);
mainFrame= (FrameLayout) findViewById(R.id.main_frame);
mainNav = (BottomNavigationView) findViewById(R.id.main_nav);
moviesFragment= new MoviesFragment ();
homeFragment = new HomeFragment();
profileFragment = new ProfileFragment ();
removeFragment(homeFragment);
mainNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_movies :
setFragment(moviesFragment);
return true;
case R.id.nav_home :
setFragment(homeFragment);
return true;
case R.id.nav_profile:
setFragment(profileFragment);
return true;
default:
return false;
}
}
});
}
private void setFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame, fragment);
fragmentTransaction.addToBackStack("detail");
fragmentTransaction.commit();
}
private void removeFragment(Fragment fragment){
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_frame, fragment);
fragmentTransaction.disallowAddToBackStack();
fragmentTransaction.commit();
}
}
Here is the codes for the Home Fragment, Movies Fragment and Profile Fragment respectively. You can ignore the codes written inside cos i know it correctly goes to another activity when launched and that has nothing to do with this issue
Home Fragment
public class HomeFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_agenda, container, false);
return view;
}
}
Movies Fragment
public class MoviesFragment extends Fragment {
ListView listofmovies;
ArrayList<String> genres;
ArrayAdapter<String> listview;
NowShowing nowShowing;
ComingSoon comingsoon;
#Override//inflate this
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_movies, container, false);
listofmovies = (ListView) view.findViewById(R.id.movielist);
genres = new ArrayList<String>();
listview = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_activated_1, genres);
listofmovies.setAdapter(listview);
//The types of options
genres.add("Now Showing");
genres.add("Coming Soon");
genres.add("July");
genres.add("June");
nowShowing = new NowShowing();
comingsoon = new ComingSoon();
listofmovies.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
Intent nextPage = new Intent(view.getContext(), NowShowing.class);
startActivityForResult(nextPage,0);
}
if (position == 1){
Intent nextPage = new Intent(view.getContext(),ComingSoon.class);
startActivityForResult(nextPage,1);
}
}
});
return view;
}
}
Profile Fragment
public class ProfileFragment extends Fragment {
ListView management;
ArrayList<String> mis;
ArrayAdapter<String> Adapter;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile,container, false );
management= (ListView) view.findViewById(R.id.management);
mis= new ArrayList<String>();
Adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_activated_1, mis);
management.setAdapter(Adapter);
//add management settings
mis.add("Settings");
mis.add("Favourites");
mis.add("Log Out");
userprofilefragment userprofilefragment = new userprofilefragment();
FragmentManager manager = getFragmentManager();
manager.beginTransaction()
.replace(R.id.profilelayout, userprofilefragment, userprofilefragment.getTag())
.commit();
return view;
}
Help is much appreciated. The context is that I'm just making a simple movie app for school assignment and i am still kinda beginner at Java..
Thanks

Fragment List view replace

When i replace fragment Listview place fragment Listview
I had trouble this in photo but i can't fix it .
i need to fix it,plz.
UI_screenshot
Code
#Override
public void onActivityCreated(Bundle savedInstanceState) {
final String[] titel = {"asdasd", "asda", "bdfg", "asdqweqwe"};
int idimg = R.mipmap.icon_main_list;
MyArrayAdapter adapter = new MyArrayAdapter(getActivity(), titel, idimg);
setListAdapter(adapter);
super.onActivityCreated(savedInstanceState);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
switch (position) {
case 0:
Anmalz anmalz=new Anmalz();
Main_List_Fragment main_list_fragment=new Main_List_Fragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment, anmalz);
fragmentTransaction.remove(main_list_fragment).commit();
break;
Change your onCreateView() to -
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.main_fragment_list, container, false);
}
Also, in onListItemClick(), you should not remove/replace the same fragment again and again. You should just refresh the list adapter.

How to refresh fragment on spinner on item selected

I am setting a language in spinner on item selected. The change is not reflected on the next line. So, I want to refresh my fragment.
public class TodayChapter extends Fragment {
String chapter_verse = "";
TextView textView;
ListView todayChapterListView;
ArrayAdapter<String> adapter;
DailyQuranMethods dailyQuranMethods = new DailyQuranMethods();
private final String[] translateLanguage={"Translate To","English","Urdu","Hindi"};
public TodayChapter() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_today_chapter, container, false);
todayChapterListView = (ListView)view.findViewById(R.id.today_chapter_list_view);
Spinner spinner = (Spinner)view.findViewById(R.id.selectLanguage);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_spinner_item, translateLanguage );
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinner.setAdapter(spinnerArrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position)
{
case 0:
dailyQuranMethods.setTranslationLanguage(getActivity().getBaseContext(), "english");
break;
case 1:
dailyQuranMethods.setTranslationLanguage(getActivity().getBaseContext(),"english");
break;
case 2:
dailyQuranMethods.setTranslationLanguage(getActivity().getBaseContext(),"urdu");
break;
default:
dailyQuranMethods.setTranslationLanguage(getActivity().getBaseContext(),"hindi");
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
String[] chapter = dailyQuranMethods.getChapter(dailyQuranMethods.getChapterNoToday(getActivity().getBaseContext()), dailyQuranMethods.getTranslationLanguage(getActivity().getBaseContext()), getActivity());
String chapterName = getActivity().getResources().getStringArray(R.array.chapters_name_arabic)[dailyQuranMethods.getChapterNoToday(getActivity().getBaseContext()) - 1 ];
TextView textView = (TextView)view.findViewById(R.id.chapterName);
textView.setText(chapterName);
adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,chapter);
todayChapterListView.setAdapter(adapter);
return view;
}
}
I can also call a method on each on item selected change. But, I want it by refreshing the fragment. In each switch case, I want to refresh the fragment. Please help me to solve this.
Edit 1:
There are three fragments, which are attached with the main activity:
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Today's Verse"),
TodayVerse.class, null);
mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Today's Chapter"),
TodayChapter.class, null);
mTabHost.addTab(mTabHost.newTabSpec("tab3").setIndicator("Complete Qur'an"),
completeQuran.class, null);
You can simply detach and attach fragment as below
Fragment currentFragment = getFragmentManager().findFragmentByTag("tab2");
FragmentTransaction fragTransaction = getFragmentManager().beginTransaction();
fragTransaction.detach(currentFragment);
fragTransaction.attach(currentFragment);
fragTransaction.commit();
This will refresh the view and locale will change

setOnItemClickListener event doesn't work in Fragment

I am trying to get onItemClick on ListItems to work from a fragment. Here is my code:
public class MyBudgetPageMenuFragment extends Fragment {
private Context context;
private ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.my_budget_listview,
container, false);
ListView listView = (ListView) myFragmentView
.findViewById(android.R.id.list);
context = this.getActivity().getApplicationContext();
String[] values = new String[4];
ListAdapter adapter = new ListAdapter(context, values);
listView.setAdapter(adapter);
listView.setOnItemClickListener( new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
selectItem(position);
}
});
return myFragmentView;
}
private void selectItem(int position) {
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment;
switch (position) {
case 0:
fragment = new MyBudgetPageFragments();
fragmentManager.beginTransaction()
.replace(R.id.listFragment, fragment).commit();
break;
default:
String message1 = Integer.toString(position);
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setMessage("Position: " + message1);
alertDialog.show();
break;
}
}
}
But every time when I select an item, it isn't doing anything or throwing any exceptions. It seems that the event doesn't get registered. I debuged the code and it doesn't enter my event.
Can someoane tell me what I'm doing wrong?
Note that the ListView blocks clicks of an item that contains at least one focusable
descendant but it doesn’t make the content focus-reachable calling
setItemsCanFocus(true). One workaround is by disabling focusability of descendants, using
android:descendantFocusability="blocksDescendants"
in the layout defining your list item. (First learned of this myself from http://cyrilmottier.com/2011/11/23/listview-tips-tricks-4-add-several-clickable-areas/) Does your layout contain buttons? If so, you'd fall into this case.
Just go the simple way.
In your Adapter class, between getView method, initialize View v = convertView; then
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "test "+ list.get(position).getS_name(), Toast.LENGTH_SHORT).show();
}
});

Replace Fragment onItemClick with ViewPager as its container

I want to replace a fragment containing a list of items with a new fragment depending on the item clicked. This is my code, how do I need to approach this? Should I declare my ListView, Adapter and such in onCreateView or onActivityCreated? The container is a ViewPager if that makes a difference.
public class PreferenceListFragment extends SherlockFragment
{
ListView lv;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return (LinearLayout)inflater.inflate(R.layout.settings, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
lv = (ListView)getView().findViewById(R.id.SettingsLV);
lv.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, Preferences.TITLES));
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Log.i("FragmentList", "Item clicked: " + arg2);
// Switch case that starts fragment depending on 'position'.
Fragment1 f1 = new Fragment1();
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.pager, f1);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
}
);
}
}
Link to some very weird behaviour from my app.
The setting of adapter and listview should be done in onActivityCreated. OnCreateView is just to draw the user interface for the first time. The processing should be in onActivityCreated(). Refer http://developer.android.com/guide/topics/fundamentals/fragments.html

Categories

Resources