Android button having two functions - java

I need to have a button that is suppose to have two functions.
If I tap on it once, it will go to the next page.
If I hold down on the button, it will allow me to edit the text on the button.
The button is able to go to the next page upon tapping on it, but how do I implement the second function which allows me to change the text If I hold down the button?
Does anybody know?
java code
public class MainActivity extends Activity {
Button button1;
Button button2;
Button button3;
Handler h;
private Socket socket;
private boolean mInSettingsMode;
private static final int SERVERPORT = 5000;
private static final String SERVER_IP = "192.168.43.83";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
// living button click start
button1 = (Button) findViewById(R.id.btnliving);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
h = new Handler();
h.postDelayed(irun, 0);
}
});
button2 = (Button) findViewById(R.id.btnbed);
button2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
h = new Handler();
h.postDelayed(irun2, 0);
}
});
button3 = (Button) findViewById(R.id.btndin);
button3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
h = new Handler();
h.postDelayed(irun3, 0);
}
});
}
Runnable irun = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, living.class);
startActivity(i);
finish();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
};
Runnable irun2 = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, bed.class);
startActivity(i);
finish();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
};
Runnable irun3 = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, din.class);
startActivity(i);
finish();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
};
/*
* #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; }
*/
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
// new Thread(new ClientThread()).start();
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
xml code
<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="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical"
android:background="#drawable/back1"
tools:context=".MainActivity" >
<Button
android:id="#+id/btnliving"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Light Control"
/>
<Button
android:id="#+id/btnbed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fan Control"
/>
<Button
android:id="#+id/btndin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Thermostat Control"
/>
</LinearLayout>

You can set second function as a setOnLongClickListener as:
button.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
//change text here
return true;
}
});
and first function is same setOnclickListener as:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
check this Documentation

button.setOnTouchListener(new View.OnTouchListener() {
private static final long MAX_CLICK_TIME = 400;
long time = 0;
#Override
public boolean onTouch(View view, MotionEvent event) {
if (MotionEvent.ACTION_DOWN == event.getAction()) {
time = System.currentTimeMillis();
} else if (MotionEvent.ACTION_UP == event.getAction()) {
long pressingTime = System.currentTimeMillis() - time;
if (pressingTime > MAX_CLICK_TIME) {
// do change text logic
} else {
// show new page logic
}
}
return true;
}
});
If you want to change the text of a button without having to wait until the user removes his finger from the button, you can use TimerTask.Code with TimerTask:
button.setOnTouchListener(new View.OnTouchListener() {
private static final long MAX_CLICK_TIME = 400;
long time = 0;
Timer timer = new Timer();
#Override
public boolean onTouch(View view, MotionEvent event) {
if (MotionEvent.ACTION_DOWN == event.getAction()) {
time = System.currentTimeMillis();
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
// do change text logic
}
};
timer.schedule(timerTask, MAX_CLICK_TIME);
} else if (MotionEvent.ACTION_UP == event.getAction()) {
long pressingTime = System.currentTimeMillis() - time;
if (pressingTime <= MAX_CLICK_TIME) {
timer.cancel();
// show new page logic
}
}
return true;
}
});
I have not tested, but should work. In any case, the idea should be clear.

Related

onBackPressed() finishes my Activity

