Fragment activity does not appear automatically - android

I'm working on a project in which I used Bottom Navigation Bar But when I run the application the fragment activity does not appear automatically until I tap on the icon in menu item of bottom navigation bar.
screenshot:
The blank activity appears first when I tap on any fragment activity then it appears.
Here is my code:
BottomNavigation.java
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.FrameLayout;
public class BottomNavigation extends AppCompatActivity {
private BottomNavigationView mMianNav;
private FrameLayout mMainFrame;
private AllResturant allResturant;
private UserProfile userprofile;
private ActivityUser activityUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom_navigation);
mMainFrame = (FrameLayout) findViewById(R.id.main_frame);
mMianNav = (BottomNavigationView) findViewById(R.id.main_nav);
allResturant = new AllResturant();
userprofile = new UserProfile();
activityUser = new ActivityUser();
//Listener for handling selection events on bottom navigation items
mMianNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.toprofile:
setFragment(userprofile);
return true;
case R.id.tohome:
setFragment(allResturant);
return true;
case R.id.toactivity:
setFragment(activityUser);
return true;
case R.id.tologout:
logout();
return true;
default:
return false;
}
}
private void logout() {
Intent intent = new Intent(BottomNavigation.this, Registration.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
});
}
private void setFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame, fragment);
fragmentTransaction.commit();
}
}
BottomNavigation.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".BottomNavigation">
<android.support.design.widget.BottomNavigationView
android:id="#+id/main_nav"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
app:itemIconTint="#color/nav_items_color"
app:itemTextColor="#color/nav_items_color"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
app:menu="#menu/nav_items" />
<FrameLayout
android:id="#+id/main_frame"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_above="#+id/main_nav"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
app:layout_constraintBottom_toTopOf="#+id/main_nav"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</FrameLayout>
</android.support.constraint.ConstraintLayout>
How it will appear automatically?

modify your on create as below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom_navigation);
mMainFrame = (FrameLayout) findViewById(R.id.main_frame);
mMianNav = (BottomNavigationView) findViewById(R.id.main_nav);
allResturant = new AllResturant();
userprofile = new UserProfile();
activityUser = new ActivityUser();
setFragment(userprofile);
//Listener for handling selection events on bottom navigation items
mMianNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.toprofile:
setFragment(userprofile);
return true;
case R.id.tohome:
setFragment(allResturant);
return true;
case R.id.toactivity:
setFragment(activityUser);
return true;
case R.id.tologout:
logout();
return true;
default:
return false;
}
}
private void logout() {
Intent intent = new Intent(BottomNavigation.this, Registration.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
});
}

Set first fragment yourself after setting up UI. Add below line at last line of onCreate() method.
setFragment(userprofile);
Cause of fail
Because when your Activity starts then onNavigationItemSelected not called, it will be called when user switch screen.

Your code is almost perfect. The only thing that you didn't do is inflate an Fragment when the Activity is created.
After creating the Activity you need to inflate the Fragment that you want once by using this line:
setFragment(userprofile);
You can put it in your onCreate method after instantiating the fragments. After that, your OnNavigationItemSelectedListener will take care of inflating the fragments.

Related

Android studio, BottomNavigationView

