i want to open a fragment from MainActivity where i have gridview.i am new to android and this is the first time to use fragment.
this is my mainactivity:
package com.example.grasu.petrosani;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ThemedSpinnerAdapter;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,AdapterView.OnItemClickListener{
private DrawerLayout DrawerLayout;
private NavigationView Drawer;
GridView gridview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Drawer = findViewById(R.id.nav_view);
Drawer.setNavigationItemSelectedListener(this);
DrawerLayout = findViewById(R.id.drawer_layout);
CategoryAdapter adapter = new CategoryAdapter(this, getSupportFragmentManager());
gridview=findViewById(R.id.album_Gridview);
gridview.setAdapter(new GridViewAdapter(this));
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
return false;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (parent.getId()==R.id.album_Gridview){
switch (position) {
case 0:
}
}
}
}
this is my xml for activity main:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<GridView
android:id="#+id/album_Gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="2"
android:layout_marginTop="10dp">
</GridView>
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
android:duplicateParentState="true"
app:menu="#menu/drawer_view"/>
</android.support.v4.widget.DrawerLayout>
and this is the fragment i want to open from gridview:
package com.example.grasu.petrosani;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class InfoFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.info, container, false);
return rootView;
}}
i tried with FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(CurrentClass.this, MainActivity.class); but it didn't work.do I have to modify my mainactivity to extend fragmentActivity?
You can try something like -
Create a New Activity.
Add your Fragment in the above created Activity.
In your GridView Item click, open the New Activity via an Intent like - startActivity(new Intent(MainActivity.this, NewActivity.class));
Follow below code:
FragmentTransaction fragmentTransaction = getSupportFragmentManager()
.beginTransaction();
Fragment profileFragment = new InfoFragment();//the fragment you want to show
profileFragment.setArguments(bundle);
fragmentTransaction
.replace(R.id.content_frame, profileFragment);//R.id.content_frame is the layout you want to replace
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Related
I tried every way to solve this problem but still I am not getting whats wrong with this code. Can you help me?
My mainpage activity is as
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Toast;
public class MainPage extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private NavigationView mNavigationView;
private FragmentTransaction fragmentTransction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main_page);
Toolbar toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mNavigationView=findViewById(R.id.idnav_view);
ActionBar actionBar=getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
mDrawerLayout=findViewById(R.id.iddrawer_layout);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment frag=null;
int itemId=menuItem.getItemId();
if(itemId==R.id.id_nvHome){
frag=new HomeFragment();
}
else if(itemId==R.id.id_nvSearch){
frag=new SearchFragment();
}
Toast.makeText(getApplicationContext(),menuItem.getTitle(),Toast.LENGTH_SHORT).show();
if(frag!=null){
FragmentTransaction transction=getSupportFragmentManager().beginTransaction();
transction.replace(R.id.idcontent_frame,frag);
transction.commit();
mDrawerLayout.closeDrawers();
return true;
}
return false;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
}
and for mypage activity layout is
<?xml version="1.0" encoding="utf-8"?>
<!-- Use DrawerLayout as root container for activity -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/iddrawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!-- Layout to contain contents of main body of screen (drawer will slide over this) -->
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/idcontent_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar" />
<!-- Container for contents of drawer - use NavigationView to make configuration easier -->
<android.support.design.widget.NavigationView
android:id="#+id/idnav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/drawer_view"
app:headerLayout="#layout/nav_header"/>
</android.support.v4.widget.DrawerLayout>
my homefragment is as
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class HomeFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragment_home,container,false);
return v;
}
}
and also layout for that is as
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HomeFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_marginTop="150dp"
android:layout_marginLeft="150dp"
android:textColor="#000000"
android:textSize="30dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</FrameLayout>
I want to REPLACE FRAGMENT WITH OTHER FRAGMENT WHEN I CLICK ON NAVIGATION DRAWER ITEMS
Can anyone help me?
I can support you giving you my working code for Android 27.1.1:
public class MainActivity extends AppCompatActivity implements
BottomNavigationView.OnNavigationItemSelectedListener {
private int mSelectedId;
/**
* Create Navigation bar and load the main fragment "statistics".
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadFragment(new FragmentStatistics());
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(this);
mSelectedId = navigation.getSelectedItemId();
}
/**
* Checks for any event in the Navigation Bar.
* If the item selected is the same as the actual item
* Do nothing
* Else
* Load new fragment selected.
*/
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
if (mSelectedId != item.getItemId()) {
mSelectedId = item.getItemId();
switch (item.getItemId()) {
case R.id.statistics:
fragment = new FragmentStatistics();
break;
case R.id.shops:
fragment = new FragmentShops();
break;
}
}
return loadFragment(fragment);
}
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
}
The rest of your code is exact as mine.
I have just started with android fragment and git stuck while implementing an example from internet.Attaching the following code below.It would be really grate to get some help.
I am getting a error at the line ft.add(R.id.fragmentone,fragment).
Regards.
MainActivity.java
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void getfragment(View view) {
FragmentOne fragment = new FragmentOne();
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.add(R.id.fragmentone,fragment);
}
}
FragmentOne.java
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment_one, container,false);
}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.vighnesh.fragmentsexp.MainActivity"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/buttonfragment"
android:layout_margin="20dp"
android:text="Click to open fragment"/>
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragmentone"
android:layout_margin="20dp">
</fragment>
</LinearLayout>
fragment_fragment_one.xml
<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"
tools:context="com.example.vighnesh.fragmentsexp.FragmentOne">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</FrameLayout>
Replace this code in your activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getfragment();
}
public void getfragment() {
FragmentOne fragment = new FragmentOne();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragmentone, fragment);
ft.commit();
}
change it.
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnFragOne = (Button)findViewById(R.id.buttonfragment);
btnFragOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentOne fragment = new FragmentOne();
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.add(R.id.fragmentone,fragment); getfragment();
}
});
}
}
So use getSupportFragmentManager() instead of getFragmentManager()
Because the FragmentOne is from the support library (android.support.v4.app.Fragment) not from the framework (android.app.Fragment), you need to use android.support.v4.app.FragmentManager to do transaction with FragmentOne.
I have a navigation drawer which I would like to press the button in the list view and change the fragment on the right side instantly. How can I do that? Why my code doesn't work?
Here is my code:
DrawerFragment.class
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import java.util.ArrayList;
public class DrawerFragment extends Fragment {
private static ListView mSelectionListView;
private ImageView mUserIcon;
private TextView mUserName;
//region (Widgets) Declaration
NonScrollListView mNewsListView, mELeaveListView, mEClaimListView, mEAttendanceListView;
//endregion
//DrawerFragmentListener drawerFragmentListener;
//endregion
Fragment mFragment;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
ExpenseClaimPageFragment expenseClaimPageFragment;
ClaimFormPageFragment claimFormPageFragment;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_drawer_fragment, container, false);
expenseClaimPageFragment = new ExpenseClaimPageFragment();
claimFormPageFragment = new ClaimFormPageFragment();
mEClaimListView = (NonScrollListView) view.findViewById(R.id.drawer_fragment_eClaim_selection);
ArrayList<DrawerSelectionEClaimResult> selectionEClaimResults = GetDrawerSelectionEClaimResult();
mEClaimListView.setAdapter(new CustomDrawerSelectionEClaimBaseAdapter(getActivity(), selectionEClaimResults));
mEClaimListView.setOnItemClickListener(mEClaimListViewOnItemClick);
return view;
}
public ArrayList<DrawerSelectionEClaimResult> GetDrawerSelectionEClaimResult() {
ArrayList<DrawerSelectionEClaimResult> results = new ArrayList<>();
DrawerSelectionEClaimResult dsecr = new DrawerSelectionEClaimResult();
dsecr.setSelection("Expenses Claim Entry");
dsecr.setDrawable(R.drawable.expenseclaim);
results.add(dsecr);
dsecr = new DrawerSelectionEClaimResult();
dsecr.setSelection("Expenses Claim Form");
dsecr.setDrawable(R.drawable.expenseclaim);
results.add(dsecr);
return results;
}
public NonScrollListView.OnItemClickListener mEClaimListViewOnItemClick = new NonScrollListView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch(position)
{
case 0:
mFragmentManager = getActivity().getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragment = new ExpenseClaimPageFragment();
mFragmentTransaction.replace(R.id.MainPageFrameLayout, mFragment);
mFragmentTransaction.commit();
break;
case 1:
mFragmentManager = getActivity().getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragment = new ClaimFormPageFragment();
mFragmentTransaction.replace(R.id.MainPageFrameLayout, mFragment);
mFragmentTransaction.commit();
break;
}
}
};
}
Main.xml
<!--Main Content View (Expense Claim Page Content)-->
<FrameLayout
android:id="#+id/MainPageFrameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.sample.flexsystem.expenseclaimapplication.ExpenseClaimPageFragment"
android:id="#+id/fragment2"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
tools:layout="#layout/activity_expenseclaim_page" />
</FrameLayout>
<!--Navigation Drawer View-->
<LinearLayout
android:id="#+id/DrawerLin"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#FFFFFF"
android:orientation="vertical">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:name="com.sample.flexsystem.expenseclaimapplication.DrawerFragment"
android:id="#+id/fragment"
tools:layout="#layout/activity_drawer_fragment" />
</LinearLayout>
I have no idea why my code doesn't work, what is the main code to replace the fragment to another? I know that I need a layout to save a fragment inside and use replace() method to handle it, but it didn't work. Is there anything wrong of my code?
I think I can not replace the fragment from another fragment since fragment doesn't communicate to each other right?
UPDATE 1
Main Activity class
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
public class ExpenseClaimPage extends AppCompatActivity implements DrawerFragment.DrawerFragmentListener{
DrawerLayout mDrawerLayout;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
Fragment mFragment;
#Override
public void setPosition(int position)
{
switch(position)
{
case 0:
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragment = new ExpenseClaimPageFragment();
mFragmentTransaction.replace(R.id.MainPageFrameLayout, mFragment);
mFragmentTransaction.addToBackStack(null);
mFragmentTransaction.commit();
break;
case 1:
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragment = new ClaimFormPageFragment();
mFragmentTransaction.replace(R.id.MainPageFrameLayout, mFragment);
mFragmentTransaction.addToBackStack(null);
mFragmentTransaction.commit();
break;
}
}
//region onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
}
//endregion
#Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
Looking at your main.xml, the main content:
Main Content View (Expense Claim Page Content)
<FrameLayout
android:id="#+id/MainPageFrameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="ExpenseClaimPageFragment"
android:id="#+id/fragment2"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
tools:layout="#layout/activity_expenseclaim_page" />
</FrameLayout>
You cant replace fragment which is added by using xml. Therefore, I suggest that you should add your ExpenseClaimPageFragment manually when the activity is created. After that, you can replace it with another fragment easily.
I am new to android and learning fragment instead of multiple, i have problem. when i call planet fragment from friends "java.lang.IllegalStateException: Activity has been destroyed" android runtime FATAL exception occurs here is my code. i saw this page but couldn't figure out how to use it. I will be grateful for any help
fragment_planet.xml
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:gravity="center"
android:padding="32dp" />
Friends.java
package com.app.hubara;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Friends extends Fragment {
public Friends() { }
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.content_friends, container, false);
MainActivity main = new MainActivity();
main.friends();
return rootView;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="100dp"/>
<Button
android:id="#+id/display"
android:height="70dp"
android:width="300dp"
android:layout_marginTop="0dp"
android:text="Display"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
MainActivity
package com.app.hubara;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import java.util.Locale;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.display);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Friends frag_friends = new Friends();
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, frag_friends);
fragmentTransaction.commit();
}
});
}
public void friends(){
PlanetFragment planetFragment = new PlanetFragment();
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, planetFragment);
fragmentTransaction.commit();
}
public static class PlanetFragment extends Fragment {
public PlanetFragment() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt("Earth");
String planet = getResources().getStringArray(R.array.planets_array)[i];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", "Earth");
((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
}
To access an Activity, you shouldn't do this:
MainActivity main = new MainActivity();
main.friends();
Because this destroys current Activity then instantiates another new Activity.
You can access it appropriately by calling getActivity():
MainActivity main = getActivity();
main.friends();
Note that actually you are recommended to define and use an interface to communicate between Fragment and Activity. If you want to learn further, please refer to the official training.
my problem is that as soon as i call a fragment in my main layout, the fragment is called in the frame, but after that, the onitemclick listener stops working. what is that i missed ?
the main.java
import java.util.Locale;
import android.annotation.TargetApi;
import android.app.Activity;
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.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
public class Main extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mDrawerMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTitle = mDrawerTitle = getTitle();
mDrawerMenu = getResources().getStringArray(R.array.menu);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_view);
// set a custom shadow that overlays the main content when the drawer opens
//mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.custom_menu_list, mDrawerMenu));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
//Action bar on item click events
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action buttons
switch(item.getItemId()) {
case R.id.menu_icon:
// create intent to perform web search for this planet
Log.d("Hello","Menu clicked");
mDrawerLayout.openDrawer(mDrawerList);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listener for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
Log.d("Hello", String.valueOf(position));
//Get the option name and compare
TextView text = (TextView) arg1.findViewById(android.R.id.text1);
String MenuName = text.getText().toString();
Log.d("Click", MenuName);
if(position == 0){
Log.d("Click","Home Clicked");
// update the main content by replacing fragments
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MenuFragment fragment = new MenuFragment();
fragmentTransaction.replace(R.id.drawer_layout, fragment, String.valueOf(position));
fragmentTransaction.commit();
}
else if(position == 1){
Log.d("Click","News Clicked 2");
}
mDrawerLayout.closeDrawer(mDrawerList);
}
}
}
This is the main.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"/>
<!-- The navigation drawer -->
<ListView android:id="#+id/list_view"
android:layout_width="320dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#000000"/>
</android.support.v4.widget.DrawerLayout>
This is the menugragment which calls the layout.
public class MenuFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.sports, container, false);
}
}
Now, as it is replaced in the frame in main (when the position is 0, the fragment is called),after that if 1 is called, the onitemclicklistener does not work. why is that ?
Thank you
replace
fragmentTransaction.replace(R.id.drawer_layout, fragment, String.valueOf(position));
to
fragmentTransaction.replace(R.id.content_frame, fragment, String.valueOf(position));
You should replace the content_frame not the drawer_layout