In my project I have just one Activity that have View.
I think that it has two View that switch the View. The first View is my home that has one Button named "play" . when You click play Button in goes to the second View. Second View is my game.
And now my problem is that when I want to use onBackPressed() method in the second View, it closes the Activity. and onBackPressed() method do the same in both View.
How to handle onBackPressed() method in second View that return to the first View.
How to switch the View in onBackPressed()?
I am new with Android and now I really confused.
any suggestion? or any key word to search to solve my problem.
here is my code:
public class PTPlayer extends Cocos2dxActivity {
static Splash splash;
public static AppList appList;
static Noti_Queue noti_queue;
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v("----------", "onActivityResult: request: " + requestCode + " result: " + resultCode);
if (requestCode == PTServicesBridge.RC_SIGN_IN) {
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (splash == null) {
splash = new Splash(this);
splash.set_identity("1");
}
if (appList == null) {
appList = new AppList(this);
appList.set_identity("1");
}
if (noti_queue == null) {
noti_queue = new Noti_Queue(this);
noti_queue.set_identity("1");
}
}
#Override
public void onNativeInit() {
initBridges();
}
private void initBridges() {
PTStoreBridge.initBridge(this);
PTServicesBridge.initBridge(this, getString(R.string.app_id));
if (PTJniHelper.isAdNetworkActive("kChartboost")) {
PTAdChartboostBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kRevMob")) {
PTAdRevMobBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kAdMob") || PTJniHelper.isAdNetworkActive("kFacebook")) {
PTAdAdMobBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kAppLovin")) {
PTAdAppLovinBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kLeadBolt")) {
PTAdLeadBoltBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kVungle")) {
PTAdVungleBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kPlayhaven")) {
PTAdUpsightBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kMoPub")) {
PTAdMoPubBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kFacebook")) {
PTAdFacebookBridge.initBridge(this);
}
if (PTJniHelper.isAdNetworkActive("kHeyzap")) {
PTAdHeyzapBridge.initBridge(this);
}
}
#Override
public Cocos2dxGLSurfaceView onCreateView() {
Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
glSurfaceView.setEGLConfigChooser(8, 8, 8, 0, 0, 0);
return glSurfaceView;
}
static {
System.loadLibrary("player");
}
#Override
protected void onResume() {
super.onResume();
if (PTJniHelper.isAdNetworkActive("kChartboost")) {
PTAdChartboostBridge.onResume(this);
}
}
#Override
protected void onStart() {
super.onStart();
if (PTJniHelper.isAdNetworkActive("kChartboost")) {
PTAdChartboostBridge.onStart(this);
}
}
#Override
protected void onStop() {
super.onStop();
if (PTJniHelper.isAdNetworkActive("kChartboost")) {
PTAdChartboostBridge.onStop(this);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onBackPressed() {
splash.Display();
splash = null;
super.onBackPressed();
}
}
here i think that in my second view:
public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelperListener {
// ===========================================================
// Constants
// ===========================================================
private static final String TAG = Cocos2dxActivity.class.getSimpleName();
// ===========================================================
// Fields
// ===========================================================
private Cocos2dxGLSurfaceView mGLSurfaceView;
private Cocos2dxHandler mHandler;
private static Context sContext = null;
public static Context getContext() {
return sContext;
}
// ===========================================================
// Constructors
// ===========================================================
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sContext = this;
this.mHandler = new Cocos2dxHandler(this);
this.init();
Cocos2dxHelper.init(this, this);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
#Override
protected void onResume() {
super.onResume();
Cocos2dxHelper.onResume();
this.mGLSurfaceView.onResume();
}
#Override
protected void onPause() {
super.onPause();
Cocos2dxHelper.onPause();
this.mGLSurfaceView.onPause();
}
#Override
public void showDialog(final String pTitle, final String pMessage) {
Message msg = new Message();
msg.what = Cocos2dxHandler.HANDLER_SHOW_DIALOG;
msg.obj = new Cocos2dxHandler.DialogMessage(pTitle, pMessage);
this.mHandler.sendMessage(msg);
}
#Override
public void showEditTextDialog(final String pTitle, final String pContent, final int pInputMode, final int pInputFlag, final int pReturnType, final int pMaxLength) {
Message msg = new Message();
msg.what = Cocos2dxHandler.HANDLER_SHOW_EDITBOX_DIALOG;
msg.obj = new Cocos2dxHandler.EditBoxMessage(pTitle, pContent, pInputMode, pInputFlag, pReturnType, pMaxLength);
this.mHandler.sendMessage(msg);
}
#Override
public void runOnGLThread(final Runnable pRunnable) {
this.mGLSurfaceView.queueEvent(pRunnable);
}
// ===========================================================
// Methods
// ===========================================================
public void init() {
// FrameLayout
ViewGroup.LayoutParams framelayout_params =
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
FrameLayout framelayout = new FrameLayout(this);
framelayout.setLayoutParams(framelayout_params);
// Cocos2dxEditText layout
ViewGroup.LayoutParams edittext_layout_params =
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
this.mGLSurfaceView = this.onCreateView();
// Switch to supported OpenGL (ARGB888) mode on emulator
if (isAndroidEmulator())
this.mGLSurfaceView.setEGLConfigChooser(8 , 8, 8, 8, 16, 0);
this.mGLSurfaceView.setCocos2dxRenderer(new Cocos2dxRenderer());
RelativeLayout relativeLayout = new RelativeLayout(getApplicationContext());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
relativeLayout.setLayoutParams(params);
//AdView adad = new AdView(this);
ClickBanner_CLickYab_Holder adad = new ClickBanner_CLickYab_Holder(this);
RelativeLayout.LayoutParams adad_params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
adad_params.addRule(RelativeLayout.CENTER_HORIZONTAL);
adad_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
// adad.setToken(getString(R.string.adad_token));
adad.setLayoutParams(adad_params);
Button myButton = new Button(this);
myButton.setBackgroundResource(R.drawable.more);
RelativeLayout.LayoutParams adad_params1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adad_params1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
adad_params1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
myButton.setLayoutParams(adad_params1);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PTPlayer.appList.Display();
}
});
Button myButton1 = new Button(this);
myButton1.setBackgroundResource(R.drawable.more);
RelativeLayout.LayoutParams adad_params2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adad_params2.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
adad_params2.addRule(RelativeLayout.ALIGN_PARENT_TOP);
myButton1.setLayoutParams(adad_params2);
myButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PTPlayer.appList.Display();
}
});
relativeLayout.addView(this.mGLSurfaceView);
relativeLayout.addView(adad);
relativeLayout.addView(myButton);
relativeLayout.addView(myButton1);
ClickBanner_CLickYab_Holder.setTestMode();
setContentView(relativeLayout);
}
public Cocos2dxGLSurfaceView onCreateView() {
return new Cocos2dxGLSurfaceView(this);
}
private final static boolean isAndroidEmulator() {
String model = Build.MODEL;
Log.d(TAG, "model=" + model);
String product = Build.PRODUCT;
Log.d(TAG, "product=" + product);
boolean isEmulator = false;
if (product != null) {
isEmulator = product.equals("sdk") || product.contains("_sdk") || product.contains("sdk_");
}
Log.d(TAG, "isEmulator=" + isEmulator);
return isEmulator;
}
}
you must use of Override Method for when back button pressed
if you want to stay on currnt activity use like this
#Override
public void onBackPressed() {
return;
}
if you want to use double click to exit and one click to stay you can use like this
first define a variable for double click
boolean doubleBackToExit = false;
and the Override backbutton method
#Override
public void onBackPressed() {
if (doubleBackToExit) {
//on double back button pressed
return;
}
this.doubleBackToExit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExit=false;
}
}, 2000);
}
Then do this.
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(MainActivityPhase2.this, GlobalSearch.class);
startActivity(intent);
finish();
}
Just don't call the super.onBackPressed() everytime.
#Override
public void onBackPressed() {
if (isFirstView()) {
super.onBackPressed();
} else {
switchToFirstView();
}
Call in only when there isn't any last view available. Or where you want to close the App. The code will finish your activity when you are on the first activity. And switch to first activity if you are on second activity.
Just replace my methods as per your code.
Overriding onBackPressed() of the activity and provide your screen where you want to go.
onBackpressed() check which is the current view you are showing and according to move to the first view.
in your second class Cocos2dxActivity, place this code.
#Override
public void onBackPressed() {
this.finish();
}
If you have just one activity with two View you can use Fragments.
Using Fragments, Activity.OnBackPressed() will remove last fragment in the stack and you can resolve your problem.
So, in the activity you have to put a container in xml layout file:
<FrameLayout android:id="#+id/container" android:layout_width="match_parent"
android:clickable="true" android:layout_height="match_parent"/>
In the Activity java file:
getFragmentManager().beginTransaction()
.add(R.id.container,new YourHomeFragment())
.commit();
So to add second Fragment you can use this code:
getFragmentManager().beginTransaction()
.add(R.id.container,new YourPlayFragment())
.addToBackStack("YourPlayFragment") //string what you want
.commit();
Pay attention: you can call this code or in YourHomeFragment class (into button clickListener) or in your Activity (using a callback system). For example:
In YourHomeFragment -->
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().beginTransaction()
.add(R.id.container,new YourPlayFragment())
.addToBackStack("YourPlayFragment") //string what you want
.commit();
}
});
In this way, you have to declare two layout xml file for fragments and one for Activity.
List of java and relative xml files:
MainActivity.java
activity_main.xml
YourHomeFragment.java
fragment_your_home.xml <-- insert here your first View
YourPlayFragment.java
fragment_your_play.xml <-- play view

