I've created a method that is called when my EditText is clicked (or touched, to be specific), which simply takes the current time and displays it exactly as it has been passed by System.currentTimeMillis() in a TextView below. The method is this one:
public void captureTime(View view) {
currentTime = System.currentTimeMillis();
String currentTimeStr = currentTime+ "";
TextView textView = findViewById(R.id.textView);
textView.setText(currentTimeStr);
}
To do that, I've had to add the code below in the onCreate method. It uses setOnTouchListener instead of setOnClickListener since otherwise the captureTime method wasn't always called. Now, this method does what I wanted, but now when I click or touch the EditText, although it does this as required, the keyboard doesn't show up anymore. I have looked into other questions in which the keyboard doesn't show up either but they're not related to my case, although I have tried them. So, what is that is making the keyboard not show up and how can I fix this?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add_time = (EditText)findViewById(R.id.editText);
add_time.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP) {
captureTime(add_time);
return true;
}
return false;
}
});
}
Try removing return true (in the if block). In this case, the "captureTime" method will work and the keyboard will open.
Related
At first my main problem was at how to call a method from the same class, even tough I think I found a way to do this, it's not working as I expected, and I would like to know what would be the best approach to my case.
This is the code I'm working on:
public class EscolhaAtendimento extends AppCompatActivity {
private ViewPager mSlideViewPager;
private LinearLayout mDotLayout;
String TAG = "TasksSample";
private TextView[] mDots;
private SliderAdapter sliderAdapter;
Dialog myDialog;
#Override
public void onCreate (Bundle SavedInstanceState){
super.onCreate(SavedInstanceState);
setContentView(R.layout.escolha_atendimento);
mSlideViewPager = findViewById(R.id.slideViewPager);
mDotLayout = findViewById(R.id.dotsLayout);
sliderAdapter = new SliderAdapter(this);
mSlideViewPager.setAdapter(sliderAdapter);
addDotsIndicator(0);
mSlideViewPager.addOnPageChangeListener(viewListener);
myDialog = new Dialog(this);
}
public void addDotsIndicator(int position){
mDots = new TextView[8];
mDotLayout.removeAllViews();
for (int i= 0; i < mDots.length; i++){
mDots[i] = new TextView(this);
mDots[i].setText(Html.fromHtml("•"));
mDots[i].setTextSize(35);
mDots[i].setTextColor(getResources().getColor(R.color.colorTransparentWhite));
mDotLayout.addView(mDots[i]);
}
if (mDots.length > 0){
mDots[position].setTextColor(getResources().getColor(R.color.colorWhite));
}
}
ViewPager.OnPageChangeListener viewListener = new ViewPager.OnPageChangeListener(){
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected (int i) {
switch (i) {
case 0: {
myDialog.show();
}
addDotsIndicator(i);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
public void ShowPopup(View v) {
TextView txtclose;
//Button btnFollow;
myDialog.setContentView(R.layout.pop_upfinal);
txtclose = myDialog.findViewById(R.id.txtclose);
txtclose.setText("X");
//btnFollow = (Button) myDialog.findViewById(R.id.btnfollow);
txtclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myDialog.dismiss();
}
});
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
myDialog.show();
}
}
This class is an activity that on user swipe, the text and image from the buttons will change, even though their IDs will stay the same. (That's controlled by another class, it's working well).
Now, I wanted the image button on the activity do something different depending on which page is selected, and that's why there is a initial switch on the onPageSelected method, inside the Page change listener. The image button in the layout has the android:onClick="ShowPopup" tag, and I guess that also complicates things for me, if I wanted it to do something different in that same activity? Also, calling it that way on the switch, every time I change pages, and go back to the first one the popup window will open, since my call is explicit there. (As I said, even tough I found a way to somehow call my method, or at least it's result, it's not working as I expected).
Edit
I tried then changing it like this, so that the button wouldn't rely on the android:onClick="ShowPopup" Tag, and also wouldn't need to call a void method directly on the switch:
Added
public ImageButton popupchoice;
And also this to onCreate method:
popupchoice = this.findViewById(R.id.imgslide1);
Inside the switch I called it like this to get the button ID:
popupchoice.setOnClickListener(image1);
And set the View.OnClickListener like this:
View.OnClickListener image1 = new View.OnClickListener() {
public void onClick(View v) {
TextView txtclose;
//Button btnFollow;
myDialog.setContentView(R.layout.pop_upfinal);
txtclose = myDialog.findViewById(R.id.txtclose);
txtclose.setText("X");
//btnFollow = (Button) myDialog.findViewById(R.id.btnfollow);
txtclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myDialog.dismiss();
}
});
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
myDialog.show();
}
};
But that returns me:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at .EscolhaAtendimento$1.onPageSelected(EscolhaAtendimento.java:81) Line 81 is the one inside the switch with the popupchoice.setOnClickListener(image1).
This error happens on page change, when coming back to the first Page, and also the button click won't work anymore.
I think you can use
EscolhaAtendimento.this.ShowPopup from inside your switch.
My Goal:
So I need help putting a boolean primitives into a bundle and retrieving it from the bundle when there is a screen orientation change in Android. I am using that boolean value in a conditional statement that helps decide if 2 Button views (mTrueButton, mFalseButton) should be enabled or not. What i have so far is causing the app to shut down (aka crash) when there is a screen rotation. I think I am not retrieving or writing my boolean from my bundle or into my bundle correctly, and it is causing the app to crash.
How The App Should Works:
When a user touches the mTrueButton or mFalseButton button to answer a question, both buttons become disabled so the user is not allowed to answer again. I want those buttons to keep being disabled when the user answers and then rotates the screen.**
I know that when a user rotates their Android device, onDestroy() is called because runtime configuration changes take place, causing the app to be relaunched without having knowledge of it's previous state, (unless store my necessary data onto a bundle and pass it onto my onCreate method).
These are SOME global variables in my activity class
private int index = 0;
priavate Button mTrueButton,mFalseButton;
private static final String KEY_INDEX = "index";
private static final String BTTN_ENABLED = "bttnEnabled";
private boolean trueFalseButtonsEnabled = true;
These are SOME statements in my onCreate() method of the same activity class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
if(savedInstanceState != null) {
index = savedInstanceState.getInt(KEY_INDEX, 0);
changeButtonEnableStatus(savedInstanceState.getBoolean(BTTN_ENABLED,true));
}
mTrueButton = (Button)findViewById(R.id.true_button);
mFalseButton = (Button)findViewById(R.id.false_button);
mTrueButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
checkAnswer(true);
changeButtonEnableStatus(false);
}
});
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
changeButtonEnableStatus(false);
}
});
}
These are SOME methods in the same activity class but not in my onCreate()
private void changeButtonEnableStatus(boolean bool){
trueFalseButtonsEnabled = bool;
mTrueButton.setEnabled(bool);
mFalseButton.setEnabled(bool);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
Log.d(TAG,"onSavedInstanceState() called");
savedInstanceState.putInt(KEY_INDEX,index);
savedInstanceState.putBoolean(BTTN_ENABLED, trueFalseButtonsEnabled);
}
Note that:
index = savedInstanceState.getInt(KEY_INDEX, 0);
works properly. It is setting global variable "index" to equal to the int primitive what was stored in into keywork "KEY_INDEX".
However I don't think: changeButtonEnableStatus(savedInstanceState.getBoolean(BTTN_ENABLED,true)); is working properly. My app seems to crash when I include that statement and run the app, and then rotate the device.
When my app starts, the user needs to touch on the screen before the real action starts. I have a textView which gives the hint to touch the screen.
After the screen is touched, I want the text to get invisible. Right now the textView never disappears and always stays in the front.
public class MainActivity extends Activity implements OnGestureListener
{
public boolean touched = false;
TextView mMyView;
public void onTouch()
{
mMyView.setVisibility(View.GONE);
touched = true;
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
mMyView = (TextView)findViewById(R.id.textView6);
if(touched == true)
{
}
}
}
1.Always use if(something) if you want to see if it's true/false instead of writing if(something == true) [something is a boolian assigned with value true.]
2.If you point your views xml to a method using android:onClick like below,
<Button android:id="#+id/mybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!"
android:onClick="onTouch" />
.
What's the point of implementing OnGestureListener?
If i do this onCreate i initialize my view
View myView = findViewById(R.id.my_view);
3.If i really want a touch i will do this
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// ... Respond to touch events --> tv.setVisibility(View.INVISIBLE);
return true; // if you return false with this then the listener will not be called for the subsequent ACTION_MOVE and ACTION_UP string of events.
}
});
Now you can see in the 3rd ones parameter there is a MotionEvent, you can identify the motion ACTION_DOWN , ACTION_MOVE and ACTION_UP
Now think have you ever used them. You got an idea in your head about a touch so tried to use touch events .. But you don't use them. So it does the same as what onClickListner does in your case. If you want motions use that 3rd one i gave.
But simply you can use
// view is the background layout
myView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Do something here --> Hide your text tv.setVisibility(View.INVISIBLE);
}
});
Those view onClickListner or setOnTouchListener you can directly use them inside onCreate or keep them inside a method and you can call that method from onCreate. Why to keep a boolean? It's nothing major
Note i considered myView as the background layout not your textView , background is the one you click / touch
So now you changed the questions code several times and I hope it´s the final change. Only than my answer could help.
You have done this in your onCreate():
if(touched == true)
{
tv.setVisibility(View.INVISIBLE);
}
But this is executed directly and has nothing to do with you onTouch() method. Let´s assume your onTouch() works correctly. Make the TextView global:
TextView mMyView;
initialize it in onCreate():
mMyView = (TextView)findViewById(R.id.textView6);
and then hide it in onTouch():
onTouch(View view){
mMyView.setVisibility(View.GONE);
}
But you have to be sure that your method onTouch() works. You can make a Toast or a Log to check. You have to be sure that:
-The TextView is inside your layout xml that you set with setContentView(R.layout.activity_game);
-The onTouch() method is declared in your TextView's xml attribute
android:onClick="onTouch"
and set clickable of your TextView to true:
android:clickable="true";
EDIT
If you implement onGestureListener() I guess the touch event is consumed by the listener and your TextView did not recognize onTouch(). If you don´t do any gesture detection in your activity, then remove this implementation.
You are checking if screen was touched in onCreate() which is called only once at the start of the activity. Initialize TextView globally and set its visibility inside onTouch(View v, MotionEvent event)
Also your onTouch() isn;t correct. You should override public boolean onTouch(View v, MotionEvent event)
public class MainActivity extends Activity
{
public boolean touched = false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
TextView tv = (TextView) findViewById(R.id.textView6);
tv.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
touched = true;
tv.setVisibility(View.INVISIBLE);
return true;
}
});
}
}
Instead of implementing OnGestureListener add a setOnTouchListener in your root view of your activity layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rlTestView"/>
For example rlTestView is your activity's root layout id, then use below code in your oncreate method
((RelativeLayout)findViewById(R.id.rlTestView)).setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
tv.setVisibility(View.GONE);
return true;
}
});`
Use the code below on the onCreate method and yes set the visibility as GONE instead of invisible. Also state the current visibilty of the TextView in the onTouch then set it to
tv.setVisibility(View.GONE);
I have been getting into the android app world as of late. I understand that you want to place what variables you can into the onCreate method so that you can start using your variables right away. However, I am at a loss for a part of my code where I need to define onEditActionListener's to listen for user input but then also once enter is pressed get their text and send it to another activity. My research has shown I want to define these using the EditText and onEditActionListeners. however, I am at a loss as to how to go about this. Do I need to create a class that extends onEditActionListener?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_horde_calculator);
EditText myText = (EditText) findViewById(R.id.numToSend);
OnEditorActionListener onEditorActionListener = new myClass();
myText.setOnEditorActionListener(onEditorActionListener);
}
that is a copy of my current code and I am unsure if this is the correct way to go about doing it. If I was to create a new onEditActionListener wouldn't that make my onCreate more complex than having a few lines of variables? I feel that there might be a more clear way of going about this. However, after looking through stack overflow I couldnt' seem to find something that made sense. I didn't want to just copy and paste code, but really understand how it all flows together.
Just another idea of how you can achieve this:
public class MainActivity extends AppCompatActivity implements TextView.OnEditorActionListener {
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
editText = (EditText) findViewById(R.id.numToSend);
editText.setOnEditorActionListener(this);
}
#Override
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_NULL
&& event.getAction() == KeyEvent.ACTION_DOWN) {
//both attempt are the same
Log.d("onEditorAction", view.getText().toString());
Log.d("onEditorAction", editText.getText().toString());
}
return true;
}
}
Use TextView.OnEditorActionListener :
TextView.OnEditorActionListener listener = new TextView.OnEditorActionListener(){
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_NULL
&& event.getAction() == KeyEvent.ACTION_DOWN) {
//call your new activity here
}
return true;
}
};
myText.setOnEditorActionListener(listener);
I have two classes. I am trying to change a boolean value depending on if the user clicks a checkbox. Then, depending on whether that value is true/false (whether the checkbox was checked or not), I want to display specific text in a textview. Here is the MainActivity class:
public class BoiseActivity extends ActionBarActivity {
CheckBox cb;
public boolean isTrue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_boise);
cb = (CheckBox) findViewById(R.id.boiseCheckBox);
cb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isTrue = true;
}
});
public boolean isTrue() {
if (isTrue == true) {
return true;
}
return false;
}
Here is the new Activity that is opened once the user presses the "submit" button:
public class BoiseResults extends BoiseActivity {
TextView TV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_boise_results);
TV = (TextView) findViewById(R.id.textView1);
if (isTrue() == true) {
TV.setText("checkbox checked");
}
}
The boolean value is never changed in the BoiseActivity class onCreate-> onClick method. Can anyone see what is wrong here? Thanks
Apart from what has been said on you picking up a book on OOP (come on guys, everybody started somewhere):
The isTrue instance variable of your BoiseActivity will be present in it's child class BoiseResults because it (BoiseResults) inherits isTrue from BoiseActivity, but it's value will not be set and therefore interpreted als false, as Vikram pointed out.
What to do to straighten this out:
use onCheckedChangeListener for CheckBox
pass the boolean ('if the checkbox has been ticked') to your second Activity via the Intent you are starting it with, links on how to do this have been given in comments
ask yourself if BoiseResults really needs to subclass BoiseActivity (I do not think it does, it is just another Activity)
get rid of all the boolean mayhem you created with the isTrue() method returning the value of your isTrue variable
Rename BoiseResults to BoiseResultsActivity for clarity
Your onCreate{...} method for BoiseActivity doesn't seem to be a closed method.
You don't need the isTrue() method as it is really only returning the value of isTrue and isTrue is already a public instance variable. Regardless of that detail, you should look into (Explicit) Intents for passing data between activities: http://www.vogella.com/tutorials/AndroidIntent/article.html
Consider the use of the OnCheckedChangeListener;
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// DO SOMETHING HERE WHEN CHECKED/UNCHECKED
}
});
You can then check whether it is checked or not using the checkBox.isChecked() method.
It's also best for you to avoid performing unnecessary checks on a boolean value like;
public boolean isTrue() {
if (isTrue == true) {
return true;
}
return false;
}
The following would achieve the same;
public boolean isTrue(){
return isTrue;
}
With regards to your BoiseResults Activity, take a look at Intents if you are going to be changing from the BoiseActivity Activity to the BoiseResults Activity from your submit and need to pass data to BoiseResults.