Android getselectionStart and Getselectionend text don't work - android

could anyone explain, what i'm doing wrong?
in this case below, "tt" is my TexView.
On my Oncreate() method, I have:
tt = (TextView) findViewById(R.id.ni);
tt.setText("This is a try");
and then
tt.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String vi = tt.getText().toString().substring(tt.getSelectionStart(),tt.getSelectionEnd());
Toast.makeText(getApplicationContext(), vi,Toast.LENGTH_LONG).show();
}
});
Nothing is Shown at Onclick.
thanks.

I encountered the same problem a few days ago and I could find the following solution in the end. Delaying the process even 10 milliseconds could help interestingly. Put this in your onClick/onLongClick method, wherever you want to fetch the selected text.
For the original answer: textView.getSelectionEnd() returning start index value on Samsung Marshmallow 6.0 devices
I hope this helps those who have similar problem in the future.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
int startIndex = textView.getSelectionStart();
int endIndex = textView.getSelectionEnd();
if ((endIndex - startIndex) <= 0) {
return;
}
// UI related code here
}
}, TIME_IN_MS_TO_DELAY);
return false;

Related

Condition never returning true

I have an if statement which checks if three slots are finished. If it is, the timer should stop, but the code is not running for some reason. I have seen a post similar to this If-condition never executes despite correct condition, however their solution solved nothing.
Here is my code:
Stop function
public void stop(ImageSwitcher slot){
slotOneFinished = (slot.equals(slotOne));
slotTwoFinished = (slot.equals(slotTwo));
slotThreeFinished = (slot.equals(slotThree));
if (slotOneFinished&&slotTwoFinished&&slotThreeFinished){
//not running
Toast.makeText(MainActivity.this, "Running",Toast.LENGTH_SHORT).show();
checkWin(getFruits());
timer.cancel();
timer = null;
}
}
Timer
private Timer timer;
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new TimerTask() {
#Override
public void run() {
if (!slotOneFinished){
animate(randomSwitchCount(), slotOne);
}
if (!slotTwoFinished) {
animate(randomSwitchCount(), slotTwo);
}
if (!slotThreeFinished) {
animate(randomSwitchCount(), slotThree);
}
}
});
}
};
Animate function
public void animate(final int maxCount, final ImageSwitcher slot) {
i++;
if (i<maxCount){
Animation in = AnimationUtils.loadAnimation(this, R.anim.new_slot_item_in);
Animation out = AnimationUtils.loadAnimation(this, R.anim.old_item_out);
slot.setInAnimation(in);
slot.setOutAnimation(out);
int fruit = randomFruit();
slot.setTag(fruit);
slot.setImageResource(fruit);
}else {
stop(slot);
}
}
Using == did nothing as well.
Thanks for your help,
PiNet
This condition can never be true, assuming that equals() is implemented in the canonical way, and slotOne, slotTwo, and slotThree are 3 distinct objects:
if (slotOneFinished&&slotTwoFinished&&slotThreeFinished)
Looks like you had a mistaken assumption about the scope of the variables. You can probably fix this by using a condition like this, instead:
if( slot == slotOne )
slotOneFinished = true;
...and so forth.
The Android Studio debugger is your friend.

Android GUI: TextView continously updating

I have got some problems to understand runOnUiThread(). I want to update the TextView continously but nothing happens. The GUI is still blocked. Could somebody help me?
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
runner();
}
public void runner (){
String[] testFiles = GeneralHelper.getPictureFileList();
TextView text = (TextView) findViewById(R.id.textfeld);
for (int i = 0; i < 2; i++)
{
runOnUiThread(new Runnable() {
public void run() {
text.setText("\n" + GeneralHelper.getPictureFileList()[i]);
}
});
...
// image analysis
}}
The loop has only 2 iterations and it is done so fast that you even can't see changes. You only see result GeneralHelper.getPictureFileList()[1]
And you are inside UiThread so you shouldn't use it. Just:
public void runner (){
String[] testFiles = GeneralHelper.getPictureFileList();
TextView text = (TextView) findViewById(R.id.textfeld);
for (int i = 0; i < 2; i++)
{
text.setText("\n" + GeneralHelper.getPictureFileList()[i]);
}
}
Sounds like you need to create your own timer class where you can include runOnUiThread() to update your TextView. That's what I did on a program I wrote where I needed to display the time counting up every second as soon as the user pressed a button.