OnLongClickListener to lock/unlock Toggle Button operation

I am trying to use a Long-Click listener on a Toggle Button to lock/unlock the normal click action of the button (to avoid accidental clicking). The below code seems to have no effect. I have tried .isActivated, .isCickable and .isEnabled properties without luck... Is it possible?
final ToggleButton btnStartStop = (ToggleButton) findViewById(R.id.toggleAction);
btnStartStop.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
if (btnStartStop.isActivated()) {
btnStartStop.setActivated(false);
} else {
btnStartStop.setActivated(true);
}
return true;
}
});
Maybe use a boolean?
Boolean longPress = false;
final ToggleButton btnStartStop = (ToggleButton) findViewById(R.id.toggleAction);
btnStartStop.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
if (longPress) {
longPress = false;
} else {
longPress = true;
}
return true;
}
});
and onClick():
btnStartStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!longPress){
//Do stuff
}
else{
Toast.makeText(getApplicationContext(), "Button is locked!\nLong press button to unlock it",Toast.LENGTH_SHORT).show();
}
});
You need to change your snippet as
final ToggleButton btnStartStop = (ToggleButton) findViewById(R.id.toggleAction); btnStartStop.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
if (togglePref.isChecked()==(true))
{
// button is checked
}
else
{
// button is unchecked
}
return true;
}
});

