.Override method of different class - android

Calling onBackPressed method of Activity class on a View Class? is it possible? and so how can I? thanks for help
UPDATE: I just created the GameView of my Game which is extends to View Class. I create a variable that increments whenever I finish every level so it will limit a levels per game. And so I want to implement a onBackPressed method which I can set the incrementing variable back to zero whenever the player press the back key.
FULL CODE: MAIN ACTIVITY
public class MainActivity extends Activity {
private GameView mGameView;
#Override
public void onBackPressed() {
if (mGameView.interceptBackPressed()) {
return;
}
// TODO Auto-generated method stub
super.onBackPressed();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
mGameView = (GameView) findViewById(GameView.countmaze);
Afterwards it goes to Menu Class
public class menu extends Activity implements OnClickListener {
static int nextmaze;
int countmaze = 0;
GameView gameView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnplay = (Button) findViewById(R.id.btnPlay);
btnplay.setOnClickListener(this);
}
#Override
public void onBackPressed() {
//I have here an AlertDialog builder
}
#Override
public void onClick(View v) {
case R.id.btnPlay:
Toast.makeText(getApplicationContext(), "LEVEL 1",
Toast.LENGTH_SHORT).show();
startnextmaze();
}
}
void startnextmaze() {
Random rand = new Random();
Intent game = new Intent(menu.this, Game.class);
nextmaze = rand.nextInt(5) + 1;
Maze maze = MazeCreator.getMaze(nextmaze);
game.putExtra("maze", maze);
startActivity(game);
}
Then on my GameView Class
public class GameView extends View {
static int countmaze;
//Big codes here......
public boolean interceptBackPressed() {
// TODO Auto-generated method stub
countmaze = 0;
return true;
}
}

Create a callback on the Activity onBackPressed that the View class will implement
Example
public void interface onBackPressedHandler {
public void onBackPressed();
}
Activity Class
public onBackPressedHandler mHandler;
#Override
public void onCreate(....) {
GameView game... //Inflate or create.
game.setActivity(this);
}
public void setListener(onBackPressedHandler handler) {
mHandler = handler;
}
#Override
public voind onBackPressed() {
if(mHandler != null) {
mHandler.onBackPressed();
}
super.onBackPressed();
View Class
public GameView extends View implements onBackPressedHandler {
public void setActivity(Activity activity) {
activity.setListener(this);
}
public void onBackPressed() {
//your code here.
}
}
This example shows when you press the back Button it will call the onBackPress on the View.
Hope it Helps.

Update your code with the following changes:
Activity
public class MyActivity extends Activity {
private GameView mGameView;
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.main);
//View reference to object defined in XML
mGameView = (GameView) findViewById(R.id.gameview);//id must be specified in XML
//I assumed that GameView is a part of your XML layout
//View created programmatically.
mGameView = new GameView(this);
//Use one of the above initialisation techniques of mGameView.
}
#Override
public void onBackPressed() {
//here we are calling method on mGameView which cannot be null
//that's why we initialised it in onCreate() method
if (mGameView.interceptBackPressed()) {
return;
}
super.onBackPressed();//finish your Activity
}
}
GameView
public class GameView extends View {
public boolean interceptBackPressed() {
//TODO handle your game logic here and return true if you don't
//want your game to be shutdown, otherwise return false
return true;
}
}

Related

Android: How to finish an activity by an ImageView which belongs to the activity in an another class

I want to finish an activity by an image, and here is what I did:
there's an ImageView in the layout [activity_login.xml] .
/**
* the activity that I want to destroy
*/
public class LoginActivity extends Activity {
public static LoginActivity activityInstance;
private ImageView imgBtnBack;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// for closing this activity by an another class
activityInstance = this;
// add event listener
imgBtnBack = (ImageView) findViewById(R.id.img_btn_back);
imgBtnBack.setOnClickListener(new LoginActivityListener());
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
/**
* the event handler of LoginActivity
*/
public class LoginActivityListener implements View.OnClickListener{
private Context context;
#Override
public void onClick(View view) {
context = view.getContext();
int id = view.getId();
switch (id) {
case R.id.img_btn_back: // close the activity by an image
LoginActivity.activityInstance.finish();
default:
break;
}
}
}
And I don't know if it was good by the way I did.
can anyone find and tell me a better way to make this work.
Add below code in your onCreate method
imgBtnBack = (ImageView) findViewById(R.id.img_btn_back);
imgBtnBack .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});

