java - Android: Implementing a Back Button from a class -
okay, here problem. i'm working on android app , learning android @ same time, of times errors. normaly can fix them after researching bit, i'm getting stuck in point.
i'm trying make button every activity in app, thought making "backbutton" class, can instanciate every time want to. here backbutton code:
import android.content.intent; import android.view.view; import android.widget.button; import android.app.activity; public class backbutton extends activity implements view.onclicklistener{ public static button backbutton; // defining button public backbutton() { backbutton = (button) findviewbyid(r.id.bback); backbutton.setonclicklistener(this); } //to button public static button getbackbutton() { return backbutton; } // onclicklistener public void onclick(view v) { try { class mainactivityclass = class.forname("eu.lafarga.treballderecerca.mainactivity"); intent mainactivityintent = new intent(backbutton.this, mainactivityclass); startactivity(mainactivityintent); } catch (classnotfoundexception e) { e.printstacktrace(); }finally { // save things we've done. } } }
so, how should implement in activity? i'm doind wrong? (sure i'm lol)
personally, suggest not doing this. think overriding button in each activity
safer, more flexible, , easy, if not easier. chances are, aren't going want return mainactivity
app grows because won't expected action users when hit button. override button in activities
need , run code
@overrride public void onbackpressed(view v) { // save data first intent mainactivityintent = new intent(currentactivityname.this, mainactivityclass); startactivity(mainactivityintent); super.onbackpressed(); }
you can use flags such flag_activity_clear_top
if want remove activities
between current 1 , target activity
(here mainactivity
) calling setflags(intent.flag_activity_clear_top)
Comments
Post a Comment