Eclipse, new activity on button click

I'm a beginner but I would like to modify an older project.
On the Preferences Activity, there are already few buttons, but I would like to add a new button, which, when clicked, opens a new Activity and shows an image only.
For this I declared this new activity in the Manifest:
<activity
android:name=".VisualHelpActivity"
android:screenOrientation="portrait"
android:theme="#style/AppTheme" >
</activity>
I declared the button on the associated xml layout:
<Button
android:id="#+id/button_visualhelp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="visual_help"
android:text="Visual Help" />
I created the new VisualHelp layout xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/visualhelp_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="#drawable/guide" />
Declared its new VisualHelpActivity java file:
public class VisualHelpActivity extends TranslatableActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visualhelp);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.visual_help, 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);
}
#Override
protected void refreshLanguage() {
}
}
… and now I’m supposed to connect it all together in the "main" PreferencesActivity, which looks as follows:
public class PreferencesActivity extends TranslatableActivity {
public static String url = "https://www.paypal.com/cgi-bin....";
ImageView donate;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_preferences);
donate = (ImageView) findViewById(R.id.button_donate);
donate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
donate(v);
}
});
Spinner s = (Spinner) findViewById(R.id.combo_language);
Lang[] languages = LanguageUtil.Lang.values();
s.setAdapter(new ArrayAdapter<Lang>(this,
android.R.layout.simple_dropdown_item_1line, languages));
s.setSelection(getPosition(languages, LanguageUtil.getLanguage()), true);
}
private int getPosition(Object[] objs, Object item) {
for (int i = 0; i < objs.length; i++) {
if (objs[i] == item)
return i;
}
return -1;
}
public void update(View v) {
Maintenance.downloadDB(this, new onFinishListener() {
#Override
public void onFinish() {
LanguageUtil.loadLanguage(PreferencesActivity.this);
}
});
}
public void copy(View v) {
Maintenance.copyDB(this, new onFinishListener() {
#Override
public void onFinish() {
LanguageUtil.loadLanguage(PreferencesActivity.this);
}
});
}
public void save(View v) {
LanguageUtil.saveLanguage(this,
(Lang) ((Spinner) findViewById(R.id.combo_language))
.getSelectedItem());
LanguageUtil.loadLanguage(this);
setResult(RESULT_OK);
finish();
}
public void donate(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(i);
}
public void cancel(View v) {
finish();
}
#Override
protected void refreshLanguage() {
((Button) findViewById(R.id.button_update)).setText(LanguageUtil
.getDeviceLabel(LanguageUtil.dev_update));
((TextView) findViewById(R.id.language_label))
.setText(LanguageUtil.getDeviceLabel(LanguageUtil.dev_language));
}
}
According to androidbegin.com, I should add this code into the PreferencesActivity java file (code above):
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visualhelp);
button = (Button) findViewById(R.id.button_visualhelp);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(PreferencesAtivity.this,
VisualHelpActivity.class);
startActivity(myIntent);
}
});
}
The only problem is that if I try to add this new public void, multiple marker errors pop up, and if I try to include all below somewhere else, my app fails to work. So, can anyone help me out where and how to include this code part to make it work?
add the code inside oncreate method like this in your PreferencesActivity class:-
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_preferences);
donate = (ImageView) findViewById(R.id.button_donate);
donate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
donate(v);
}
});
button = (Button) findViewById(R.id.button_visualhelp);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(PreferencesAtivity.this,
VisualHelpActivity.class);
startActivity(myIntent);
}
});
Spinner s = (Spinner) findViewById(R.id.combo_language);
Lang[] languages = LanguageUtil.Lang.values();
s.setAdapter(new ArrayAdapter<Lang>(this,
android.R.layout.simple_dropdown_item_1line, languages));
s.setSelection(getPosition(languages, LanguageUtil.getLanguage()), true);
}