Android: Text Colors not changing

I'm writing a quiz application which presents the user with a question and 4 choices. When the user clicks on a choice, the app should change the colour of the correct choice to green and the colour of the incorrect choice to red. It should then wait a second before displaying the next question.
The problem is that it doesn't do the colour changes (except for the last question) and I don't understand why. I know that my android.os.SystemClock.sleep(1000) has something to do with it.
I'd appreciate it if you could tell me where I've gone wrong or if I'm going about this an incorrect way. Thanks :)
public void onClick(View v) {
setButtonsEnabled(false);
int answer = Integer.parseInt(v.getTag().toString());
int correct = question.getCorrectAnswer();
if(answer == correct)
numCorrect++;
highlightAnswer(answer,correct,false);
android.os.SystemClock.sleep(1000);
MCQuestion next = getRandomQuestion();
if(next != null) {
question = next;
highlightAnswer(answer,correct,true);
displayQuestion();
setButtonsEnabled(true);
}
else {
float percentage = 100*(numCorrect/questionsList.size());
QuizTimeApplication.setScore(percentage);
Intent scoreIntent = new Intent(QuestionActivity.this,ScoreActivity.class);
startActivity(scoreIntent);
}
}
private void setButtonsEnabled(boolean enable) {
for(Button b: buttons)
b.setEnabled(enable);
}
private void highlightAnswer(int answer, int correct, boolean undo) {
if(undo) {
for(Button button : buttons) {
button.setTextColor(getResources().getColor(R.color.white));
button.setTextSize(FONT_SIZE_NORMAL);
}
return;
}
buttons[correct].setTextColor(getResources().getColor(R.color.green));
buttons[correct].setTextSize(FONT_SIZE_BIG);
if(answer!=correct) {
buttons[answer].setTextColor(getResources().getColor(R.color.red));
buttons[answer].setTextSize(FONT_SIZE_BIG);
}
}
SystemClock.sleep(1000);
will give unexpected behaviour and may not work good for your requirement. It is better you use Handler with a delay like below.
Handler h = new Handler();
h.postDelayed(new Runnable(){
#Override
public void run()
{
//your code that has to be run after a delay of time. in your case the code after SystemClock.sleep(1000);
},YOUR_DELAY_IN_MILLISECONDS
);

Function not repeating On Click?

I'm trying to make a small Android game. My on click function however is not getting repeated... It adds one point the first time and then stops working. It looks correct to me.
addButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
playerScoreField = (TextView)findViewById(R.id.playerScore);
int playerScore = 0;
if(playerScore != target){
playerScore++;
playerScoreField.setText("You are at: " + playerScore);
} else {
addButton.setClickable(false);
addButton.setEnabled(false);
countDown.onFinish();
}
}
});
I think you might have a logic error. You are setting playerScore to zero on each click. This will result in the score always being 1. Declare your playerScore variable in a different way.

setHint fails during Runnable

My code is intended to update the hint of an EditText with the time, allowing the user to enter a different time as the text or use the hint if the user has not entered anything like so:
mTicker = new Runnable()
{
public void run()
{
time.setHint(new TimeDate().getTime());
long now = SystemClock.uptimeMillis();
long next = now + (1000 - now % 1000);
spaceTimeHandler.postAtTime(mTicker, next);
}
This code runs except that the EditText remains blank; if you exchange setHint with setText then everything works fine. Is this a bug?
I realize I should probably use the DateTimePicker or whatever but I haven't gotten around to that yet, and this issue would occur regardless of what string I try to setHint with.
mTicker = new Runnable()
{
public void run()
{
runOnUiThread(new Runnable(){
#Override
public void run() {
time.setHint(new TimeDate().getTime());
long now = SystemClock.uptimeMillis();
long next = now + (1000 - now % 1000);
spaceTimeHandler.postAtTime(mTicker, next);
}
});
}
}
Enclose it in a runOnUiThread, let me know if it worked.

Categories

Resources