Using a button as a boolean switch - android-layout

I'm trying to make a button in android function as a boolean switch. I want it to do something on the first click and do something else on the second click. On the third click, I want it to do the same thing on the first click et cetera. The main reason I want this due to the text element on the button that changes with each click. Switches and checkboxes have no texts to change.
I've tried finding documentations on doing this online but can't seem to find any previous examples of doing this. Would appreciate if anyone has any ideas or just tell me outright that this is not workable.

yourButton
.setOnClickListener(new View.OnClickListener() {
private boolean state = false;
public void onClick(View v) {
if ( state ) {
state = false;
yourButton.setText("False");
} else {
state = true;
yourButton.setText("True");
}
}
});
You can try something like this, by the way i DIDN'T test this code i'm just trying to show you a way you could try to do it

1. set button to change drawable background and remove
button.setOnClickListener ( new View.OnClickListener () {
private boolean state=false;
#Override
public void onClick(View v) {
if (state){
state=false;
textView.setBackground ( getDrawable(R.drawable.led_mode ) );
}
else{
state=true;
textview.setbackground(null);
}
}
});

Related

How to Scroll pdfView automatically with button click or volume buttons

I'm using barteksc pdf viewer library to load pdf in my application.
pdfView = findViewById(R.id.pdfView);
pdfView.fromAsset(getResources().getString(R.string.pdfname))
.enableDoubletap(true)
.enableSwipe(true)
.defaultPage(pageNumber)
.onPageChange(mainreading.this)
.pageFitPolicy(FitPolicy.WIDTH)
.pageFling(true)
.linkHandler(null)
.enableAnnotationRendering(true)
.swipeHorizontal(true)
.scrollHandle(new DefaultScrollHandlenew(mainreading.this))
.enableAntialiasing(true)
.load();
}
I want pdf to start scroll automatically when user click the button of volume up and down buttons to start stop. I tried with below code while wrapping it in the handler with handler.performClick(); but it shows blank screen while scrolling up and down.
scrollbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pdfView.scrollTo(0, pdfView.getScrollY() + 24);
}
});
Example :
https://play.google.com/store/apps/details?id=com.emptysheet.pdfreader_autoscroll&hl=en&gl=US
I want to make as like this. Can anyone help please.
Also tried with this. But it shows blank page after some scrolls.
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
if (action == KeyEvent.ACTION_DOWN) {
pdfView.scrollTo(0, pdfView.getScrollY() -24);
}
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (action == KeyEvent.ACTION_DOWN) {
pdfView.scrollTo(0, pdfView.getScrollY() + 24);
}
return true;
default:
return super.dispatchKeyEvent(event);
}
}
You can simply use this PDF viewer from github.
It's based on the same 'barsteksc' pdf viewer with the feature to jump to any pages.
It's MagicalPdfViewer and you can use 'jumpTo(pageNo)' method to simply jump to the specific page. It also gives you the option to animate to the specific page with the same method, just pass 'true' as the 2nd parameter.
Moreover, if you pass the values like '-1' and 'bigger than pageNo', It will automatically scroll to the 0 & last page respectively.
Give it a try & let me know if you got what you wanted.

Why does my RotateTransition throw errors after it runs for the first time?

Warning: This is my first time using threads and my first time trying out an animation. Please bear with me.
I want to rotate an ImageView. I set up a thread for it:
public class ThreadAnimation extends Thread
{
private ImageView iv;
private RotateTransition rt;
public ThreadAnimation(ImageView iv)
{
this.iv = iv;
}
#Override
public void run()
{
while (true)
{
RotateTransition r = new RotateTransition();
r.setToAngle(360);
r.setCycleCount(1);
r.setDuration(Duration.millis(300));
r.setNode(iv);
r.play();
try
{
sleep(100);
} catch (InterruptedException e)
{
return;
}
}
}
}
I call this inside my controller class, upon pressing a Button.
animation.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle (ActionEvent abschicken)
{
ThreadAnimation thread = null; //ANIMATION PIZZA
if (thread == null)
{
thread = new ThreadAnimation(olivenview);
thread.start();
}
}
});
My ImageView olivenview will rotate just like I wanted it to. However it takes quite a long time until it seems to stop (I can see it because the button triggering it still looks triggered for a while) and when I go ahead to press it a second time afterwards, I get a nonstop error stream with a lot of null pointer exceptions. I am very clueless, can anyone help me out? Is this due to my Thread Setup or does the problem lie somewhere else (in code that I didn't post here)?
I believe you do not need threads for this. Notice the .play() method returns immediately and the animation will run in the background.
That being said, try this.
...
//Create your rotation
final RotateTransition r = new RotateTransition();
r.setToAngle(360);
r.setCycleCount(1);
r.setDuration(Duration.millis(300));
r.setNode(iv);
//When the button is pressed play the rotation. Try experimenting with .playFromStart() instead of .play()
button.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent action) {
r.play();
}
});
...
On an other note I recommend switching to java 8 so that you can use lambda expressions instead of the anonymous class!