How to display 3 2 1 text in the center of the screen in transparency form

I am working on a game.I have an AlertDialog for exit the game but when i press cancle button ao alertDialog my game stop for 3 seconds and resume again. i have implement this code but the text is not visible in center of the screen.
i thing which i want is when i press cancle button 3 2 1 text show on the screen and after display 1 text is invisible and game starts again.
here's my code
public class Game extends Activity {
MediaPlayer backgroungMusic;
Toast toast;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_game);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//turn title off
requestWindowFeature(Window.FEATURE_NO_TITLE);
// set full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(new GamePanel(this));
backgroungMusic = MediaPlayer.create(Game.this, R.raw.music);
backgroungMusic.setLooping(true);
backgroungMusic.start();
}
#Override
protected void onPause()
{
super.onPause();
backgroungMusic.release();
finish();
System.exit(0);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// GamePanel.thread.setStoped(true);
GamePanel.thread.setRunning(false);
// in the next line of code we also style the dialog through xml which i put in styles
AlertDialog alertDialog = new AlertDialog.Builder(this,R.style.myBackgroundStyle).create();
alertDialog.setTitle("Exit Alert");
alertDialog.setMessage("Do you really want to exit the Game?");
alertDialog.setButton("Quit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//Best way is firstly use finish() and after that use System.exit(0) to clear static variables. It will give you some free space.
// A lot of applications leave working processes and variables what makes me angry. After 30 minutes of using memory is full and i have to run Task Manager - Lvl 2 clear memory
finish();
System.exit(0);
return;
}
});
alertDialog.setButton2("Cancle", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// dialog.cancel();
// GamePanel.thread.resume();
// When user press the "Cancle" button then game resume for 3 seconds then start again
// dialog.dismiss();
// Here is the Code of the toasts and each toast appear with delay of one second.
final Handler handler = new Handler();
final TextView textView = (TextView) findViewById(R.id.textView123);
final java.util.concurrent.atomic.AtomicInteger n = new AtomicInteger(3);
final Runnable counter = new Runnable() {
#Override
public void run() {
if(n.getAndDecrement() >= 1 )
handler.postDelayed(this, 1000);
else {
GamePanel.thread.setRunning(true);
}
}
};
handler.postDelayed(counter, 1000);
return;
}
}
);
alertDialog.show();
return true;
}
return super.onKeyDown(keyCode, event);
}
#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_game, 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);
}
}
And here's textview in xml layout.
<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" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".Game">
<TextView
android:id="#+id/textView123"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:paddingRight="10dip"
android:textSize="50dp" />
please help me thanks!
You dont need to do dialog.dismiss();
You also have the problem that final TextView textView = (TextView) findViewById(R.id.textView123); is looking for a view on the dialog rather than on the activity where it lives, are there no erros in your Logcat? You need to be calling textView.setText at some point, but I would expect you to get a NullPointerException
What I would do is use a callback to the activity, it's best to do that by creating a DialogFragment.
public class MyDialogFragment extends DialogFragment {
public MyDialogFragment newInstance() {
MyDialogFragment fragment = new MyDialogFragment();
return fragment;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.myBackgroundStyle);
builder.setTitle("Exit Alert");
builder.setMessage("Do you really want to exit the Game?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
if (getActivity() instanceof DialogClickListener) {
((DialogClickListener) getActivity()).onPositive();
}
}
});
return builder.create();
}
}
public interface DialogClickListener {
void onPositive();
}
public class MyActivity extends Activity implements DialogClickListener {
private TextView textView; //rename this
public void onCreate(...) {
...
textView = (TextView) findViewById(R.id.textView123);
}
public void showExitDialog() {
FragmentManager fm = getSupportFragmentManager();
MyDialogFragment exitDlg = (MyDialogFragment) fm.findFragmetByTag(MyDialogFragment.TAG);
if (exitDlg != null && exitDlg.isAdded()) {
exitDlg.dismiss();
}
exitDlg = MyDialogFragment.newInstance();
exitDlg.show(fm, AddEditDialogFragment.TAG);
}
public void onPositive() {
final Handler handler = new Handler();
final java.util.concurrent.atomic.AtomicInteger n = new AtomicInteger(3);
final Runnable counter = new Runnable() {
#Override
public void run() {
if (n.getAndDecrement() >= 1 ) {
handler.postDelayed(this, 1000);
} else {
GamePanel.thread.setRunning(true);
}
textView.setText(String.valueOf(n));
}
};
handler.postDelayed(counter, 1000);
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
showExitDialog()
}
}
}
In a RelativeLayout you can use centerInParent:
<TextView
android:id="#+id/textView123"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:paddingRight="10dip"
android:textSize="50dp" />