So I have a problem with my application. I select item from BottomNavigationView and he switch activity normally, but have a problem to change item selected why remains to home not to new activity item..
code Java main activity:
package mediaser.tivvmialive;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;
import android.net.Uri;
import android.widget.MediaController;
import android.widget.VideoView;
public class MainActivity extends AppCompatActivity {
private TextView mTextMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextMessage = (TextView) findViewById(R.id.message);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
VideoView videoView =(VideoView)findViewById(R.id.videoView2);
MediaController mediaController= new MediaController(this);
mediaController.setAnchorView(videoView);
Uri uri=Uri.parse("http://rumblehwk.altervista.org/VideoHome/default.mp4");
videoView.setMediaController(mediaController);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
Intent myIntent = new Intent(MainActivity.this, MainActivity.class);
startActivity(myIntent);
break;
case R.id.navigation_dashboard:
Intent myIntent2 = new Intent(MainActivity.this, Archivio.class);
startActivity(myIntent2);
break;
case R.id.navigation_notifications:
break;
}
return true;
}
};
}
And archivio activity is identic cose
You say that the Archivo activity is equal to MainActivity, so what happens is that when you enter the option R.id.navigation_dashboard it opens the Archivo activity that when it is displayed, shows the first BottomNavigation option but the Activity Archivo and not the MainActivity
To achieve that effect you must use a FragmentLayout
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<FrameLayout
android:id="#+id/contenido"
android:layout_width="match_parent"
android:layout_marginTop="0dp"
android:layout_height="match_parent"
android:layout_marginBottom="56dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:fitsSystemWindows="true"/>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:fitsSystemWindows="false"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:elevation="6dp"
android:background="#color/blanco"
android:foreground="?attr/selectableItemBackground"
app:menu="#menu/menu_propietario"/>
</android.support.design.widget.CoordinatorLayout>
And in the MainActivity class
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
Fragment fragment;
FrameLayout frameLayout;
BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
frameLayout = (FrameLayout) findViewById(R.id.contenido);
bottomNavigationView.setOnNavigationItemSelectedListener(this);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fr = fragment;
switch (item.getItemId()){
case R.id.navigation_home:
pestaƱa = R.id.inicio;
fragment = InicioFragment.newInstance();
break;
case R.id.navigation_dashboard:
fragment = ArchivoFragment.newInstance();
break;
case R.id.navigation_notifications:
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (fr != null){
transaction.remove(fr);
}
if(fragment != null){
transaction.replace(R.id.contenido, fragment);
}
transaction.commit();
return true;
}
}
and your ArchiveFragment class like that
public class ArchiveFragment extends Fragment {
public ArchiveFragment() {
}
public static ArchiveFragment newInstance() {
ArchiveFragmentFragment fragment = new ArchiveFragmentFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_archive, container, false);
return view;
}
}
I hope I've helped
BottomNavigationView resolved thx, but another problem ... "findViewById error cannot resolve method"
Code home (not main activity).
package mediaser.tivvmialive;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.net.Uri;
import android.widget.MediaController;
import android.widget.VideoView;
public class Home extends Fragment {
public static Home newInstance() {
Home fragment = new Home();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
VideoView mVideoView2 = (VideoView)findViewById(R.id.videoView2);
String uriPath2 = "http://rumblehwk.altervista.org/VideoHome/default.mp4";
Uri uri2 = Uri.parse(uriPath2);
mVideoView2.setVideoURI(uri2);
mVideoView2.requestFocus();
mVideoView2.start();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_home, container, false);
}
}

How to display another view in Bottom Navigation Activity?

I am wondering what is the simplest way to display a View instead of
mTextMessage.setText(R.string.title_home); in a Bottom Navigation Activity?
public class MainActivity extends AppCompatActivity {
private TextView mTextMessage;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
// How to display anotherView here?
mTextMessage.setText(R.string.title_home);
return true;
case R.id.navigation_dashboard:
mTextMessage.setText(R.string.title_dashboard);
return true;
case R.id.navigation_notifications:
mTextMessage.setText(R.string.title_notifications);
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextMessage = (TextView) findViewById(R.id.message);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
}
I found good solution here Start fragment in BottomNavigationView
My working code is following
MainActivity
public class MainActivity extends AppCompatActivity {
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
switch (item.getItemId()) {
case R.id.navigation_home:
FragmentOne selectedFragment1 = new FragmentOne();
transaction.replace(R.id.fragmentContainer, selectedFragment1);
break;
case R.id.navigation_dashboard:
FragmentTwo selectedFragment2 = new FragmentTwo();
transaction.replace(R.id.fragmentContainer, selectedFragment2);
break;
case R.id.navigation_notifications:
FragmentThree selectedFragment3 = new FragmentThree();
transaction.replace(R.id.fragmentContainer, selectedFragment3);
break;
}
transaction.commit();
return true;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
navigation.setSelectedItemId(R.id.navigation_home);
}
}
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:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="android.apps.myapp.gpsmegatracker.MainActivity"
android:orientation="vertical">
<FrameLayout
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="?android:attr/windowBackground"
app:menu="#menu/navigation" />
</LinearLayout>
Fragment classes are the same
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 {
public FragmentOne() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_fragment_one, container, false);
}
}
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=".FragmentOne">
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1" />
</FrameLayout>

How to set URL image properly in Android?

