I've created an Activity with a Navigation Drawer and replaced the options icon (placed in the top-right corner) with an ImageButton to handle the back click.
The problem is, that I don't know how to do it. I'm a little confused about how to use the back button. What code should I do to go to the previous Activity?
A back button for:
Activity to Another Activity and MainActivity to Fragment activity.
this is my Manifest code:
<activity
android:name="com.teamamazing.with_sidebar.activity.Accomodation"
android:label="Accomodation"
android:parentActivityName="com.teamamazing.with_sidebar.activity.SpecialPage">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.teamamazing.with_sidebar.activity.SpecialPage" />
</activity>
this is my Accommodation activity:
package com.teamamazing.with_sidebar.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.teamamazing.with_sidebar.R;
public class Accomodation extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accomodation);
} }
and this is my SpecialPage code: which will be the parent activity.
package com.teamamazing.with_sidebar.activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import com.teamamazing.with_sidebar.R;
public class SpecialPage extends AppCompatActivity {
public ImageButton accomodation;
public void init() {
accomodation = (ImageButton) findViewById(R.id.AccomodationButton);
accomodation.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent accomodation = new Intent(SpecialPage.this, Accomodation.class);
startActivity(accomodation);
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_special_page);
init();
}}
Thank you for the answer.
You can use onBackPressed() or finish() Method.
buttonClickOBJ.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onBackPressed();
}
});
onBackPressed ()
Called when the activity has detected the user's press of the back
key. The default implementation simply finishes the current activity,
but you can override this to do whatever you want.
You can also use the following method.
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
Easy way
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.app_name);
builder.setIcon(R.mipmap.ic_launcher);
builder.setMessage("If You Enjoy The App Please Rate us?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent play =
new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=kd.travellingtips"));
startActivity(play);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
Firstly, Add the Listener to the button you want to associate with it. Then initiate a back-press option within the method.
Related
So I created a pop-up dialog window to serve as the tutorial for the user, I decided to run tests on it since it was working well but saw that when you added an active button to it, it would not work. Each time I pressed the button that brings up the tutorial(which worked before the addition of the button code), the addition I made with the button taking the user to another part now renders that button inactive and instead takes the user back to the start screen when the tutorial button is pressed.
This is the code I used for it:
package com.example.rockpaperscissors;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import static com.example.rockpaperscissors.R.id.tutorialButton;
public class MainMenu extends AppCompatActivity {
Button tutorialButton, playGameButton, testbutton;
Dialog tutorial_popup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tutorial_popup = new Dialog(this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
setContentView(R.layout.activity_main_menu);
playGameButton = findViewById(R.id.playGameButton);
tutorialButton = findViewById(R.id.tutorialButton);
testbutton = findViewById(R.id.testbutton);
tutorial_popup = new Dialog(this);
playGameButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainMenu.this, MainGame.class));
}
});
tutorialButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tutorial_popup.setContentView(R.layout.tutorial_popup);
tutorial_popup.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
tutorial_popup.show();
testbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainMenu.this, MainGame.class));
}
});
}
});
}
}
As you can see, there's another setOnClickListener within the tutorial which is basically supposed to take the user to another class/activity when pressed on. However, it does not do it and instead just ignores it, showing that there is an error.
tutorialButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tutorial_popup.setContentView(R.layout.tutorial_popup);
tutorial_popup.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
tutorial_popup.show();
testbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainMenu.this, MainGame.class));
}
});
}
});
Is there something I missed when doing this? Please let me know how I can fix this.
Try setting the onclick on the button before showing the pop up
testbutton.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) {startActivity(new Intent(MainMenu.this, MainGame.class));}}); tutorial_popup.show();
So I found a solution to this answer, being that there was actually no need to add a buttonListener to the pop-up dialog as not only was it unnecessary, but it was also breaking the code. With how pop-up dialogs work in Android Studio, I realised through watching videos that you are able to click off of it without needing an "X" button or whatsoever, so I removed the buttonListener and tried again. Safe to say it ran perfectly this time with no problems whatsoever.
tutorialButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tutorial_popup.setContentView(R.layout.tutorial_popup);
tutorial_popup.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
tutorial_popup.show();
}
});
I'm using a fragment because I used a nav drawer menu. After I click "Category" menu it will take me to "Category" fragment and in that fragment, I have added a floating action bar that will take you to "Add category" activity.
Since fragments can't be viewed in AndroidManifest.xml file, I can't make a fragment as a parent. What I want is to add a "Back Button" from "Add category" activity, display a toast message (If sure to leave without saving changes..etc) and will go back to "Category" fragment.
I have tried using "onBackPressed()" and "getSuppoerActionBar()" that will show a toast but when running the app, the toast message will just show up in a few seconds and will go back to "Category" fragment.
Please help. Thanks!
Here is my code.
CategoriesFragment.java
package com.example.devcash;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class CategoriesFragment extends Fragment {
public CategoriesFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_categories, container, false);
//add floating action button
FloatingActionButton categories_fab = view.findViewById(R.id.addcategories_fab);
categories_fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// when add fab is pressed, go to add product activity
Intent addprod = new Intent(getActivity(), AddCategoryActivity.class);
startActivity(addprod);
}
});
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Categories");
}
}
AddCategoryActivity.java
package com.example.devcash;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
public class AddCategoryActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_category);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Unsaved changes");
builder.setMessage("Are you sure you want to leave without saving changes?");
builder.setPositiveButton("LEAVE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
AddCategoryActivity.super.onBackPressed();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.show();
super.onBackPressed();
}
}
You need to remove below code from onBackPressed() as it is calling super class method and eventually destroying activity.
super.onBackPressed();
To handle toolbar back add following code
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// todo: goto back activity from here
onBackPressed();
default:
return super.onOptionsItemSelected(item);
}
}
Your AddCategoryActivity should be like this
public class AddCategoryActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_category);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onBackPressed() {
quitActivity();
}
private void quitActivity() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Unsaved changes");
builder.setMessage("Are you sure you want to leave without saving changes?");
builder.setPositiveButton("LEAVE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
quitActivity();
return true;
} else
return super.onOptionsItemSelected(item);
}
}
you can use EventBus.
class Activity{
fun backToFragment(){
EventBus.postEvent(BackToFragmentEvent())
}
}
class HomeActivity{
EventBus.register{
fragmentmanager.replace(CategoriesFragment)
}
}
There are two activities in my app. I want to perform a simple function. In Second Activity, If button is clicked it should hide and go back to First Activity And If I click the button in First Activity the Second Activity should be open with hidden button. I've achieved this by below code.
But the problem is. I can't close (call onDestroy())the app when I press back button while I'm in First Activity. The back button performs switch between two activities.
First Activity Java:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class first extends AppCompatActivity {
Button btn1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(first.this, second.class);
startActivity(intent);
}
});
}
public void onBackPressed() {
super.onBackPressed();
}
}
Second Activity Java:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class second extends AppCompatActivity {
Button btn2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
onBackPressed();
btn2 = (Button) findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btn2.setVisibility(View.GONE);
Intent intent = new Intent(second.this, first.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
});
}
public void onBackPressed() {
intent = new Intent(second.this, first.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
}
How can I call OnDestroy() in this Condition?
The reason is you override onBackPressed() in the second activity. So that means everytime you press the back button on your second activity, it will create a new first activity instead return to the old one. The app will stuck in this loop. Try to remove onBackPressed method on second activity or call finish() in it.
Call finish() from the back pressed event. Override the backpressed event so you can customise it.
#Override
public void onBackPressed() {
finish();
//super.onBackPressed();
}
}
You can use this onBackPress() method like this in first activity
#Override
public void onBackPressed() {
//super.onBackPressed();
finish();
}
OR
you can just delete onBackPress() because you don't have to override it.
I am having issue with my app, my app loads however when I click on "options" button it stops working and quits the app.
Can someone help me?
first code is from options.java class and second code is from mainactivity
package com.example.sportsquizzone;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
/**
* Created by Usman on 22/02/2016.
*/
public class options extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
}
public void onButtonClick(View view) {
Intent b = new Intent(this, MainActivity.class);
b.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(b);
}
public void btnAbout(View view) {
AlertDialog.Builder About = new AlertDialog.Builder(this);
About.setMessage("* Developed by Usman Saddique \n* Developed on \n* This game runs on Android version 4.2 and above")
.setPositiveButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setTitle("About")
.setIcon(R.drawable.question_mark)
.create();
About.show();
}
}
package com.example.sportsquizzone;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#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;
}
public void onButtonClick(View v)
{
if(v.getId() == R.id.btnPlay)
{
Intent i = new Intent(MainActivity.this, level.class);
startActivity(i);
}
if(v.getId() == R.id.btnOptions)
{
Intent i = new Intent(MainActivity.this, option.class);
startActivity(i);
}
}
#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);
}
public void Instructions(View view) {
final AlertDialog.Builder Instructions = new AlertDialog.Builder(this);
Instructions.setMessage("The SQZ is designed to test your knowledge across variety of sports, to play: \n1. Click Play \n2. Select Dificulty \n3. when quiz begins, four answers will be provided select the correct one. ")
.setPositiveButton("Got It", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setTitle("Instructions")
.setIcon(R.drawable.question_mark)
.create();
Instructions.show();
}
public void btnQuit(View view) {
new AlertDialog.Builder(this)
.setIcon(R.drawable.warning)
.setTitle("Closing Application")
.setMessage("Are you sure you want to Quit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
I can not see the your logcat error but I think you have created the "option" class and its layout separately. So if it is what you have done , probably you have forgotten to declare the activity on manifest:
include it on your manifest:
I was just trying showing a DialogFragment object from an on click inside a button listener.
Here is the code of the activity that should start the Dialog:
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerToButton1();
}
private void addListenerToButton1(){
final Context context = this;
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
DP ciao = new DP();
ciao.show(this,"MyDP");
}
});
}
}
And here's the code of the Dialog:
public class DP extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Prova")
.setPositiveButton("POS", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("NEG", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
return builder.create();
}
}
Errors are:
The method show(FragmentManager, String) in the type DialogFragment is not applicable for the arguments (MainActivity, String)
The method show(FragmentManager, String) in the type DialogFragment is not applicable for the arguments (new View.OnClickListener(){}, String)
Any advice?
Show DialogFragment from Activity by passing FragmentManager instance for interacting with fragments associated with current activity as instead of by passing Activity or Button Context:
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
DialogFragment ciao = DP.newInstance();
ciao.show(MainActivity.this.getFragmentManager(),"MyDP");
}
});
and you will also need to add following newInstance() method in DP DialogFragment which return you DialogFragment instance :
public static DP newInstance() {
DP frag = new DP();
return frag;
}
Try this method of passing the correct context into your DialogFragment
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
DP ciao = new DP();
ciao.show(view.getContext(),"MyDP");
}
});
In your original code, when calling
'ciao.show(this,"MyDP");'
the this refers to its parent class which is OnClickListener.
When assigning a click listener and overriding the onClick, you get passed the view and an argument which you can use to access information from, including the context.
Extend your fragment (DP) from the android.app.DialogFragment
you can access FragmentManager from within Activity by getFragmentManager()
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
DP ciao = new DP();
ciao.show(getFragmentManager(),"MyDP");
}
});
Hopefully this works :)