I created a bottom navigation for my app and was wondering how could I make it so when the user opens the app, it returns to the last fragment they were viewing? At the moment even if you just switch apps for a second, it reverts to the home page immediately. Thanks in advance!
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.MenuItem;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomnav = findViewById(R.id.bottom_menu);
bottomnav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout, new HomeFragment()).commit();
mediaPlayer = MediaPlayer.create(this, R.raw.clickandboop);
}
private final BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()) {
case R.id.nav_home:
selectedFragment = new HomeFragment();
mediaPlayer.start();
break;
case R.id.nav_favourites:
selectedFragment = new FavFragment();
mediaPlayer.start();
break;
case R.id.nav_trophies:
selectedFragment = new TrophiesFragment();
mediaPlayer.start();
break;
case R.id.nav_info:
selectedFragment = new InfoFragment();
mediaPlayer.start();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout, selectedFragment).commit();
return true;
}
};
Fragments already restore you back to exactly where you were.
This means that you need to wrap your replace() call with a check of savedInstanceState == null to avoid destroying the just recreated Fragment:
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_layout, new HomeFragment())
.commit();
}
Just use sharedprefs and store the last fragment that the user was in. Use the onStop callback of the fragment to store it.
When the user opens the application just check this value if it's not set open homefragment otherwise just open the last fragment based on the value you have in your shared preferences
Related
I am currently writing an app that includes a BottomNavigationBar (android studio)
but I got a problem:
I want the layouts to switch (or at least the TextViews inside each),
currently the navigation is not doing more than switching between single strings. so how can I make it work? please give me a step-by-step guide because I am fairly new to this whole stuff.
here's some code:
package com.john.doe.mycvasapp;
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;
public class Personal 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.personal:
mTextMessage.setText(R.string.personal1);
return true;
case R.id.school:
mTextMessage.setText(R.string.school1);
return true;
case R.id.work:
mTextMessage.setText(R.string.work1);
return true;
case R.id.skills:
mTextMessage.setText(R.string.skills1);
return true;
case R.id.lastly:
mTextMessage.setText(R.string.lastly1);
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_persoenliche_daten);
mTextMessage = (TextView) findViewById(R.id.message);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
}
thanks for all the incoming help,
regards, guy from internet
Here I make a DrawerBase activity to let all of my Activity to have the same DrawerLayout, However when I do like this, some boring thing happened, when I start a new Intent to start new Activity the did not close the drawers.
Here is my code, hope someone could help me.
package cn.rezero.utool;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import cn.rezero.utool.Note.NotelistActivity;
/**
* Created by ReZero on 2017/4/5.
*/
public class DrawerBase extends AppCompatActivity {
protected DrawerLayout mDrawerLayout;
protected NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setCheckedItem(R.id.nav_moment);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.nav_lbs:
startActivity(new Intent(DrawerBase.this, BmapActivity.class));
mDrawerLayout.closeDrawers();
break;
case R.id.nav_note:
startActivity(new Intent(DrawerBase.this, NotelistActivity.class));
mDrawerLayout.closeDrawers();
break;
case R.id.nav_web:
startActivity(new Intent(DrawerBase.this, BrowserActivity.class));
mDrawerLayout.closeDrawers();
default:
}
return true;
}
});
}
}
this a test demo :
public class MainActivity extends DrawerBase {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Remove this line from your drawer layout...
setContentView(R.layout.activity_main);
and override the setContentView like this
#Override
public void setContentView(int layoutResID) {
DrawerLayout fullView = (DrawerLayout) getLayoutInflater().inflate(R.layout.activity_base, null);
FrameLayout activityContainer = (FrameLayout) fullView.findViewById(R.id.activity_content);
getLayoutInflater().inflate(layoutResID, activityContainer, true);
super.setContentView(fullView);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle("Activity Title");
}
replace
startActivity(new Intent(DrawerBase.this, BmapActivity.class));
mDrawerLayout.closeDrawers();
to
mDrawerLayout.closeDrawer(GravityCompat.START);
startActivity(new Intent(this, BmapActivity.class));
return true;
You can see the full implementation from here Adding a Toolbar and Navigation Drawer Across all Activities of an Android App
Use this :
mDrawerLayout.closeDrawer(GravityCompat.START);
use this method
/**
* Close Navigation Drawer
*/
private void closeNavMenu() {
if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START);
}
}
you Just try this
mDrawerLayout.closeDrawer(GravityCompat.START);
You need to use
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START);
}
rather than
mDrawerLayout.closeDrawers();
This issue has persisted repeatedly no matter how many times I redo this. According to Android Developers, the ID to an object in the View Hierarchy of a fragment is obtained during onCreateView, and all of the questions I've pored over on here confirm this. However for some reason it ALWAYS returns null during the check I have setup and therefore I can not proceed to work with the buttons. The Fragment gets loaded during "decision events" in this project, and each event has different decisions. Thus I want to use just one fragment and change the button texts as appropriate. However I can not seem to get them not to return null. I just need help to figure out what I am doing wrong that is causing the NPE.
DecisionFragment.java:
package com.saphiric.simproject.uimanipulation;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.saphiric.simproject.R;
import com.saphiric.simproject.datacontrols.DataCore;
public class DecisionFragment extends Fragment {
// Activity/Global variables
private static final String TAG = "DecisionFragment";
DataCore dataCore = DataCore.getInstance();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.i(TAG, "Begin: Inflate");
// Gets handles to important UI elements for scalability
View root = inflater.inflate(R.layout.fragment_decision, container, false);
Button buttonTrue = (Button) root.findViewById(R.id.btnChoiceOne);
Button buttonFalse = (Button) root.findViewById(R.id.btnChoiceTwo);
if(buttonTrue == null){
System.out.println("buttonTrue is null");
} else {
System.out.println("buttonTrue is working fine");
}
Log.i(TAG, "Finished: Inflate");
if (root == null){
Log.e(TAG, "omg Inflate == null");
}
switch (dataCore.controller.getCurrentDecision()){
case "OPSDecision":
// buttonTrue.setText(R.string.ops_decision_one);
// buttonFalse.setText(R.string.ops_decision_two);
break;
default:
System.out.println("ERROR: No decision set");
}
return root;
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
}
}
fragment_decision.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="90dp"
android:orientation="horizontal"
android:weightSum="1.0"
tools:context="com.saphiric.simproject.uimanipulation.DecisionFragment">
<Button
android:id="#+id/decisionOne"
android:layout_width="0dp"
android:layout_height="90dp"
android:layout_weight=".5"
android:text="#string/defaul_btn"
android:onClick="cryingDecisionOne"/>
<Button
android:id="#+id/decisionTwo"
android:layout_width="0dp"
android:layout_height="90dp"
android:layout_weight=".5"
android:text="#string/defaul_btn"
android:onClick="cryingDecisionTwo"/>
</LinearLayout>
DayOne.java:
package com.saphiric.simproject.activities;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.saphiric.simproject.R;
import com.saphiric.simproject.datacontrols.DataCore;
import com.saphiric.simproject.uimanipulation.ControlsFragment;
import com.saphiric.simproject.uimanipulation.DecisionFragment;
/**
* Created by Saphiric on 11/12/14.
*/
public class DayOne extends Activity {
/**
* Necessary activity variables
*/
ControlsFragment controlsFragment = new ControlsFragment();
DecisionFragment decisionFragment = new DecisionFragment();
DataCore dataCore = DataCore.getInstance();
/**
* Android activity methods
*
* #param savedInstanceState is the apps savedInstanceState
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_day_one);
// Initializes the opening story text
// Initializes the dayProgress variable in DataController
String storyStart = getResources().getString(R.string.story_opening_one);
dataCore.controller.setCurrentText(storyStart);
dataCore.controller.setCurrentDecision("OPSDecision");
// Handles for fragment management
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// UI will add the ControlsFragment in it's starting state for that activity.
fragmentTransaction.add(R.id.fragmentContainer, controlsFragment);
fragmentTransaction.commit();
}
#Override
public void onResume(){
super.onResume();
}
public void cryingDecisionOne(View view) {
dataCore.controller.setDayProgress(dataCore.controller.getDayProgress());
// Sets cryingDecision Story Lock
dataCore.locks.setCryingDecision(true);
dataCore.controller.setCurrentDecision("HLSOne");
// Removes the decision fragment and replaces it with the controls fragment
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Sets the text to be pulled to storyText
String decision = getResources().getString(R.string.crying_decision_true);
dataCore.controller.setCurrentText(decision);
fragmentTransaction.replace(R.id.fragmentContainer, controlsFragment);
fragmentTransaction.commit();
}
public void cryingDecisionTwo(View view) {
dataCore.controller.setDayProgress(dataCore.controller.getDayProgress());
// Sets cryingDecision choice
dataCore.locks.setCryingDecision(false);
dataCore.controller.setCurrentDecision("HWSOne");
// Removes the decision fragment and replaces it with the controls fragment
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Updates the currentText for updating the story view
String decision = getResources().getString(R.string.crying_decision_false);
dataCore.controller.setCurrentText(decision);
fragmentTransaction.replace(R.id.fragmentContainer, controlsFragment);
fragmentTransaction.commit();
}
public void advanceGameFunction(View view) {
String textUpdate;
// Handles for fragment management
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Obtains handles to UI components
TextView storyText = (TextView) findViewById(R.id.storyText);
RelativeLayout gameStart = (RelativeLayout) findViewById(R.id.gameStart);
ImageView charOne = (ImageView) findViewById(R.id.char_one);
ImageView charTwo = (ImageView) findViewById(R.id.char_two);
ImageView charThree = (ImageView) findViewById(R.id.char_three);
ImageView charFour = (ImageView) findViewById(R.id.char_four);
// Increments the data variable in DataController
dataCore.controller.setDayProgress(dataCore.controller.getDayProgress());
System.out.println(dataCore.controller.getDayProgress());
// Switch case for handling day progression
switch (dataCore.controller.getDayProgress()) {
case 1:
textUpdate = getResources().getString(R.string.story_opening_two);
dataCore.controller.setCurrentText(textUpdate);
storyText.setText(dataCore.controller.getCurrentText());
break;
case 2:
fragmentTransaction.replace(R.id.fragmentContainer, decisionFragment);
fragmentTransaction.commit();
break;
case 3:
if (dataCore.locks.getCryingDecision()) {
storyText.setText(dataCore.controller.getCurrentText());
} else {
storyText.setText(dataCore.controller.getCurrentText());
}
break;
case 4:
if (dataCore.locks.getCryingDecision()) {
textUpdate = getResources().getString(R.string.ops_d1_line1);
dataCore.controller.setCurrentText(textUpdate);
storyText.setText(dataCore.controller.getCurrentText());
} else {
textUpdate = getResources().getString(R.string.ops_d2_line1);
dataCore.controller.setCurrentText(textUpdate);
storyText.setText(dataCore.controller.getCurrentText());
}
break;
case 5: // Transition to hurt leg scene if Crying Decision is true, hallway scene if false
if (dataCore.locks.getCryingDecision()){
gameStart.setBackgroundResource(R.drawable.bg_gym_front);
textUpdate = getResources().getString(R.string.hls_line1);
dataCore.controller.setCurrentText(textUpdate);
storyText.setText(dataCore.controller.getCurrentText());
}else{
gameStart.setBackgroundResource(R.drawable.bg_hallway);
textUpdate = getResources().getString(R.string.hws_line1);
dataCore.controller.setCurrentText(textUpdate);
storyText.setText(dataCore.controller.getCurrentText());
}
break;
case 6:
if(dataCore.locks.getCryingDecision()){
textUpdate = getResources().getString(R.string.hls_line2);
dataCore.controller.setCurrentText(textUpdate);
storyText.setText(dataCore.controller.getCurrentText());
}else{
textUpdate = getResources().getString(R.string.hws_line2);
dataCore.controller.setCurrentText(textUpdate);
storyText.setText(dataCore.controller.getCurrentText());
}
break;
case 7:
if(dataCore.locks.getCryingDecision()){
charOne.setVisibility(View.VISIBLE);
textUpdate = getResources().getString(R.string.hls_line3);
dataCore.controller.setCurrentText(textUpdate);
storyText.setText(dataCore.controller.getCurrentText());
}else {
}
break;
case 8:
if(dataCore.locks.getCryingDecision()){
textUpdate = getResources().getString(R.string.hls_line4);
dataCore.controller.setCurrentText(textUpdate);
storyText.setText(dataCore.controller.getCurrentText());
}else{
}
break;
case 9:
if(dataCore.locks.getCryingDecision()){
}else{
}
break;
default:
System.out.println("Default case called");
}
}
}
You are using the wrong ids in your code! The buttons in your layout have the id decisionOne and decisionTwo but in your code you are using btnChoiceOne and btnChoiceTwo.
To fix it replace this:
Button buttonTrue = (Button) root.findViewById(R.id.btnChoiceOne);
Button buttonFalse = (Button) root.findViewById(R.id.btnChoiceTwo);
with this in your DecisionFragment:
Button buttonTrue = (Button) root.findViewById(R.id.decisionOne);
Button buttonFalse = (Button) root.findViewById(R.id.decisionTwo);
Your button ids in code do not match with the ones in xml layout.
In your xml, the id is 'decisionOne' but the code is looking for 'R.id.btnChoiceOne'
just getting started with Android development and I can't figure out why this won't work. Here is the error that I am getting (last line before bold block-quote):
package com.ample.ballv2;
import java.util.Random;
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.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
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();
}
Button answer = (Button) findViewById(R.id.answerbutton);
answer.setOnClickListener(answerL);
}
private OnClickListener answerL = new OnclickListener(){
public void onClick(view v) {
Random token = random();
int tokenno = token.nextInt(10);
CharSequence ans = "";
switch(tokenno)
{case 0:ans=getString(R.string.msg0);break;
case 1: ans=getString(R.string.msg1);break;
case 2: ans=getString(R.string.msg2);break;
case 3: ans=getString(R.string.msg3);break;
case 4: ans=getString(R.string.msg4);break;
case 5: ans=getString(R.string.msg5);break;
case 6: ans=getString(R.string.msg6);break;
case 7: ans=getString(R.string.msg7);break;
case 8: ans=getString(R.string.msg8);break;
case 9: ans=getString(R.string.msg9);break;
case 10:ans=getString(R.string.msg10);break;
}
Context context = getApplicationContext();
Toast msg = Toast.makeText(context,ans,Toast.LENGTH_LONG);
msg.show();
}
}//error's popping up here
> Description Resource Path Location Type
Syntax error, insert ";" to complete FieldDeclaration MainActivity.java /8ballv2/src/com/ample/ballv2 line 56 Java Problem
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
Well, I tried your code in IDE and the problem - in provided sample - is in variable declaration:
private OnClickListener answerL = new OnClickListener(){
public void onClick(view v) {
Random token = random();
int tokenno = token.nextInt(10);
CharSequence ans = "";
switch(tokenno) {
case 0:ans=getString(R.string.msg0);break;
case 1: ans=getString(R.string.msg1);break;
case 2: ans=getString(R.string.msg2);break;
case 3: ans=getString(R.string.msg3);break;
case 4: ans=getString(R.string.msg4);break;
case 5: ans=getString(R.string.msg5);break;
case 6: ans=getString(R.string.msg6);break;
case 7: ans=getString(R.string.msg7);break;
case 8: ans=getString(R.string.msg8);break;
case 9: ans=getString(R.string.msg9);break;
case 10:ans=getString(R.string.msg10);break;
}
Context context = getApplicationContext();
Toast msg = Toast.makeText(context,ans,Toast.LENGTH_LONG);
msg.show();
}
}//here should be ';'
It occurs because View.OnClickListener has body with methods. If there were no methods (e.g. you created a
private class MyOnClickListener implements OnClickListener
(http://developer.android.com/reference/android/view/View.OnClickListener.html)
then it would be like that:
private MyOnClickListener answerL = new MyOnClickListener(); //<- semicolon here.
You can avoid such in future using autoformating tool (ctrl+shift+f as default in Eclipse/ADT and ctrl+alt+l (or something like that) in AndroidStudio) or declaring class fields strictly before/after methods.
Hope it helps)
just as it says you need to insert a semicolon there since you are declaring a field here. So this is how it should be
private OnClickListener answerL = new OnclickListener(){
public void onClick(view v) {
...............
}//onClick ends here
}; //OnClickListener ends here
OnclickListener is an interface and you are supposed to create its object like this:
private OnClickListener answerL = new OnclickListener(){
public void onClick(view v) {
//do stuffs here
}
};
Please notice the semi-colon at the end.
I'm trying to make an ImageView, in the Graphical view it shows up but when I run it on my device and the emulator the image doesn't show up. Here's my XML code.
<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" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:scaleType="fitXY"
android:src="#drawable/map_mockup" />
and here's my Fragment1 code (I am using Fragment1 as the Fragment to display this ImageView)
import com.actionbarsherlock.app.SherlockFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import android.app.*;
import android.content.Intent;
public class Fragment1 extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
return rootView;
}
}
I hope this is enough, but if you need more code of the application I'll post it.
This is the first time I'm asking a question on Stack Overflow so if I do something wrong PLEASE tell me so I can correct it, so that in the future my questions layout is correct.
Here's the code for the activity I am adding the fragment to.
import android.app.Activity;
import android.os.Bundle;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.content.res.Configuration;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.support.v4.view.GravityCompat;
public class MainActivity extends SherlockFragmentActivity {
// Declare Variable
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
MenuListAdapter mMenuAdapter;
String[] title;
String[] subtitle;
int[] icon;
Fragment fragment1 = new Fragment1();
Fragment fragment2 = new Fragment2();
Fragment fragment3 = new Fragment3();
Fragment fragment4 = new Fragment4();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_main);
// Generate title
title = new String[] { "Main", "Nick Honegger",
"Discounts", "About" };
// Generate subtitle
subtitle = new String[] { "Check nearby markets", "View your profile",
"Coupons and deals!", "Find out more!" };
// Generate icon
icon = new int[] { R.drawable.action_about, R.drawable.profile_pic,
R.drawable.collections_cloud, R.drawable.action_about };
// Locate DrawerLayout in drawer_main.xml
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// Locate ListView in drawer_main.xml
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// Pass results to MenuListAdapter Class
mMenuAdapter = new MenuListAdapter(this, title, subtitle, icon);
// Set the MenuListAdapter to the ListView
mDrawerList.setAdapter(mMenuAdapter);
// Capture button clicks on side menu
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// Enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
// TODO Auto-generated method stub
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
return super.onOptionsItemSelected(item);
}
// The click listener for ListView in the navigation drawer
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Locate Position
switch (position) {
case 0:
ft.replace(R.id.content_frame, fragment1);
break;
case 1:
ft.replace(R.id.content_frame, fragment2);
break;
case 2:
ft.replace(R.id.content_frame, fragment3);
break;
case 3:
ft.replace(R.id.content_frame, fragment4);
}
ft.commit();
mDrawerList.setItemChecked(position, true);
// Close drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
I've tried using Log.d and it shows that Fragment1 is being loaded. I'm stumped, I don't know what to do and am completely lost right here.
If it matters, the resolution for the PNG is 900x1429.
Two things I can think of.
First, I'm not sure if your layout code shows us the whole file or a snippet. If it's the whole file, you're missing a closing tag on the relativeLayout. If it's a snippet then ignore me.
Second, can you post the code for the Activity that you are adding this Fragment to?
Did you try to add the in the onCreateView instead of the xml?That would be the first thing I'd try.Btw I used the same tutorial as you did and consider yourself lucky,mine doesnt even show the image on my device -.-
Please would you try this:
ft.replace(android.R.id.content, fragment1, "frag1");
instead of
ft.replace(R.id.content_frame, fragment1);
?
If this doesn't change anything, I suggest you use Log.d to confirm that your fragment1 is actually being loaded.
Edit:
Good, then follow Arkan's line or reasoning or place a textview in your xml like this, to determine whether or not the xml is being loaded:
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="if you can see me the problem must be with my image"
/>