Fragments still visible after calling replace method - android

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>

Related

Fragment activity does not appear automatically

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.

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

android PagerTabStrip to start from left and not center

i have a pager tab strip in my project and when run on emulator or device it starts center like this
what i would like to achieve is to have the tab start left like this
I have tried layout graviity left in my xml but this is not working for me and i can't put my finger on how to resolve this, here is my xml with the pager tab strip.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity" >
<android.support.v4.view.PagerTabStrip
android:layout_width="wrap_content"
android:layout_height="50dp"
android:background="#drawable/gradient_bg"
android:textColor="#fff"
android:textSize="20sp"
android:id="#+id/tab_strip"
android:focusableInTouchMode="false">
</android.support.v4.view.PagerTabStrip>
</android.support.v4.view.ViewPager>
</LinearLayout>
java code
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
public class MainActivity extends FragmentActivity {
//adview
ViewPager pager;
PagerTabStrip tab_strp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_tab);
ma_pager_adapter mapager=new ma_pager_adapter(getSupportFragmentManager());
pager=(ViewPager)findViewById(R.id.pager);
pager.setAdapter(mapager);
tab_strp=(PagerTabStrip)findViewById(R.id.tab_strip);
tab_strp.setTextColor(Color.WHITE);
// tab_strp.setTextSize(14,14);
// tab_strp.setTabIndicatorColor(Color.WHITE);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.firsteps);
mp.start();
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
if(hasFocus){
ImageView welcomeText = (ImageView)findViewById(R.id.btsMainTextImage);
//welcomeText.animate().rotation(1440f).setDuration(2000);
}
}
#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.share) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.Locale;
//final MediaPlayer mp = MediaPlayer.create(this, R.raw.short_whoosh2);
public ma_pager_adapter(FragmentManager fm) {
super(fm);
}
//final MediaPlayer mp = MediaPlayer.create(this, R.raw.short_whoosh2);
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
tab1 t1 = new tab1();
return t1;
case 1:
tab2 t2 = new tab2();
return t2;
case 2:
tab4 t4 = new tab4();
return t4;
case 3:
tab3 t3 = new tab3();
return t3;
case 4:
tab5 t5 = new tab5();
return t5;
}
return null;
}
#Override
public int getCount() {
return 5;
}//set the number of tabs
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return "Tab1";
case 1:
return "Tab2";
case 2:
return "Tab3";
case 3:
return "Tab4";
case 4:
return "Tab5";
}
return null;
}
}
That is not possible with PagerTabStrip and ToolBar. Since ActionBarTabs have been deprecated, use a TabLayout.
Here is the Code that how you can use TabLayout easily.
Here is the output that you will get.
main_activty.xml or any of your XML file where your want to use these Tabs and Viewpager
<android.support.design.widget.AppBarLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" android:id="#+id/appBarLayout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabTextColor="#f9f8f8"
app:tabSelectedTextColor="#fff"
app:tabGravity="fill"
app:tabMode="fixed"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="left"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
app:layout_constraintTop_toBottomOf="#+id/appBarLayout" app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent">
</android.support.v4.view.ViewPager>
That XML code should work for you. For the complete code, you can visit here - https://tutorialvilla.com/how/how-to-use-tablayout-and-viewpager-in-android-kotlin

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.

Android app stop when is being to run

I'm new to android and java. this is my first app. an example of a book. I did all steps according the book. the app is going to increase the number by click on + button
this is my Java file :
package com.example.myprayercounter;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
#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();
}
}
#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 {
int counter;
TextView tView;
Button btn;
public PlaceholderFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
counter = 0;
tView = (TextView)getActivity().findViewById(R.id.txt_textTwo);
btn = (Button)getActivity().findViewById(R.id.btn_buttonOne);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
tView.setText(" " + counter);
}
});
return rootView;
}
}
}
xml file :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fbfbdd"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.myprayercounter.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/txt_textOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="تعداد ذکرهای من"
android:textColor="#763f05"
android:textSize="20dp" />
<TextView
android:id="#+id/txt_textTwo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textColor="#763f05"
android:textSize="40dp" />
<Button
android:id="#+id/btn_buttonOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#763f05"
android:text="+"
android:textColor="#fbfbdd"
android:textSize="40dp" />
</LinearLayout>
I got this error at first run of the app :
What is my mistakes? and how i can fix them?
Thanks in advance
change:
tView = (TextView)getActivity().findViewById(R.id.txt_textTwo);
btn = (Button)getActivity().findViewById(R.id.btn_buttonOne);
to ( getActivity() --> rootView)
tView = (TextView)rootView.findViewById(R.id.txt_textTwo);
btn = (Button)rootView.findViewById(R.id.btn_buttonOne);
in PlaceholderFragment, your View is rootView and you need find your view from that

Categories

Resources