Restarting activity inside onClick method

I have an app which reads .txt file and displays contents in table layout.
here is my MainActivity.java file:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new TableLayout(this,0));
}
}
Inside TableLayout class when adding first row (headers), i also add on click listeners.
Here is the code that gets executed when click happens:
public class MyOnClickListener extends MainActivity implements OnClickListener {
int rowNumber;
public MyOnClickListener(int rowNumber) {
this.rowNumber = rowNumber;
}
#Override
public void onClick(View v) {
setContentView(new TableLayout(context,rowNumber));
}
};
context is saved from when activity is first started, but i get nullpointexception error with this as an argument.
What i would like to do when header is clicked is to recreate table with header number argument.
So my question is what should i do to restart table creation within onClick method?
Edit: this is how context is saved
Context context;
public TableLayout(Context context, int rowNr) {
super(context);
this.context = context;
I would probably do something like this
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new TableLayout(this, getRowNumber()));
}
protected int getRowNumber(){
return 0;
}
}
and then you do something like
public class MyOnClickListener extends MainActivity implements OnClickListener {
// here you initialize rowNumber
static int rowNumber = 0;
#Override
protected void getRowNumber(){
return rowNumber;
}
#Override
public void onClick(View v) {
// here you set your rowNumber
rowNumber = some_value;
recreate();
}
};
P.S: I haven't compiled this but you can get the idea

android inheritance activity(Base - Main activity)

I am having a problem about implemeting android apps.
I made baseActivity which is that base of other applications and other applications.
These are my code.
First, BaseActivity.java
public class BaseActivity extends Activity {
protected void onCreate(Bundle savedInstanceState,int layoutId) {
super.onCreate(savedInstanceState);
setContentView(layoutId);
Button menuBtn = (Button)findViewById(R.id.menuBtn);
menuBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("bss","menu");
}
});
}
}
And the other one is MainActivity.java
public class MainActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState,R.layout.activity_main);
setContentView(R.layout.activity_main);
}
}
Now I have a question! When I was click the menu button, click listener did not act. It did not print log message and any action. So, I have a problem to make my application. Is it related with life-cycle or How can I solve the problem.
I do not like the way you are forcing thing, still if you want to make it works this way you have remove setContentView(R.layout.activity_main); from MainActivity, that's because one you call again setContentView(R.layout.activity_main); in the sublcass, the view hierarchy for that Activity will be recreated invalidating what you have done in the super class
The code is setting the Content View twice. Following is the sequence of your code.
setContentView()
Add button listener
setContentView()
Statement # 2, adds the button listener and it is all good till now. But as soon as you reset the content view on statement # 3, the previous settings get void. And the button gets reinitialized and the onClickListener is no more attached to the button.
Remove the contentview from BaseActivity and put
Button menuBtn = (Button)findViewById(R.id.menuBtn);
menuBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("bss","menu");
}
});
into MainActivity. The Base activity should be SuperClass and MainActivity subclass all the actions for view shold be initialize into the subclass.
Try this :
public class BaseActivity extends Activity {
protected void onCreate(Bundle savedInstanceState,int layoutId) {
super.onCreate(savedInstanceState);
}
public int getLayoutXML() {
return -1;
}
public abstract int getMenuId();
}
After this use this BaseActivity class like this :
public class service_detail extends BaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Use button like this:
Button menuBtn = (Button)findViewById(R.id.menuBtn);
menuBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("bss","menu");
}
});
}
#Override
public int getMenuId() {
// TODO Auto-generated method stub
return 1;
}
#Override
public int getLayoutXML() {
// TODO Auto-generated method stub
return R.layout.service_detail;
}
}