Intellij Idea Live Template to create field and method at same time

How to create field variable automatically when I create method used that field. I've create template like this:
void $METHOD_NAME$() {
$FIELD_NAME$ = true;
}
when I type field name (e.g. mState) in method will create field as:
private boolean mState = false;
Hope someone help. Sorry my bad.
Given the screenshot of your template, you can also create a field with the following live template:
private boolean $param$ = false;
#Override
public void onBackPressed() {
if ($param$) super.onBackPressed();
android.widget.Toast.makeText(this, "$message$",
android.widget.Toast.LENGTH_SHORT).show();
$param$ = true;
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
$param$ = false;
}
}, 100);
}
Where $param$ and $message$ are regular variables without anything special.
However, like I said in the comment on your question, I suggest to split it up in several smaller templates.
Consider to split it up in:
field + method with just:
private boolean $param$ = false;
#Override
public void onBackPressed() {
if ($param$) super.onBackPressed();
$param$ = true;
}
Then create a template for the message:
android.widget.Toast.makeText(this, "$message$", android.widget.Toast.LENGTH_SHORT).show();
And last but not least, create a template for the postDelayed:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
$END$
}
}, $delay$);
Note: the $delay$ as a bonus you can even give it a default value or create a list of predefined values for ease of use.
Note2: Instead of $param$ = false; I've replaced it with $END$. This will position your cursor here once you've selected the delay. Now you can type mState = false manually here, or whatever code you need in the context at that moment. This makes the template much more flexible and easier to use.
PS. I suppose you want to call super.onBackPressed() only when the value is false (on the first invocation). In that case use if (!$param$) instead.
// Update:
In order to group the newly added field with the other fields and not halfway somewhere in your class between other methods, rearrange the code
via the menu with: Code -> rearrange code.
To customise this, check your arrangement settings under: settings -> code style -> <language> -> arrangement

Android - Back button behavior

I have a project with 2 activities, the first one is the "SplashActivity" - where I load some network data - the second one, the MainActivity.
Inside of my MainActivity I have a fragment and inside of this fragment a webview. My first point is, when the user clicks on back button, the SplashScreen is open again.
The back button should behave like:
When the user doesn't navigate inside of my webview, close the app.
When the user navigates in webview, use the back history of the browswer.
I read about back stack here: http://developer.android.com/training/implementing-navigation/temporal.html#back-webviews
I didn't understand at all how it should work, because I have all cases "mixed". Anyone knows what should I do to fix this problem?
Any idea or sample code will be appreciate!
Define Webview wb as a global variable. Then try this;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(wb.canGoBack() == true){
wb.goBack();
}else{
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Application will be closed")
.setMessage("Close app?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
System.exit(0);
}
}).setNegativeButton("No", null).show();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}

Is it possible to forbid selection in TextField?

I have a small problem: my text field keeps selecting itself, for example if I alt-tab from and to application.
For my application, text selection is not needed and will not be used - so I want to disallow this annoying behavior. Actually, just setting selection color to transparent or white will work fine.
Is there some way to do this?
The following css fixed the problem for me:
-fx-highlight-fill: null;
-fx-highlight-text-fill: null;
You can disable text selection for key events:
myTextField.addEventFilter(KeyEvent.KEY_TYPED, new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent inputevent) {
if (!myTextField.getSelectedText().isEmpty()) {
myTextField.deselect();
}
}
});
For mouse events you could also use:
myTextField.addEventFilter(MouseEvent.MOUSE_DRAGGED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (!myTextField.getSelectedText().isEmpty()) {
myTextField.deselect();
}
}
});
Super late for an answer, but I have a better solution.
Instead of disabling the style for selected text or managing mouse events, it's better to directly manage the selectedTextProperty().
The advantages of this solution are:
The selection properties will always be empty selection
Double clicks are also covered, not only mouse drag events
The code...
textField.selectedTextProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue.isEmpty()) textField.deselect();
});

Resources