Moving between Activities

I have couple of activities. On the mainActivity I have 4 buttons each leads to another activity.
On three of the activities I activate a thread which draws in a canvas and in each of them I have a button to return to the mainActivity. I have tried using:
Intent i = new Intent(getApplicationContext(), MainActivity.class);
// i tried also (theClassName.this,MainActivity.Class)
startActivity(i);
When I clicked on the return button, I did return to the mainActivity but the app stopped responding (it alerted me that the app isn't responding and I had to choose between waiting or exiting the app. Waiting doesn't help).
When I used
finish();
instead,
And clicked on the return button, I returned to the home screen of the device (went out of the app) but didn't exit it - I could still go back to the app using the task manager, and when I did it put me back in the activity I entered and not the mainActivity.
As I said I have 4 buttons on the mainActivity and when I use the fourth one it goes to another activity that doesn't activate a thread, it only has listView, and when I return from it to the mainActivity it does work.
How can I fix it? Thanks for the help
*when the problem occurs there is no error stack trace.
*if you need to see any code tell and I'll be happy to post it here
The code:
MainActivity:
public class MainActivity extends Activity {
Button classic;
Button vsPlayer;
Button vsComp;
// Button settings;
Button scores;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
classic=(Button) findViewById(R.id.Classic);
classic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,ClassicActivity.class);
startActivity(i);
}
});
vsPlayer=(Button) findViewById(R.id.PlayerVSPlayer);
vsPlayer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,VsPlayerActivity.class);
startActivity(i);
}
});
vsComp=(Button) findViewById(R.id.PlayerVSComp);
vsComp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,VsCompActivity.class);
startActivity(i);
}
});
/* settings=(Button) findViewById(R.id.Settings);
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,SettingsActivity.class);
startActivity(i);
}
});
*/
scores=(Button) findViewById(R.id.Scores);
scores.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,ScoresActivity.class);
startActivity(i);
}
});
}//onCreate
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mains, menu);
return true;
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
MainActivity.this.finish();
}
}
-=------ some other activity:
public class ClassicActivity extends Activity {
Classic g;
ImageView left;
ImageView right;
ImageView up;
ImageView down;
TextView pause;
TextView back;
TextView scoretv;
LinearLayout surface;
LinearLayout screen;
LinearLayout stoped;
LinearLayout gameover;
ScoreDataSource sds;
Button no;
Button yes;
EditText name;
Button continueb;
Button leave;
//protected static TextView MyScore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*requestWindowFeature(Window.FEATURE_NO_TITLE);
v= new GameView1(this);
setContentView(v);
*/
setContentView(R.layout.activity_classic);
sds=new ScoreDataSource(this);
gameover=(LinearLayout) findViewById(R.id.gameover);
screen = (LinearLayout)findViewById(R.id.screen);
surface = (LinearLayout)findViewById(R.id.surface);
g= new Classic(this, surface);
surface.addView(g);
//MyScore=(TextView) findViewById(R.id.MyScore);
//MyScore.setText("My score:"+gv.getPoints());
left=(ImageView) findViewById(R.id.left);
right=(ImageView) findViewById(R.id.right);
up=(ImageView) findViewById(R.id.up);
down=(ImageView) findViewById(R.id.down);
left.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(g.snake.getDir()!="LEFT"&&g.snake.getDir()!="RIGHT"){
g.snake.Left();
}
}
});
right.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(g.snake.getDir()!="RIGHT"&&g.snake.getDir()!="LEFT"){
g.snake.Right();
}
}
});
up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(g.snake.getDir()!="UP"&&g.snake.getDir()!="DOWN"){
g.snake.Up();
}
}
});
down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(g.snake.getDir()!="DOWN"&&g.snake.getDir()!="UP"){
g.snake.Down();
}
}
});
pause=(TextView) findViewById(R.id.Pause);
back=(TextView) findViewById(R.id.Back);
stoped=(LinearLayout) findViewById(R.id.stoped);
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(g.getRunning()){
pause.setText("continue");
g.setRunning(false);
}
else{
pause.setText("pause");
g.setRunning(true);
new Thread(g.snakethread).start();
}
}
});
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
g.setRunning(false);
stoped.setVisibility(View.VISIBLE);
}
});
no=(Button) findViewById(R.id.no);
yes=(Button) findViewById(R.id.yes);
continueb=(Button) findViewById(R.id.Continue);
leave=(Button) findViewById(R.id.leave);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
name=(EditText) findViewById(R.id.name);
yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String date = df.format(c.getTime());
sds.open();
Score s=new Score(0,name.getText().toString(),date, g.getPoints(),"Classic");
s=sds.createScore(s);
sds.close();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
continueb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stoped.setVisibility(View.GONE);
g.setRunning(true);
new Thread(g.snakethread).start();
}
});
leave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
scoretv=(TextView) findViewById(R.id.scoretv);
screen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(g.getGameover()){
scoretv.setText("Your score is:"+g.getPoints());
gameover.setVisibility(View.VISIBLE);
g.setGameover(false);
}
}
});
}
#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;
}
}
----ClassicActivity usus this activity:
public class Classic extends SurfaceView implements Runnable {
private boolean isRunning=false;
private final long FPS=8;//MAX is 16
final float scale = Resources.getSystem().getDisplayMetrics().density;
float PART_SIZE= 10*scale;
private SurfaceHolder holder;
Thread snakethread;
static SnakePlayer snake;
Arena a;
LinearLayout view;
Bitmap arena;
Food food1;
Boolean gameover;
int points;
Paint writePB=new Paint();
Paint writePR=new Paint();
public Classic(Context context,LinearLayout view) {
super(context);
this.gameover=false;
this.view=view;
this.a=new Arena(view,PART_SIZE,33,36,1,0);
this.food1=new Food(PART_SIZE,"GRAY");
points=0;
writePB.setColor(Color.BLACK);
writePB.setTextSize(PART_SIZE);
writePR.setColor(Color.RED);
writePR.setTextSize(PART_SIZE);
snakethread=new Thread(this);
holder= getHolder();
holder.addCallback(new SurfaceHolder.Callback(){
#Override
public void surfaceCreated(SurfaceHolder arg0) {
setRunning(true);
snakethread.start();
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2,int arg3) {
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
setRunning(false);
while(true){
try {
snakethread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
snake=new SnakePlayer(0+3*PART_SIZE, 0+3*PART_SIZE, "RIGHT",PART_SIZE,2,"RED","BLACK");
}
#SuppressLint("WrongCall")
#Override
public void onDraw(Canvas c) {
a.onDraw(c);
c.drawText("Your Score:"+points, 5*scale, 10*scale, writePB);
food1.drawFood(c);
snake.onDraw(c);
}
#SuppressLint("WrongCall")
#Override
public void run() {
long stepPerSecond=1000/FPS;
long startTime;
long sleepTime;
Canvas c = null;
while(isRunning){
startTime=System.currentTimeMillis();
c = null;
try{
c=this.getHolder().lockCanvas();
onDraw(c);
}
catch(Exception e){
}
finally{
if(c!=null){
this.getHolder().unlockCanvasAndPost(c);
}
}
AllChecks(c);
sleepTime= stepPerSecond-(System.currentTimeMillis()-startTime);
if(sleepTime>0)
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(gameover){
try{
c=this.getHolder().lockCanvas();
c.drawText("GAMEOVER", 125*scale, 150*scale, writePR);
c.drawText("Touch Anywhere To Continue ", 87*scale, 162*scale, writePR);
}
catch(Exception e){
}
finally{
if(c!=null){
this.getHolder().unlockCanvasAndPost(c);
}
}
}
}
boolean firstTime=true;
public void AllChecks(Canvas c){
/*
* Call all the right function, to check if the snake has bumped in a wall, or eaten a food.
*/
if(Arena.WallCollision(snake.getxLoc(), snake.getyLoc())){
setRunning(false);
gameover=true;
}
if(snake.snakeCollisionNoHead(snake.getxLoc(), snake.getyLoc())){
setRunning(false);
gameover=true;
}
if(firstTime){
firstTime=false;
changeFoodLoc(food1);
}
if(food1.hasEaten(snake.getxLoc(), snake.getyLoc())){
changeFoodLoc(food1);
snake.Add();
points+=10;
}
}
public void changeFoodLoc(Food food){
/*
* if a snake has eaten a food it changes the location of the food randomly
*/
Random rnd = new Random();
food.x=(rnd.nextInt(32) + 3)*food.SIZE;
food.y=(rnd.nextInt(35) + 1)*food.SIZE;
if(snake.snakeCollision(food.getX(), food.getY()))
changeFoodLoc(food);
}
public void setRunning(boolean b){
isRunning=b;
}
public Boolean getRunning(){
return isRunning;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public Boolean getGameover() {
return gameover;
}
public void setGameover(Boolean gameover) {
this.gameover = gameover;
}
}
First I would try removing the override on the MainActivity for onPause - you do not need to call finish. In your second activity, if you want to go back to the MainActivity- call finish on the 2nd activity and it should go back to the MainActivity.

Categories