I am struggling to get the Navigation drawer items to register and start and intent for a new activity. The drawer opens fine and is displayed correctly but nothing happens when I click on the items in the list. Here is my code
package radiofm.arabel;
import android.app.ProgressDialog;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
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.widget.Button;
import android.widget.ImageButton;
import static android.widget.AbsListView.OnScrollListener.SCROLL_STATE_IDLE;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
ImageButton id_play,id_pause;
private Button btn;
private boolean playPause;
private MediaPlayer mediaPlayer;
private ProgressDialog progressDialog;
private boolean initialStage = true;
FragmentTransaction fragmentTransaction;
NavigationView navigationView;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Log.d("myTag", "This is my toolbar");
id_play = (ImageButton) findViewById(R.id.id_play);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
progressDialog = new ProgressDialog(this);
id_play.setEnabled(true);
id_play.setImageResource(R.drawable.play);
id_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!playPause) {
id_play.setImageResource(R.drawable.pause);
if (initialStage) {
Log.d("myTag", "This is my excute");
new Player().execute("http://arabelfm.ice.infomaniak.ch/arabelprodcastfm.mp3");
} else {
Log.d("myTag", "This is my beforestart");
if (!mediaPlayer.isPlaying())
Log.d("myTag", "This is my afterstart");
mediaPlayer.start();
}
playPause = true;
} else {
id_play.setImageResource(R.drawable.play);
Log.d("myTag", "This is my beforestop");
if (mediaPlayer.isPlaying()) {
Log.d("myTag", "This is afterstop");
mediaPlayer.reset();
}
playPause = false;
}
}
});
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);
}
#Override
protected void onPause() {
super.onPause();
if (mediaPlayer != null) {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}
}
class Player extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... strings) {
Boolean prepared = false;
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
Log.d("myTag", "This is my listnner");
initialStage = true;
playPause = false;
id_play.setImageResource(R.drawable.play);
mediaPlayer.stop();
mediaPlayer.reset();
}
});
mediaPlayer.prepare();
prepared = true;
} catch (Exception e) {
// Log.e("MyAudioStreamingApp", e.getMessage());
prepared = false;
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if (progressDialog.isShowing()) {
progressDialog.cancel();
}
mediaPlayer.start();
initialStage = true;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setMessage("Buffering...");
//progressDialog.show();
}
}
#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.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) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void displaySelectedScreen(int id)
{
Fragment fragment=null;
Log.d("myTag", "This is my displ");
switch (id){
case R.id.nav_alarm:
fragment = new Add_Alarm();
break;
}
if (fragment !=null)
{
FragmentTransaction ft =getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_main,fragment);
ft.commit();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment = null;
if (id == R.id.nav_alarm) {
Intent goToNextActivity = new Intent(getApplicationContext(), Main2Activity.class);
startActivity(goToNextActivity);
}
FragmentTransaction ft =getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_main,fragment);
ft.addToBackStack(null);
ft.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
try change your code inside onNavigationItemSelected to this:
switch (item.getItemId()){
case R.id.nav_alarm:
//do stuff
Intent goToNextActivity = new Intent(getApplicationContext(), Main2Activity.class);
startActivity(goToNextActivity);
break;
}
FragmentTransaction ft =getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_main,fragment);
ft.addToBackStack(null);
ft.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
You should check your onNavigationItemSelected(MenuItem item) method because while replacing the fragment you initailized you fragment null like Fragment fragment = null; .So, for replace the fragment you need to take actual fragment instead of null fragmnet.
You may go through about the fragments here.
`
Change the flow of the code as below:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
item.setCheckable(false);
Fragment fragment=null;
switch (item.getItemId()) {
case R.id.navigation_home:
fragment = new HomeFragment();
break
}
loadHomeFragment(fragment);
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
}
private void loadHomeFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment);
fragmentTransaction.commitAllowingStateLoss();
}
Related
When I m using shared preference class as a separated class, I'm going to check the user already login or not in the navigation activity class, if it is first time then it transfer me in the login activity otherwise continue in the navigation activity
But my problem is that when I'm going to backPressed on login activity it should close the app but it transfer me in the navigation activity....pls help me...
package com.apkglobal.no_dues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
public class Shared {
SharedPreferences sp;
SharedPreferences.Editor ed;
String Filename="himanshu";
int mode=0;
Context context;
String First="first";
public Shared(Context context) {
this.context = context;
sp=context.getSharedPreferences(Filename,mode);
ed=sp.edit();
}
public void secondtime()
{
ed.putBoolean(First,true);
ed.commit();
}
public boolean firsttime()
{
if(!this.isfirst())
{
Intent i=new Intent(context,LoginActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
return false;
}
public boolean isfirst() {
return sp.getBoolean(First,false);
}
public void getback()
{
ed.putBoolean(First,false);
ed.commit();
}
}
Navigationacitivity.class
package com.apkglobal.no_dues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.support.design.widget.NavigationView;
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.widget.Button;
import android.widget.TextView;
import com.apkglobal.no_dues.Fragment.AboutFragment;
import com.apkglobal.no_dues.Fragment.BookDetailsFragment;
import com.apkglobal.no_dues.Fragment.FeedbackFragment;
import com.apkglobal.no_dues.Fragment.HomeFragment;
import com.apkglobal.no_dues.Fragment.MarksFragment;
import com.apkglobal.no_dues.Fragment.NoDuesFormFragment;
public class NavigationActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
Button btn_mis,btn_attendence;
Shared shared;
String rollno;
SharedPreferences sp;
SharedPreferences.Editor ed;
NavigationView navigationView;
TextView tv_rollno;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
shared = new Shared(getApplicationContext());
shared.firsttime();
setContentView(R.layout.activity_navigation);
btn_attendence = (Button) findViewById(R.id.btn_attendence);
btn_mis=(Button)findViewById(R.id.btn_mis);
tv_rollno = (TextView)findViewById(R.id.tv_rollno);
navigationView = (NavigationView) findViewById(R.id.nav_view);
View header=navigationView.getHeaderView(0);
tv_rollno = (TextView)header.findViewById(R.id.tv_rollno);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
sp=getSharedPreferences("rajput",MODE_PRIVATE);
rollno=sp.getString("rollno",null);
tv_rollno.setText(rollno);
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.setNavigationItemSelectedListener(this);
defaultSelectitem(R.id.nav_homepage);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
else {
AlertDialog.Builder ab = new AlertDialog.Builder(NavigationActivity.this);
ab.setIcon(R.drawable.logo);
ab.setTitle("Exit Application");
ab.setMessage("Are You Sure ?");
ab.setCancelable(false);
ab.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
ab.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ab.create();
ab.show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.navigation, 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) {
Intent i = new Intent(getApplicationContext(), SettingActivity.class);
startActivity(i);
} else if (id == R.id.action_contact) {
Intent i = new Intent(getApplicationContext(), ContactActivity.class);
startActivity(i);
} else if (id == R.id.action_search) {
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
defaultSelectitem(item.getItemId());
return true;
}
private void defaultSelectitem(int itemId) {
Fragment fragment = null;
switch (itemId) {
case R.id.nav_homepage:
fragment = new HomeFragment();
break;
case R.id.nav_nodues_form:
fragment = new NoDuesFormFragment();
break;
case R.id.nav_feedback:
fragment = new FeedbackFragment();
break;
case R.id.nav_marks:
fragment = new MarksFragment();
break;
case R.id.nav_book:
fragment = new BookDetailsFragment();
break;
case R.id.nav_about:
fragment = new AboutFragment();
break;
case R.id.nav_fees_detail:
Intent intent = new Intent(NavigationActivity.this,FeesDetail.class);
startActivity(intent);
break;
case R.id.nav_share:
break;
case R.id.nav_logout:
shared.getback();
Intent i = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(i);
finish();
break;
}
if (fragment != null) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction().replace(R.id.frame, fragment);
fragmentTransaction.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
}
You have to take Activity as a param instead of context. Then after starting the activity, you should finish the current activity.
Your code should be like this.
package com.apkglobal.no_dues;
import android.content.Intent;
import android.content.SharedPreferences;
public class Shared {
SharedPreferences sp;
SharedPreferences.Editor ed;
String Filename="himanshu";
int mode=0;
Activity activity;
String First="first";
public Shared(Activity activity) {
this.activity= context;
sp=activity.getSharedPreferences(Filename,mode);
ed=sp.edit();
}
public void secondtime()
{
ed.putBoolean(First,true);
ed.commit();
}
public boolean firsttime()
{
if(!this.isfirst())
{
Intent i=new Intent(activity,LoginActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(i);
activity.finish();
}
return false;
}
public boolean isfirst() {
return sp.getBoolean(First,false);
}
public void getback()
{
ed.putBoolean(First,false);
ed.commit();
}
}
Hope it helps:)
Add android:noHistory=true in your Manifest.xml for LoginActivity. With that the Login Activity will not be on the backstack.
Just add finish() to finish current activity :
if(!this.isfirst()){
Intent i=new Intent(context,LoginActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
finish()
}
use NavigationActivity.this instead of getApplicationContext()
shared = new Shared(NavigationActivity.this);
shared.firsttime();
and call finish(); method after startActivity();
Good afternoon,
I was following a tutorial to create a drawer menu for Android.
As programmed, came to me the need for when I go into a Fragment Class, wanted on the menu when you press on the Home, back to the Home (MainActivity) and not for another class.
I leave here my code of this project.
MainActivity.java
package pt.projects.bpn.menudrawerproject;
import android.content.res.Configuration;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
mDrawer.addDrawerListener(drawerToggle);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
setupDrawerContent(nvDrawer);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
}
private void setupDrawerContent(NavigationView nvDrawer) {
nvDrawer.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener(){
#Override
public boolean onNavigationItemSelected(MenuItem menuItem){
selectDrawerItem(menuItem);
return true;
}
});
}
private void selectDrawerItem(MenuItem menuItem) {
Fragment fragment = null;
Class fragmentClass;
switch (menuItem.getItemId()){
case R.id.nav_home_fragment:
fragmentClass = null;
break;
case R.id.nav_first_fragment:
fragmentClass = FirstFragment.class;
break;
case R.id.nav_second_fragment:
fragmentClass = SecondFragment.class;
break;
case R.id.nav_third_fragment:
fragmentClass = ThirdFragment.class;
break;
default:
fragmentClass = FirstFragment.class;
}
if(fragmentClass != null) {
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
else {
FragmentManager fragmentManager = getSupportFragmentManager();
for(int i = 0; i < fragmentManager.getFragments().size(); ++i) {
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
}
Can you please clarify me how i can do that?
EDIT
I update the code for the tips from the comments bellow.
Now, the graphic layout take no changes.
I am developing an application where i have to display a navigation drawer in home page.I am using NavigationView where i will point which menu it should populate.Now what problem i am facing is, its displaying items twice.Below code will show you what i have done so far
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
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.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.mylaw.rkme3.mylawproject.fragments.HomeFragment;
import com.mylaw.rkme3.mylawproject.fragments.VideoHomeFragment;
import com.mylaw.rkme3.mylawproject.interfaces.FragmentInterface;
import com.mylaw.rkme3.mylawproject.utils.Constants;
/**
* Created by Lincy on 7/4/2016.
**/
public class MainActivity extends AppCompatActivity implements FragmentInterface {
private static final String TAG = "MainActivity";
private Toolbar mToolBar;
private DrawerLayout mDrawerLayout;
private NavigationView mNavigationView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
displayScreens();
}
private void initView() {
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
mToolBar = (Toolbar) findViewById(R.id.toolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
setUpNavigationDrawer();
mNavigationView.inflateMenu(R.menu.drawer);
}
private void setUpNavigationDrawer() {
setSupportActionBar(mToolBar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout, mToolBar,
R.string.openDrawer,
R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
if (item.isChecked())
item.setChecked(false);
else item.setChecked(true);
mDrawerLayout.closeDrawers();
switch (item.getItemId()) {
case R.id.sub_item_in_progress:
goToInProgress();
return true;
case R.id.sub_item_completed:
goToCompleted();
return true;
case R.id.sub_lapsed:
goToLapsed();
return true;
default:
Toast.makeText(getApplicationContext(), "Somethings Wrong", Toast.LENGTH_SHORT).show();
return true;
}
}
});
}
private void goToLapsed() {
Intent courseLapsedIntent = new Intent(MainActivity.this, CourseProgressActivity.class);
Bundle extras = new Bundle();
extras.putString(Constants.BundleParameters.FRAGMENT_NAME, "Lapsed");
courseLapsedIntent.putExtras(extras);
startActivity(courseLapsedIntent);
}
private void goToCompleted() {
Intent courseCompletedIntent = new Intent(MainActivity.this, CourseProgressActivity.class);
Bundle extras = new Bundle();
extras.putString(Constants.BundleParameters.FRAGMENT_NAME, "Completed");
courseCompletedIntent.putExtras(extras);
startActivity(courseCompletedIntent);
}
private void goToInProgress() {
Intent courseProgressIntent = new Intent(MainActivity.this, CourseProgressActivity.class);
Bundle extras = new Bundle();
extras.putString(Constants.BundleParameters.FRAGMENT_NAME, "InProgress");
courseProgressIntent.putExtras(extras);
startActivity(courseProgressIntent);
}
private void displayScreens() {
this.action(Constants.FragmentInterfaceConstants.ACTION_HOME, null);
}
#Override
public void action(int tag, Bundle args) {
switch (tag) {
case Constants.FragmentInterfaceConstants.ACTION_HOME:
handleHomeScreen();
break;
case Constants.FragmentInterfaceConstants.ACTION_VIDEO_HOME:
handleVideoHomeScreen();
break;
default:
break;
}
}
#Override
public void showActionBar(boolean show) {
}
#Override
public void showHomeButton(boolean show) {
}
#Override
public void setActionBarTitle(String title) {
}
private void handleHomeScreen() {
HomeFragment homeFragment = new HomeFragment();
addFragment(homeFragment, HomeFragment.TAG);
}
private void handleVideoHomeScreen() {
VideoHomeFragment videoHomeFragment = new VideoHomeFragment();
addFragment(videoHomeFragment, HomeFragment.TAG);
}
private void addFragment(Fragment fragment, String tag) {
FragmentTransaction ft =
getSupportFragmentManager()
.beginTransaction();
ft.replace(R.id.mainFrame, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(tag);
ft.commitAllowingStateLoss();
}
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
finish();
}else {
getSupportFragmentManager().popBackStack();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_Register:
Intent registerIntent = new Intent(MainActivity.this, TransparentActionBarActivity.class);
Bundle extras = new Bundle();
extras.putString("fragName", "Register");
registerIntent.putExtras(extras);
startActivity(registerIntent);
break;
case R.id.item_search:
Intent searchIntent = new Intent(MainActivity.this, TransparentActionBarActivity.class);
Bundle searchExtras = new Bundle();
searchExtras.putString("fragName", "Search");
searchIntent.putExtras(searchExtras);
startActivity(searchIntent);
break;
case R.id.item_login:
Intent loginIntent = new Intent(MainActivity.this, TransparentActionBarActivity.class);
Bundle loginExtras = new Bundle();
loginExtras.putString("fragName", "Login");
loginIntent.putExtras(loginExtras);
startActivity(loginIntent);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
I am pretty new to the Google Maps API v2 and would like to integrate a map available via this base link: https://tiles.guildwars2.com/{continent_id}/{floor}/{zoom}/{x}/{y}.jpg. My problem is, well everything, but let's get started with the following:
1) How can I set the map sizes that there is no grey space at any side?
2) How can I move the map correctly because I have obviously 4 parameters while I can change only 3 at a time with getTileUrl?
3) Why are the tiles mixed and not shown in their correct order?
The map documentation is available here:
http://wiki.guildwars2.com/wiki/API:2/maps
http://wiki.guildwars2.com/wiki/API:Maps
Working example link: 0.jpg
My current code is:
import android.content.Intent;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
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 android.widget.TextView;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.*;
import java.net.MalformedURLException;
import java.net.URL;
public class mapsContainer extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback {
SupportMapFragment mapFragment;
private DrawerLayout drawer;
private Toolbar toolbar;
private ActionBarDrawerToggle toggle;
private NavigationView navigationView;
private GoogleMap mMap;
private TileOverlay mSelectedTileOverlay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mapFragment = SupportMapFragment.newInstance();
setContentView(R.layout.activity_maps_container);
toolbar = (Toolbar) findViewById(R.id.toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
setSupportActionBar(toolbar);
toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
/**
* Called when a drawer has settled in a completely closed state.
*/
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/**
* Called when a drawer has settled in a completely open state.
*/
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
drawer.addDrawerListener(toggle);
navigationView.setNavigationItemSelectedListener(this);
ConnectivityManager connMgr = (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
View navHeader = navigationView.getHeaderView(0);
if (networkInfo != null && networkInfo.isConnected()) {
TextView connectionStatus = (TextView) navHeader.findViewById(R.id.connection_status);
connectionStatus.setText(R.string.common_online);
} else {
TextView connectionStatus = (TextView) navHeader.findViewById(R.id.connection_status);
connectionStatus.setText(R.string.common_offline);
}
toggle.syncState();
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.mapsFragement, mapFragment).commit();
mapFragment.getMapAsync(this);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
toggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
toggle.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
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.main, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = drawer.isDrawerOpen(GravityCompat.START);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.syncProfile) {
//String res = gwApiAccess.apiQueryAuthorized("https://api.guildwars2.com/v2/account/dyes");
//Log.d(DEBUG_TAG,"res: " + res);
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else if (id == R.id.nav_profile) {
Intent intent = new Intent(this, profile.class);
startActivity(intent);
} else if (id == R.id.nav_itemDB) {
Intent intent = new Intent(this, items.class);
startActivity(intent);
} else if (id == R.id.nav_guilds) {
Intent intent = new Intent(this, guilds.class);
startActivity(intent);
} else if (id == R.id.nav_maps) {
//Do nothing
} else if (id == R.id.settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NONE);
CustomUrlTileProvider mTileProvider = new CustomUrlTileProvider(256, 256, "https://tiles.guildwars2.com/{continent_id}/{floor}/{zoom}/{x}/{y}.jpg");
mSelectedTileOverlay = mMap.addTileOverlay(new TileOverlayOptions().tileProvider(mTileProvider).zIndex(-1));
mMap.getUiSettings().setTiltGesturesEnabled(false);
mMap.getUiSettings().setRotateGesturesEnabled(false);
}
private static class CustomUrlTileProvider extends UrlTileProvider {
private String baseUrl;
CustomUrlTileProvider(int width, int height, String url) {
super(width, height);
this.baseUrl = url;
}
#Override
public URL getTileUrl(int zoom, int x, int y) {
try {
return new URL(baseUrl.replace("{continent_id}", "" + 1).replace("{floor}", "" + 0).replace("{zoom}", "" + zoom).replace("{x}", "" + x).replace("{y}", "" + y));
} catch (MalformedURLException e) {
e.printStackTrace();
}
return null;
}
private boolean checkTileExists(int x, int y, int zoom) {
int minZoom = 0;
int maxZoom = 0;
return !(zoom < minZoom || zoom > maxZoom);
}
}
}
Ok, after having a looooong break because of school I figured everything out except the first thing.
My fault with the wrong tiles was that I did not have the correct order of params.
The other thing with the to much params, I will program myself a workaround in the near future.
So I will close the thread and open a new one just before I smash the display because sth doesn't work.
I want to call another fragment from the current fragment on the click of the button in the current fragment.
Here is my Mainactivity :
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
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 com.asd.fragments.RecommendationsFragment;
import com.asd.ibitz4college.fragments.SearchCoachingFragment;
import com.asd.fragments.SearchCollegesFragment;
import com.asd.fragments.MainFragment;
import com.asd.fragments.SearchConsultanciesFragment;
import com.asd.fragments.TrendingFragment;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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);
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame,new MainFragment()).commit();
}
#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.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) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame,new MainFragment()).commit();
if (id == R.id.search_colleges) {
// Handle the Search Colleges action
fm.beginTransaction().replace(R.id.content_frame,new SearchCollegesFragment()).commit();
}
else if (id == R.id.search_consultancies) {
fm.beginTransaction().replace(R.id.content_frame,new SearchConsultanciesFragment()).commit();
}
else if (id == R.id.search_coaching) {
fm.beginTransaction().replace(R.id.content_frame,new SearchCoachingFragment()).commit();
}
else if (id == R.id.my_recommendations) {
fm.beginTransaction().replace(R.id.content_frame, new RecommendationsFragment()).commit();
}
else if (id == R.id.trending) {
fm.beginTransaction().replace(R.id.content_frame, new TrendingFragment()).commit();
} else if (id == R.id.profile) {
} else if (id == R.id.logout) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Here is one of my fragment :
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.asd.k4c.R;
public class SearchCoachingFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.fragment_search_coaching,container,false);
return rootview;
}
} //Update code formatting
Suppose I want to call resultsfragment from the above fragment on the click
of a button whose id is btn_search, then what should I do?
I tried some already existing answers here, no luck!
P.S: I'm a starter to the world of android dev.
For doing a fragment transaction.Please do the following.
Eg..
A and B are fragments.
Currently A is visible to the User. If you want to do a transaction.
Just create as like below
B b = new B();
((YourActivity)getActivity).setnewFragment(b,true);
public void setNewFragment(Fragment fragment,boolean addbackstack) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_content, fragment);
if (addbackstack)
transaction.addToBackStack(title);
transaction.commit();
}
Use an interface to communicate between fragments. For example
public YourFirstFragment extends Fragment {
public interface FragmentCallBack {
void callBack();
}
private FragmentCallBack fragmentCallBack;
public void setFragmentCallBack(FragmentCallBack fragmentCallBack) {
this.fragmentCallBack = fragmentCallBack;
}
private void callThisWhenYouWantToCallTheOtherFragment(){
fragmentCallBack.callBack();
}
}
Then in You activity
private void setCallToFragment{
yourFirstFragment.setFragmentCallBack(new FragmentCallBack(){
void callBack(){
yourSecondFragment.doWhatEver();
}})
}
First you need to create an interface which defines methods that will be used by your fragment to invoke code from the respective activity it is attached to
public interface OnFragmentInteractionlistener {
// the method that you call from your fragment,
// add whatever parameter you need in the implementation of this
// method.
void onClickOfMyView();
}
once you have created the interface, implement it any and all activities that use this fragment.
public class MainActivity extends AppCompatActivity
implements OnMyFragmentInteractionListener {
#Override
public void onClickOfMyView() {
// DO your on click logic here, like starting the transaction
// to add/replace another fragment.
}
}
Then in the onAttach of your fragment to an activity be sure to check if the attaching activity implements this interface, else throw a RunTimeException like so
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnMyFragmentInteractionListener) {
mListener = (OnMyFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnMyFragmentInteractionListener");
}
}
Here mListener is a interface reference you hold in your fragment class through which you invoke the onClickOfMyView() method when actually the click happens
Your fragment class where the view's click code is there.
myView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
mListener.onClickOfMyview();
}
});
You should create some method in your activity. Supposedly it will look like this :
public void startFragment(Fragment fragment) {
fm.beginTransaction().replace(R.id.content_frame,new fragment).commit();
}
As you already done in youronNavigationItemSelected
Then, from your fragment, you can call
((MainActivity)getActivity()).startFragment(new SearchConsultanciesFragment())
for example
Create a method switchFragment in your MainActivity
FragmentTransaction ft;
public void switchFrag() {
try {
ft = getActivity().getFragmentManager().beginTransaction();
ft.replace(R.id.frame_container, new Your_Fragment.class);
ft.commit();
} else {
Log.e("test", "else part fragment ");
}
} catch (Exception e) {
e.printStackTrace();
}
}
Now from your current Fragment you can call this MainActivity's funciton throught the below code:
((MainActivity)getActivity()).switchFrag();
Let me know if this works for you! :)