how to send data in both directions using an interface between Activity and Fragment

i made an interface in the fragment class kind of like a listener to send a string from the Fragment to the Activity. what is the best way to also send strings in the opposite direction? from activity to fragment? so there is now an interface in the fragment, so do i have to make another interface in the Activity to send strings in the other direction, or is there a better way?
the fragment class:
public class FragmentHeadless extends Activity implements FragmentHeadlessFragment.OnTimeRequestedListener {
FragmentTransaction transaction;
Button button;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_headless);
button = (Button) findViewById(R.id.button1);
textView = (TextView) findViewById(R.id.textView1);
FragmentManager fragmentManager = getFragmentManager();
transaction = fragmentManager.beginTransaction();
transaction.add(new FragmentHeadlessFragment(), "processorFragment");
transaction.commit();
}
#Override
public void passString(String stringFromFragment) {
textView.setText(stringFromFragment);
Toast.makeText(this, "String passed from fragment " + stringFromFragment, Toast.LENGTH_SHORT).show();
}
}
the activity class
public class FragmentHeadlessFragment extends Fragment {
private OnTimeRequestedListener listener;
String tempString = "";
Activity activity;
Handler handler;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
handler = new Handler();
new Thread(){
public void run() {
SystemClock.sleep(3000);
handler.post(new Runnable() {
#Override
public void run() {
// pass string to activity
passData("test string from fragment with 3 second delay");
}
});
} // end run
}.start();
} // end onCreate
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof OnTimeRequestedListener) {
listener = (OnTimeRequestedListener) activity;
} else {
throw new ClassCastException(activity.toString()
+ " must implemenet OnTimeRequestedListener");
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
activity = getActivity();
setRetainInstance(true);
}
public interface OnTimeRequestedListener {
public void passString(String timeNumberString);
}
public void passData(String data) {
listener.passString(data);
}
}
since you have an instance to the fragment, you can just call the function you need via the activitiy:
instead of :
transaction.add(new FragmentHeadlessFragment(), "processorFragment");
use:
private FragmentHeadlessFragment mFragment;
...
mFragment=new FragmentHeadlessFragment();
transaction.add(mFragment, "processorFragment");
and when you wish, call:
mFragment.foo(myInt,myString,...) ;
btw, why do you have a field for the transaction?

How can I pass the method from ac Activity to OnClickListener

Hello I have 2 classes for a Memory Game:
One is the NV1 who have the method, for exampe:
public class Nv1 extends Activity{
protected int cardsUp;
protected int currentIndex = -1;
protected int lastIndex = -1;
protected int cardEquals = 0;
protected int lifes = 3;
protected TextView lifes_txt;
protected Handler handler;
protected int [] imgIds = {
R.id.img_1,
R.id.img_2,
R.id.img_3,
R.id.img_4,
};
An another class NVListener that implements OnClickListener.
public class CardsListener implements OnClickListener{
#Override
public void onClick(View v) {
------------
I need to call the method from my Activity to CardsListener. How could I do that?
Method A : Make the listener abstract, implement the abstract method onClick in the Activity
(recommended, listener can be reused easily, easier to debug)
Example:
In SampleActivity.java
public class SampleActivity extends Activity {
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Your code here.....
// findViewById()..... etc.
b.setOnClickListener(new SomeListener(){
#Override
public void onClick(View v) {
someMethod();
}
});
}
public void someMethod(){
Log.d("Log Tag","Some Message");
}
}
In SomeListener.Java
//make it abstract
public abstract class SomeListener implements OnClickListener{
//put your own method,variables inside
//do not override onClick()
}
Method B : Create a constructor with the Activity as a input parameter. Save the activity instance and call its method freely (less recommended : not flexible, and not logical IMO)
In SomeListener.Java
public class SomeListener implements OnClickListener {
private SampleActivity mAct;
public SomeListener(SampleActivity act){
mAct = act;
}
#Override
public void onClick(View v) {
mAct.someMethod();
}
}

Categories

Resources