I was trying to inflate a fragment in an Activity and here is the code.
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container2, new DetailFragment())
.commit(); //Line with Error
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.detail, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_refresh) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And here is my DetailFragment class
/**
* A placeholder fragment containing a simple view.
*/
public class DetailFragment extends Fragment {
public DetailFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
return rootView;
}
}
Here goes the layout for fragment_detail
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:textSize="18sp"
android:id="#+id/fragment_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
The error I am facing is cannot resolve method 'add(int,com.example...DetailFragment)'. As, I am beginner to android, please also guide me on how should I go about, tackling such type of errors.
Your DetailFragment need to extends from android.support.v4.app.Fragment instead of Fragment. Something like this
public class DetailFragment extends android.support.v4.app.Fragment {
......
}
Make sure your DetailFragment uses the fragment from the version 4 support library and
import the library below into your fragment class. The problem is that you are using android.app.fragment instead of android.support.v4.app.Fragment.
import android.support.v4.app.Fragment;
public class DetailFragment extends Fragment{
}
Related
I have an action bar menu defined in my main activity. Now, one of the fragments I am using in that activity has its own action bar menu but when I click on the menu option, I get both the fragment's as well as the activity's menu items. How to ensure that only that fragment's menu item is displayed?
My java code for that fragment is:
public class ProfileD extends Fragment {
TextView tv_named, tv_genderd, tv_cfd, tv_aged, tv_biod, tv_statusd;
ImageView imageView_dp;
public ProfileD() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_profile_d, container, false);
tv_named = (TextView)rootView.findViewById(R.id.tv_named);
tv_genderd = (TextView)rootView.findViewById(R.id.tv_genderd);
tv_cfd= (TextView)rootView.findViewById(R.id.tv_cfd);
tv_aged = (TextView)rootView.findViewById(R.id.tv_aged);
tv_biod = (TextView)rootView.findViewById(R.id.tv_biod);
tv_statusd = (TextView) rootView.findViewById(R.id.tv_statusd);
imageView_dp = (ImageView)rootView.findViewById(R.id.imageView_dp);
setHasOptionsMenu(true);
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
getActivity().getMenuInflater().inflate(R.menu.profile_menu, menu);
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.edit_profile) {
Intent intent = new Intent(getContext(),PersonalDetails.class);
intent.putExtra("Edit",1);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
AppCompatActivity appCompatActivity = (AppCompatActivity)getActivity();
ActionBar actionBar = appCompatActivity.getSupportActionBar();
actionBar.setTitle("Profile");
}
}
The xml file for the menu is:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/edit_profile"
android:orderInCategory="100"
android:title="Edit"
app:showAsAction="never" />
</menu>
I found a solution to my problem. I am posting it here so if anyone else is facing the same issue, they can benefit from this:
I created a static menu object and stored the activity's action bar menu in that object. I then called that object from my fragment and cleared it thereby clearing the activity's menu and leaving me with the fragment's menu
Here is the updated java code for the fragment
public class ProfileD extends Fragment {
TextView tv_named, tv_genderd, tv_cfd, tv_aged, tv_biod, tv_statusd;
ImageView imageView_dp;
public ProfileD() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_profile_d, container, false);
tv_named = (TextView)rootView.findViewById(R.id.tv_named);
tv_genderd = (TextView)rootView.findViewById(R.id.tv_genderd);
tv_cfd= (TextView)rootView.findViewById(R.id.tv_cfd);
tv_aged = (TextView)rootView.findViewById(R.id.tv_aged);
tv_biod = (TextView)rootView.findViewById(R.id.tv_biod);
tv_statusd = (TextView) rootView.findViewById(R.id.tv_statusd);
imageView_dp = (ImageView)rootView.findViewById(R.id.imageView_dp);
setHasOptionsMenu(true);
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
HomePage.menu_home.clear();
getActivity().getMenuInflater().inflate(R.menu.profile_menu, menu);
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.edit_profile) {
Intent intent = new Intent(getContext(),PersonalDetails.class);
intent.putExtra("Edit",1);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
AppCompatActivity appCompatActivity = (AppCompatActivity)getActivity();
ActionBar actionBar = appCompatActivity.getSupportActionBar();
actionBar.setTitle("Profile");
}
}
I already have made a class that extends PreferenceFragment to display my apps preferences. It works, but I decided I should make the fragment appear in a new activity so that the user can back out of it. Right now, it just gets swapped into the main fragment and displayed. How can I simply make an activity that displays the entire PreferenceFragment? There is no layout defined for the Fragment since it's a PreferenceFragment.
Make a new activity that contains one fragment. Insert the preferences fragment in it. Here is a copy of what I use in my project.
public class SettingsActivity extends Activity{
public final static String SETTINGS_NATIVE_IGNORE = "pref_native_ignore";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(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();
switch(id)
{
case android.R.id.home:
onBackPressed();
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
then the xml for it
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:baselineAligned="false"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="...SettingsActivity"
tools:ignore="MergeRootFrame" >
<fragment
android:id="#+id/preferences_fragment"
android:name="...fragment.PreferencesFragment"
tools:layout="#layout/fragment_preferences"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
And finally the preferences fragment
public class PreferencesFragment extends PreferenceFragment {
public PreferencesFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
I have a problem with adding the fragment transactions to the back stack. I have a Main activity in which I populate my layout with a Menu Fragment:
public class MainActivity extends ActionBarActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction().add(R.id.frag_container, new MainMenuFragment()).commit();
}
#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);
}
}
Then, inside the MainMenuFragment, the user chooses some option which results in replacing the menu fragment with some other fragment:
public class MainMenuFragment extends Fragment implements OnItemClickListener{
GridView grid;
FragmentManager manager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.main_menu_fragment, container, false);
manager = getActivity().getFragmentManager();
grid = (GridView) root.findViewById(R.id.gridView1);
grid.setAdapter(new MenuTileAdapter(getActivity()));
grid.setOnItemClickListener(this);
return root;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FragmentTransaction trans = manager.beginTransaction();
if (position == 0){
trans.replace(R.id.frag_container, new BasicSettingsFragment());
trans.addToBackStack(null);
trans.commit();
}
}
}
For what i understand, this should make it so that when the user presses back button on their device, they will be brought back to the menu fragment, but instead this quits the app. What am i doing wrong?
In your Activity overwrite:
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
And probably you need to use in every commited fragment transaction:
FragmentTransaction.addToBackStack(null);
Your code is a mixup, you use ActionBarActivity from appcompat and not using getSupportFragmentManager() and the fragments import should be the appcompat one if you decide to use it. If not, use Activity instead of ActionBarActivity and the simple Fragment import with FragmentManager
Add this to your activity android:configChanges="keyboardHidden|orientation|screenSize"
This will stop your activity from restarting when you rotate.
use setRetainInstance(true) on fragments.
You are not adding the MainMenuFragment to the back stack. You can try this one on your activity:
getFragmentManager().beginTransaction().add(
R.id.frag_container, new MainMenuFragment()).
addToBackStack(null).commit();
When you add or replace a fragment with the FragmentManager, you need to manually add the old fragment to the backstack with addToBackStack() before calling commit().
So i've just started doing some android programing, and I'm already stuck! My problem is; I want want my fragment, from MainActivity, to NOT be a part of my new Activity. I want the activity to be all blank, the fragment from MainActivity should be gone, buuut it's not.
The content from the "fragmentz" xml document, which is "linked" in the Fragment Class. Should NOT appear in the second Activity... Where in the SecondActivity have I associated it with the Fragment Class? This is getting frustrating :D
So here is my MainActivity code:
public class MainActivity extends ActionBarActivity {
FragmentManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
manager= getSupportFragmentManager();
ArticleFragment frag = new ArticleFragment();
FragmentTransaction transaction = manager.beginTransaction();
transaction = manager.beginTransaction();
transaction.add(R.id.fragmentet,frag,"tagg");
transaction.commit();
// here the Fragment should be added to my MainActiviy
}
public void WalkForward(View view)
{
ArticleFragment frag = (ArticleFragment) manager.findFragmentByTag("tagg");
FragmentTransaction transaction = manager.beginTransaction();
transaction.remove(frag);
transaction.commit();
// Here, the fragment should disappear before the new activity start
Intent intenten = new Intent(this, SecondActivity.class);
startActivity(intenten);
// Start new activity
finish();
// I've tried this finish method, and also onDestroy and so on... But that work either. I thought the Fragments should
// disappear with its activity?
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends 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;
}
}
}
My Fragment Class:
public class ArticleFragment extends Fragment {
public void onAttach(Activity activity)
{
Log.d("Fraggment", "onAttach");
super.onAttach(activity);
// #17 Android FragmentTransaction Part 2: Android Application Development Development [HD 1080p]
}
public void onCreate(Bundle saveInstanceState)
{
Log.d("Fraggment", "onCreate");
super.onCreate(saveInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragmentz, container, false);
}
public void onActivityCreate(Bundle saveInstanceState)
{
Log.d("Fraggment", "onActivityCreated");
super.onActivityCreated(saveInstanceState);
}
public void onPause()
{
super.onPause();
Log.d("Fraggment", "onPause");
}
public void onStop()
{
super.onStop();
Log.d("Fraggment", "onStop");
}
public void onDestroyView()
{
super.onDestroyView();
Log.d("Fraggment", "onDestroyView");
}
public void onDestroy()
{
super.onDestroy();
Log.d("Fraggment", "onDestroy");
}
public void onDetach()
{
super.onDetach();
Log.d("Fraggment", "onDetach");
}
And my Second Activity Class:
public class SecondActivity extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_second,
container, false);
return rootView;
}
}
}
I hope you understand what I mean :P Is there anything I can do? Thanks in advance!
Remove this
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
from your Second Activity. And why are you extending MainActivity? Some Reason?
I am having issues with the cardflip animation in Android. I am following their guide and also trying to pick a part the AnimationsDemo to try to understand this. But I have created all the card flip in and outs in XML and the card front and back layout in XML. I keep getting an error message when I try to add the fragment in onCreate. I'm not sure what is triggering the error as the code looks like the example code they use. I've included the error message and jave code below. Thanks for your time.
public class MainActivity extends ActionBarActivity {
/**
* Whether or not we're showing the back of the card (otherwise showing the front).
*/
private boolean mShowingBack = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager()
.beginTransaction()
.add(R.id.container, new CardFrontFragment())
.commit();
}else {
mShowingBack = (getFragmentManager().getBackStackEntryCount() > 0);
}
/**
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
*/
}
private void flipCard() {
if (mShowingBack) {
getFragmentManager().popBackStack();
return;
}
// Flip to the back.
mShowingBack = true;
// Create and commit a new fragment transaction that adds the fragment for the back of
// the card, uses custom animations, and is part of the fragment manager's back stack.
getFragmentManager()
.beginTransaction()
// Replace the default fragment animations with animator resources representing
// rotations when switching to the back of the card, as well as animator
// resources representing rotations when flipping back to the front (e.g. when
// the system Back button is pressed).
.setCustomAnimations(
R.animator.card_flip_right_in, R.animator.card_flip_right_out,
R.animator.card_flip_left_in, R.animator.card_flip_left_out)
// Replace any fragments currently in the container view with a fragment
// representing the next page (indicated by the just-incremented currentPage
// variable).
.replace(R.id.container, new CardBackFragment())
// Add this transaction to the back stack, allowing users to press Back
// to get to the front of the card.
.addToBackStack(null)
// Commit the transaction.
.commit();
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends 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;
}
}
/**
* A fragment representing the front of the card.
*/
public static class CardFrontFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.card_front, container, false);
}
}
/**
* A fragment representing the back of the card.
*/
public static class CardBackFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.card_back, container, false);
}
}
}
Error:
The method add(int, Fragment) in the type FragmentTransaction is not applicable for the arguments (int, MainActivity.CardFrontFragment) MainActivity.java /Lab6b/src/you/ca/mohawk/lab6b line 28 Java Problem
It seems issue should be with your Fragment import.
If you are using fragment support library then
import android.support.v4.app.Fragment;
and fragment manager instance should be get as
getSupportFragmentManager()
Else if your using the default Fragment then change the import as
import android.app.Fragment;