I am new to android, I am trying to open URL image on my main screen. My problem is that I am using navigation drawer also on my main page. Everything works fine only my main image which is coming from database is going slightly upwards, whereas the example which I copied in that the image is looking perfectly.
I don't know why my image is going upwards. The image should render like this :
My image is rendering like this:
Here is my FragmentOne.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical">
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.7">
<ImageView
android:id="#+id/ms1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:src="#mipmap/ic_launcher" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.3">
<ImageView
android:id="#+id/ms2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:scaleType="fitXY"
android:src="#mipmap/ic_launcher" />
<ImageView
android:id="#+id/ms3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:scaleType="fitXY"
android:src="#mipmap/ic_launcher" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
My containt_main.xml
<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">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</RelativeLayout>
My Main activity:
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
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.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.example.zeba.broccoli.AddToCart;
import com.example.zeba.broccoli.FragmentOne;
import com.example.zeba.broccoli.FragmentTwo;
import com.example.zeba.broccoli.Login;
import com.example.zeba.broccoli.R;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
/**
* As i told you i just create only navigation drawer with displaying images.
* I jus created two fragment only for understanding purpose.
* If you want more then developed by yourself.
* Remove this comment no need after you understood.
* #param savedInstanceState
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//add this line to display menu1 when the activity is loaded
displaySelectedScreen(0);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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) {
switch (item.getItemId()) {
case R.id.action_settings:
// User chose the "Settings" item, show the app settings UI...
case R.id.action_cart:
Intent ibs = new Intent(MainActivity.this,AddToCart.class);
ibs.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(ibs);
finish();
break;
// User chose the "Favorite" action, mark the current item
// as a favorite...
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.br_menu) {
Intent i = new Intent(MainActivity.this,Login.class);
startActivity(i);
displaySelectedScreen(0);
}
else if (id == R.id.tr_ordr)
{
displaySelectedScreen(1);
}
else if (id == R.id.pl_ordr)
{
displaySelectedScreen(2);
} else if (id == R.id.profl)
{
displaySelectedScreen(3);
}
else if (id == R.id.addr)
{
displaySelectedScreen(4);
} else if (id == R.id.crds)
{
displaySelectedScreen(5);
}
return true;
}
private void displaySelectedScreen(int position)
{
try {
Fragment fragment = null;
if (position == 0)
{
fragment = new FragmentOne();
}
else if (position == 1)
{
fragment = new FragmentTwo();
}
else if (position == 2)
{
} else if (position == 3) {
} else if (position == 4) {
} else if (position == 5) {
}
//replacing the fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}catch (Exception e){
e.printStackTrace();
}
}
}
My FragmentOne.java
public class FragmentOne extends Fragment
{
Activity activity;
View rootView;
ImageView im1, im2, im3;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
rootView = inflater.inflate(R.layout.fragment_one, container, false);
activity = getActivity();
im1 = (ImageView)rootView.findViewById(R.id.ms1);
im2 = (ImageView)rootView.findViewById(R.id.ms2);
im2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Login.class);
startActivity(intent);
}
});
im3 = (ImageView)rootView.findViewById(R.id.ms3);
Picasso.with(activity).load("http://i.imgur.com/DvpvklR.png").into(im1);
Picasso.with(activity).load("https://api.learn2crack.com/android/images/donut.png").into(im2);
Picasso.with(activity).load("http://hdwallpaperbackgrounds.net/wp-content/uploads/2016/07/hd-nature-wallpapers.jpg").into(im3);
return rootView;
}
}
I tried doing debugging but then also no use, it's so weird problem.
The problem occur for main_content xml . your image is cut off when you use it in you main_activity xml . Use this trick it will work . Simple put margin above your main_content xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_marginTop="?actionBarSize"
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</RelativeLayout>
You have to include a custom action bar in your layout.
Please follow this link. It is explained very nicely with the code snaps and in depth. :)
In MainAcitivity you should extends Activity no an AppCompatActivity. AppCompatActivity show a bar

Fragments get not replaced during OnClick event in navigation drawer

I created a menu with 5 items in a navigation drawer, the 5 items represent 5 different fragments, each time an item gets clicked it should show the related fragment.
Another click on a different item, fragment should be replaced and so on.
I created 5 seperate classes for the fragments.
When i start the app and click an item the very first time, the related fragment gets shown but after i click another item in the menu nothing happens (the fragment gets not replaced), i also get no errors and the app does not crash.
I don`t know where the problem is hopefully somebody can help, here is my code:
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private Toolbar toolbar;
private MyAdapter myAdapter;
public ListView mainMenuList;
public Fragment_Android fAndroid;
public Fragment_Latest_Releases fLatest;
public Fragment_My_Applications fMyapps;
public Fragment_Platforms fPlatforms;
public Fragment_Settings fSettings;
public android.support.v4.app.FragmentManager fragmanager;
public android.support.v4.app.FragmentTransaction fragtrans;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
mainMenuList = (ListView) findViewById(R.id.testList);
myAdapter = new MyAdapter(this);
mainMenuList.setAdapter(myAdapter);
toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp((R.id.fragment_navigation_drawer), (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
fAndroid = new Fragment_Android();
fLatest = new Fragment_Latest_Releases();
fMyapps = new Fragment_My_Applications();
fPlatforms = new Fragment_Platforms();
fSettings = new Fragment_Settings();
mainMenuList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0: {
Toast.makeText(getApplicationContext(), "Android has been clicked.", Toast.LENGTH_SHORT).show();
fragmanager = getSupportFragmentManager();
fragtrans = fragmanager.beginTransaction();
fragtrans.replace(R.id.fragment_container, fAndroid);
fragtrans.commit();
drawer.closeDrawers();
break;
}
case 1: {
Toast.makeText(getApplicationContext(), "Latest Releases has been clicked.", Toast.LENGTH_SHORT).show();
fragmanager = getSupportFragmentManager();
fragtrans = fragmanager.beginTransaction();
fragtrans.replace(R.id.fragment_container, fLatest);
fragtrans.commit();
drawer.closeDrawers();
break;
}
case 2: {
Toast.makeText(getApplicationContext(), "Platforms has been clicked.", Toast.LENGTH_SHORT).show();
fragmanager = getSupportFragmentManager();
fragtrans = fragmanager.beginTransaction();
fragtrans.replace(R.id.fragment_container, fPlatforms);
fragtrans.commit();
drawer.closeDrawers();
break;
}
case 3: {
Toast.makeText(getApplicationContext(), "My Applications has been clicked.", Toast.LENGTH_SHORT).show();
fragmanager = getSupportFragmentManager();
fragtrans = fragmanager.beginTransaction();
fragtrans.replace(R.id.fragment_container, fMyapps);
fragtrans.commit();
drawer.closeDrawers();
break;
}
case 4: {
Toast.makeText(getApplicationContext(), "Settings has been clicked.", Toast.LENGTH_SHORT).show();
fragmanager = getSupportFragmentManager();
fragtrans = fragmanager.beginTransaction();
fragtrans.replace(R.id.fragment_container, fSettings);
fragtrans.commit();
drawer.closeDrawers();
break;
}
}
}
});
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#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) {
// 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_settings) {
Toast.makeText(this, "Just hit settings.." + item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Example of 1 class (in this case Android):
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment_Android extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View fragandroid = inflater.inflate(R.layout.layout_android, null);
return fragandroid;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
Example of 1 fragment xml (Android fragment):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
My main activity xml:
<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"
android:orientation="vertical"
tools:context="android.kadas.org.teka.MainActivity">
<include
android:id="#+id/my_toolbar"
layout="#layout/app_bar" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="android.kadas.org.teka.NavigationDrawerFragment"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
In the click listener you are actually replacing the entire layout of the activity with the desired fragment.
In your main activity's xml add the following layout, inside the RelativeLayout:
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Change your
fragtrans.replace(R.id.drawer_layout, fragmentX);
statements to
fragtrans.replace(R.id.container, fragmentX);
Finally solved due to the big help of Alexandru Rosianu.
The code has been amended with the correct one.

Fragments still visible after calling replace method

I know this has other answers but I've looked around and tried other solutions; all of which did not work.
I have a menu with items that are clickable; and when clicked they replace a Fragment on the main screen with another Fragment.
Here is my code:
package com.nanospark.cnc;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
//import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
GridLayout_Fragment profileGridFragment = new GridLayout_Fragment();
EventList_Fragment eventListFragment = new EventList_Fragment();
ContactList_Fragment contactListFragment = new ContactList_Fragment();
FragmentManager transactionManager = getSupportFragmentManager();
FragmentTransaction transaction;
//CustomIOIO customioio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null){
transaction = transactionManager.beginTransaction();
transaction.replace(R.id.fragment_frame, profileGridFragment);
transaction.commit();
}
//insert the initial fragment for when the app boots.
/* customioio = (CustomIOIO) getApplicationContext();
customioio.create();
customioio.start();*/
}
#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();
switch (id) {
case R.id.action_settings:
openSettings();
return true;
case R.id.action_home:
openHome();
return true;
case R.id.action_events:
openEvents();
return true;
case R.id.action_help:
openHelp();
return true;
case R.id.action_contacts:
openContacts();
return true;
}
return super.onOptionsItemSelected(item);
}
private void openContacts() {
transaction = transactionManager.beginTransaction();
transaction.replace(R.id.fragment_frame, contactListFragment);
transaction.commit();
}
private void openHome() {
transaction = transactionManager.beginTransaction();
transaction.replace(R.id.fragment_frame, profileGridFragment);
transaction.commit();
}
private void openHelp() {
}
private void openEvents() {
transaction = transactionManager.beginTransaction();
transaction.replace(R.id.fragment_frame, eventListFragment);
transaction.commit();
}
private void openSettings() {
}
}
I am not sure as to why the previous Fragments are still visible?
EDIT - adding my activiy_main.xml layout file:
<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.nanospark.cnc.MainActivity" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/fragment_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
</LinearLayout>
</RelativeLayout>

Categories

Resources