Android app - Inputting integers from buttons depending on number of presses - java

I'm writing a calculator app for android using android studio. I want to used 4 buttons for inputting values and functions. However the way I am currently doing it takes the input from the text written on the button. So for my button 1/2/3 when this is pressed 1/2/3 is passed to the textView.
Below is my MainActivity:
package com.example.myfirstapp;
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.MediaController;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private int[] operatorButtons = {R.id.operators};
private int[] numericButtons = {R.id.onetwothree, R.id.fourfivesix, R.id.seveneightninezero};
private boolean lastNumeric, stateError;
private TextView txtScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the TextView
this.txtScreen = (TextView) findViewById(R.id.txtScreen);
// Find and set OnClickListener to numeric buttons
setNumericOnClickListener();
// Find and set OnClickListener to operator buttons, equal button and decimal point button
setOperatorOnClickListener();
}
private void setNumericOnClickListener() {
// Create a common OnClickListener
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Just append/set the text of clicked button
Button button = (Button) v;
if (stateError) {
// If current state is Error, replace the error message
txtScreen.setText(button.getText());
stateError = false;
} else {
// If not, already there is a valid expression so append to it
txtScreen.append(button.getText());
}
// Set the flag
lastNumeric = true;
}
};
// Assign the listener to all the numeric buttons
for (int id : numericButtons) {
findViewById(id).setOnClickListener(listener);
}
}
private void setOperatorOnClickListener() {
// Create a common OnClickListener for operators
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// If the current state is Error do not append the operator
// If the last input is number only, append the operator
if (lastNumeric && !stateError) {
Button button = (Button) v;
txtScreen.append(button.getText());
lastNumeric = false;
}
}
};
// Assign the listener to all the operator buttons
for (int id : operatorButtons) {
findViewById(id).setOnClickListener(listener);
}
// Equal button
/*findViewById(R.id.btnEqual).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onEqual();
}
});*/
}
}
and my activity_main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtScreen"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:gravity="right|center_vertical"
android:maxLength="16"
android:padding="10dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30sp"
android:typeface="serif" />
<!--<Button-->
<!--android:id="#+id/equal1"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="100dp"-->
<!--android:text="="-->
<!--/>-->
<Button
android:id="#+id/equal2"
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="="
android:layout_alignParentBottom="true"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/txtScreen"
android:orientation="vertical"
android:layout_above="#id/equal2">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<Button
android:id="#+id/onetwothree"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="1/2/3"/>
<Button
android:id="#+id/fourfivesix"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="4/5/6"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<Button
android:id="#+id/seveneightninezero"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="7/8/9/0"/>
<Button
android:id="#+id/operators"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="+-*/"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Will it be possible for me to get the input of 1, 2 or 3 from my first button for example? So on 1 press you get 1, 2 press gives 2 etc.
Any suggestions/ ideas on how I can move forward with this are greatly appreciated.
Kind Regards,
Ben

You could use a timer or delay variable to detect single, double or triple taps. This post may be of interest. If the time interval is not a factor, you could just keep track of the last pressed button and if the same button is being pressed again, update the text accordingly.
If you follow approach one, the code for the click listener for button onetwothree may be something like this (I commented out setNumericOnClickListener() and setOperatorOnClickListener(); in mainActivity onCreate and added the following):
Button onetwothree = (Button) findViewById(R.id.onetwothree);
onetwothree.setOnTouchListener(new View.OnTouchListener() {
Handler handler = new Handler();
int numberOfTaps = 0;
long lastTapTimeMs = 0;
long touchDownMs = 0;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchDownMs = System.currentTimeMillis();
break;
case MotionEvent.ACTION_UP:
handler.removeCallbacksAndMessages(null);
if ((System.currentTimeMillis() - touchDownMs) > ViewConfiguration.getTapTimeout()) {
//it was not a tap
numberOfTaps = 0;
lastTapTimeMs = 0;
break;
}
if (numberOfTaps > 0
&& (System.currentTimeMillis() - lastTapTimeMs) < ViewConfiguration.getDoubleTapTimeout()) {
numberOfTaps += 1;
} else {
numberOfTaps = 1;
}
lastTapTimeMs = System.currentTimeMillis();
if (numberOfTaps == 1) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("1");
} else txtScreen.append("1");
}
}, ViewConfiguration.getDoubleTapTimeout());
}else if (numberOfTaps == 2) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("2");
} else txtScreen.append("2");
}
}, ViewConfiguration.getDoubleTapTimeout());
} else if (numberOfTaps == 3) {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("3");
} else txtScreen.append("3");
}
}
return true;
}
});
Complete MainActivity:
package com.example.myfirstapp;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private int[] operatorButtons = {R.id.operators};
private int[] numericButtons = {R.id.onetwothree, R.id.fourfivesix, R.id.seveneightninezero};
private boolean lastNumeric, stateError;
private TextView txtScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the TextView
this.txtScreen = (TextView) findViewById(R.id.txtScreen);
// Find and set OnClickListener to numeric buttons
// setNumericOnClickListener();
// Find and set OnClickListener to operator buttons, equal button and decimal point button
// setOperatorOnClickListener();
Button onetwothree = (Button) findViewById(R.id.onetwothree);
onetwothree.setOnTouchListener(new View.OnTouchListener() {
Handler handler = new Handler();
int numberOfTaps = 0;
long lastTapTimeMs = 0;
long touchDownMs = 0;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchDownMs = System.currentTimeMillis();
break;
case MotionEvent.ACTION_UP:
handler.removeCallbacksAndMessages(null);
if ((System.currentTimeMillis() - touchDownMs) > ViewConfiguration.getTapTimeout()) {
//it was not a tap
numberOfTaps = 0;
lastTapTimeMs = 0;
break;
}
if (numberOfTaps > 0
&& (System.currentTimeMillis() - lastTapTimeMs) < ViewConfiguration.getDoubleTapTimeout()) {
numberOfTaps += 1;
} else {
numberOfTaps = 1;
}
lastTapTimeMs = System.currentTimeMillis();
if (numberOfTaps == 1) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("1");
} else txtScreen.append("1");
}
}, ViewConfiguration.getDoubleTapTimeout());
}else if (numberOfTaps == 2) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("2");
} else txtScreen.append("2");
}
}, ViewConfiguration.getDoubleTapTimeout());
} else if (numberOfTaps == 3) {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("3");
} else txtScreen.append("3");
}
}
return false;
}
});
}
private void setNumericOnClickListener() {
// Create a common OnClickListener
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Just append/set the text of clicked button
Button button = (Button) v;
if (stateError) {
// If current state is Error, replace the error message
txtScreen.setText(button.getText());
stateError = false;
} else {
// If not, already there is a valid expression so append to it
txtScreen.append(button.getText());
}
// Set the flag
lastNumeric = true;
}
};
// Assign the listener to all the numeric buttons
for (int id : numericButtons) {
findViewById(id).setOnClickListener(listener);
}
}
private void setOperatorOnClickListener() {
// Create a common OnClickListener for operators
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// If the current state is Error do not append the operator
// If the last input is number only, append the operator
if (lastNumeric && !stateError) {
Button button = (Button) v;
txtScreen.append(button.getText());
lastNumeric = false;
}
}
};
// Assign the listener to all the operator buttons
for (int id : operatorButtons) {
findViewById(id).setOnClickListener(listener);
}
}
}

You can take all numbers when doing some operation
(Button) plusBtn = (Button) findViewById(R.id.plusBtn);
plusBtn.setOnClickListener(new OnClickListener(){
#Override
public voidonClick(View v){
number1 = Integer.parseInt(txtScreen.getText().toString());
});
Where number1 is global int. But I don't know how it can help you and if it is a good approach. You could find a better solution, just remember how to parse the String from your TextView to Integer for your calculation.

Related

Black screen on android studio

Hi this is one of my old apps I am trying to fix, when I run this code I get a black screen but the app does not close. There are no errors and the fonts are fine so why is it not working? It works up until I start a new activity with this class. Thanks in advance. Also if you are able to suggest a better timer to use that would be great as when I used to use this app it did not work correctly.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
android:gravity="end">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/MainQuestion"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/SecondsLeft"
android:layout_gravity="center_horizontal"
/>
<Button
android:layout_width="115dp"
android:layout_height="87dp"
android:id="#+id/Question1"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="115dp"
android:layout_height="87dp"
android:id="#+id/Question2"
android:text=""
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="115dp"
android:layout_height="87dp"
android:id="#+id/Choice3"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="115dp"
android:layout_height="87dp"
android:id="#+id/Choice4"
android:layout_gravity="center_horizontal" />
</LinearLayout>
package com.steam.mytriviaapp;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.*;
import android.os.CountDownTimer;
import android.content.Intent;
//necessary imports//
public class SportsCat extends AppCompatActivity {//extension needed for app//
TextView Question;//new textview variable to show the random question//
Button Choice1;//new button variable for answers//
Button Choice2;//^//
Button Choice3;//^//
Button Choice4;//^//
TextView SecondsLeft;//new textview variable//
int QuestionCounter =0;//question counter int set to 0//
public static Integer Points = 0;// points set/reset to 0 depending on if it is first game since it was opened //
boolean[] numbers = new boolean [4];//new boolean array with 4 numbers and are auto set to false, then later if true, they cannot be used, so it will not use samequestion//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sports_cat);//all of these linked to their respective xml variable to change sizing etc//
SecondsLeft = findViewById(R.id.SecondsLeft);
Question = findViewById(R.id.MainQuestion);
Choice1 = findViewById(R.id.Question1);
Choice2 = findViewById(R.id.Question2);
Choice3 = findViewById(R.id.Choice3);
Choice4 = findViewById(R.id.Choice4);
for(int k=0;k<=4;k++)
{
Body();
}
}
public void Body() {//new object//
String[] ArraySportsQuestions = {"Which NBA team holds the record for the most season wins in the Eastern Conference in history?",
"Which of these soccer players has won the most FIFA Ballon d'Ors after 2010?",
"Since what year was table tennis an Olympic sport?", "Which of these athletes had a video game made in honour of him?", "How many national sports does Canada have?"};//questions to be used//
final String[] ArraySportsQ1 = {"Boston Celtics", "Miami Heat", "Chicago Bulls", "Cleveland Cavaliers"};//question answers//
final String[] ArraySportsQ2 = {"Lionel Messi", "Cristiano Ronaldo", "Neymar", "Luis Suarez"};
final String[] ArraySportsQ3 = {"1988", "1974", "1984", "1996"};
final String[] ArraySportsQ4 = {"Shaun White", "Micheal Jordan", "Lionel Messi", "Shaun Federer"};
final String[] ArraySportsQ5 = {"2", "1", "3", "4"};
String[][] arrayofQs = {ArraySportsQ1, ArraySportsQ2, ArraySportsQ3,
ArraySportsQ4, ArraySportsQ5};//2D array//
QuestionCounter++;
Random gen = new Random();//new random generator gen//
int num = gen.nextInt(4);
while(numbers[num] = true)//makes sure it is not the same number//
{
num = gen.nextInt(4);
}
numbers[num] = true;
int x = gen.nextInt(3);
int y = gen.nextInt(3);
while(y==x) //^//
{
y = gen.nextInt(3);
}
int z = gen.nextInt(3);
while(z==x||z==y) {
z = gen.nextInt(3);
}
int u = gen.nextInt(3);
while(u==x||u==y||u==z) {
u = gen.nextInt(3);
}
new CountDownTimer(10000, 1000) {//android made countdown timer that icustomised//
public void onTick(long millisUntilFinished) {
SecondsLeft.setText("seconds remaining: " + millisUntilFinished /
1000);
}
public void onFinish() {
SecondsLeft.setText("done!");
}
}.start();
Typeface font2 = Typeface.createFromAsset(getAssets(), "subway.ttf");
Question.setTypeface(font2);
Question.setText(ArraySportsQuestions[num]);//randomising of questions andanswers//
Choice1.setText(arrayofQs[num][x]);//sets the answer to the set for thequestion, for example is num = 3, answer set 3, and then the buttons below to randomstrings in this inner array//
Choice2.setText(arrayofQs[num][y]);
Choice3.setText(arrayofQs[num][z]);
Choice4.setText(arrayofQs[num][u]);
Choice1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Choice1.getText().equals(ArraySportsQ1[1])||Choice1.getText().equals(ArraySportsQ2[
1]) || Choice1.getText().equals(ArraySportsQ3[1]) ||
Choice1.getText().equals(ArraySportsQ4[1]) ||
Choice1.getText().equals(ArraySportsQ5[1]))// these are the answers//
{
Points++;
Toast.makeText(SportsCat.this, "Correct!" ,
Toast.LENGTH_LONG).show();//a notification type message at the bottom of the screendisappearing after//
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else{
Body();
}
}else
{
Toast.makeText(SportsCat.this, "Incorrect" ,
Toast.LENGTH_LONG).show();
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else
{
Body();
}
}
}
});
Choice2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Choice1.getText().equals(ArraySportsQ1[1])||Choice1.getText().equals(ArraySportsQ2[
1]) || Choice1.getText().equals(ArraySportsQ3[1]) ||
Choice1.getText().equals(ArraySportsQ4[1]) ||
Choice1.getText().equals(ArraySportsQ5[1]))
{Points++;
Toast.makeText(SportsCat.this, "Correct!" ,
Toast.LENGTH_LONG).show();
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else{
Body();
}
}else
{
Toast.makeText(SportsCat.this, "Incorrect" ,
Toast.LENGTH_LONG).show();
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else{
Body();
}
}
}
});
Choice3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Choice1.getText().equals(ArraySportsQ1[1])||Choice1.getText().equals(ArraySportsQ2[
1]) || Choice1.getText().equals(ArraySportsQ3[1]) ||
Choice1.getText().equals(ArraySportsQ4[1]) ||
Choice1.getText().equals(ArraySportsQ5[1]))
{Points++;
Toast.makeText(SportsCat.this, "Correct!" ,
Toast.LENGTH_LONG).show();
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else{
Body();
}
}else
{
Toast.makeText(SportsCat.this, "Incorrect" ,
Toast.LENGTH_LONG).show();
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else{
Body();
}
}
}
});
Choice4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Choice1.getText().equals(ArraySportsQ1[1])||Choice1.getText().equals(ArraySportsQ2[
1]) || Choice1.getText().equals(ArraySportsQ3[1]) ||
Choice1.getText().equals(ArraySportsQ4[1]) ||
Choice1.getText().equals(ArraySportsQ5[1]))
{Points++;
Toast.makeText(SportsCat.this, "Correct!" ,
Toast.LENGTH_LONG).show();
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else{
Body();
}}else
{
Toast.makeText(SportsCat.this, "Incorrect" ,
Toast.LENGTH_LONG).show();
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else{
Body();
}
Toast.makeText(SportsCat.this, "Incorrect" ,
Toast.LENGTH_LONG).show();
}
}
});
}}

EditText cursor visible even if the EditText is not editable

I need to introduce data in an EditText but i want to use an virtual keyboard, not the android keyboard. If I use setKeyListener(null) the cursor is invisible even after using setCursorVisible(true).
Is it possible to make an EditText where even if it isn't editable the cursor is visible ?
EDIT 2 :
I found an partial method to do that, but it's not working when i'm double taping the EditText.
I made an setOnClickListner() and an setOnLongClickListner() method for the EditText. In this methods I hide the Soft Input from the Window, also i use setTextIsSelectable(false). My only problem is that when I double tap the EditText the soft input keyboard shows and I dont know how to hide it, I tried to use android:windowSoftInputMode="stateAlwaysHidden" in manifest, but it doesn't work either.
EDIT :
Here is the code that I'm using at this moment for my base converter calculator.
public class MainActivity extends AppCompatActivity {
EditText number;
EditText base;
boolean baseB = false;
String numberS = "0";
String baseS = "10";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
//make the EditText for number and base not editable
number = (EditText) findViewById(R.id.number);
number.setKeyListener(null);
base = (EditText) findViewById(R.id.base);
base.setKeyListener(null);
//... more code here (changing fonts for each EditText and changing status bar color
}
// I have a function for each button all are the same
public void onClickBaseChange(View v) {
if (baseB) {
baseB = false;
// i use toasts at this moment to know when i'm on number or base field
Toast.makeText(this, "Number", Toast.LENGTH_SHORT).show();
} else {
baseB = true;
Toast.makeText(this, "Base", Toast.LENGTH_SHORT).show();
}
}
public void onClickB0(View v) {
if (numberS.length() > 0 && !numberS.equals("0") && !baseB) {
numberS += "0";
number = (EditText) findViewById(R.id.number);
number.setText(numberS, TextView.BufferType.EDITABLE);
number.setSelection(numberS.length());
} else {
if (Integer.valueOf(baseS) >= 1) {
baseS += "0";
base = (EditText) findViewById(R.id.base);
base.setText(baseS, TextView.BufferType.EDITABLE);
}
}
}
public void onClickB1(View v) {
if (numberS.equals("0")) {
numberS = "1";
} else {
numberS += "1";
}
number = (EditText) findViewById(R.id.number);
number.setText(numberS, TextView.BufferType.EDITABLE);
number.requestFocus();
number.setSelection(numberS.length());
}
And the xml looks like this :
<android.widget.RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/colorBackground"
tools:context="manastur.calculator.MainActivity">
<EditText
android:id="#+id/base"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="20dp"
android:layout_marginTop="120dp"
android:background="#android:color/transparent"
android:cursorVisible="true"
android:text=""
android:textColor="#color/text"
android:textSize="30dp" />
<EditText
android:id="#+id/number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="50dp"
android:background="#android:color/transparent"
android:cursorVisible="true"
android:text=""
android:textColor="#color/text"
android:textSize="50dp" />
<LinearLayout
android:id="#+id/secondRow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/firstRow"
android:layout_centerHorizontal="true">
<Button
android:id="#+id/b1"
android:layout_width="85dp"
android:layout_height="85dp"
android:background="#drawable/b1"
android:onClick="onClickB1" />
<Button
android:id="#+id/b2"
android:layout_width="85dp"
android:layout_height="85dp"
android:background="#drawable/b2"
android:onClick="onClickB2" />
<!-- from this point on is the same, there are 5 LinearLayouts which
represents the 5 rows of button of the num pad -->
Use this code to achieve that,
While develop I took reference from native Dialpad code
KeypadlessKeypad.java
import android.content.Context;
import android.graphics.Rect;
import android.support.v4.view.MotionEventCompat;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class KeypadlessKeypad extends EditText {
private static final Method mShowSoftInputOnFocus = getSetShowSoftInputOnFocusMethod(
EditText.class, "setShowSoftInputOnFocus", boolean.class);
public static Method getSetShowSoftInputOnFocusMethod(Class<?> cls, String methodName, Class<?>... parametersType) {
Class<?> sCls = cls.getSuperclass();
while (sCls != Object.class) {
try {
return sCls.getDeclaredMethod(methodName, parametersType);
} catch (NoSuchMethodException e) {
// Just super it again
}
sCls = sCls.getSuperclass();
}
return null;
}
private Context mContext;
/**
* Listener for Copy, Cut and Paste event
* Currently callback only for Paste event is implemented
*/
private OnEditTextActionListener mOnEditTextActionListener;
public KeypadlessKeypad(Context context) {
super(context);
mContext = context;
init();
}
public KeypadlessKeypad(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
init();
}
public KeypadlessKeypad(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
mContext = context;
init();
}
#Override
protected void onSelectionChanged(int selStart, int selEnd) {
super.onSelectionChanged(selStart, selEnd);
}
public final void appendText(CharSequence text) {
append(text, 0, text.length());
}
/***
* Initialize all the necessary components of TextView.
*/
private void init() {
setSingleLine(true);
synchronized (this) {
setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
setFocusableInTouchMode(true);
}
reflexSetShowSoftInputOnFocus(false); // Workaround.
// Ensure that cursor is at the end of the input box when initialized. Without this, the
// cursor may be at index 0 when there is text added via layout XML.
setSelection(getText().length());
}
#Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
hideKeyboard();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
final boolean ret = super.onTouchEvent(event);
// Must be done after super.onTouchEvent()
hideKeyboard();
return ret;
}
private void hideKeyboard() {
final InputMethodManager imm = ((InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE));
if (imm != null && imm.isActive(this)) {
imm.hideSoftInputFromWindow(getApplicationWindowToken(), 0);
}
}
private void reflexSetShowSoftInputOnFocus(boolean show) {
if (mShowSoftInputOnFocus != null) {
invokeMethod(mShowSoftInputOnFocus, this, show);
} else {
// Use fallback method. Not tested.
hideKeyboard();
}
}
public static Object invokeMethod(Method method, Object receiver, Object... args) {
try {
return method.invoke(receiver, args);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
return null;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int textViewWidth = View.MeasureSpec.getSize(widthMeasureSpec);
int height = getMeasuredHeight();
this.setMeasuredDimension(textViewWidth, height);
}
#Override
protected void onTextChanged(CharSequence text, int start, int before,
int after) {
super.onTextChanged(text, start, before, after);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
}
#Override
public boolean onTextContextMenuItem(int id) {
boolean consumed = super.onTextContextMenuItem(id);
switch (id) {
case android.R.id.paste:
if (mOnEditTextActionListener != null) {
mOnEditTextActionListener.onPaste();
}
break;
}
return consumed;
}
/**
* Setter method for {#link #mOnEditTextActionListener}
*
* #param onEditTextActionListener
* Instance of the {#link OnEditTextActionListener}
*/
public void setOnEditTextActionListener(OnEditTextActionListener onEditTextActionListener) {
this.mOnEditTextActionListener = onEditTextActionListener;
}
private Rect mRect = new Rect();
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
final int action = MotionEventCompat.getActionMasked(event);
int[] location = new int[2];
getLocationOnScreen(location);
mRect.left = location[0];
mRect.top = location[1];
mRect.right = location[0] + getWidth();
mRect.bottom = location[1] + getHeight();
int x = (int) event.getX();
int y = (int) event.getY();
if (action == MotionEvent.ACTION_DOWN && !mRect.contains(x, y)) {
InputMethodManager input = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
input.hideSoftInputFromWindow(getWindowToken(), 0);
}
return super.dispatchTouchEvent(event);
}
#Override
public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED) {
// Since we're replacing the text every time we add or remove a
// character, only read the difference. (issue 5337550)
final int added = event.getAddedCount();
final int removed = event.getRemovedCount();
final int length = event.getBeforeText().length();
if (added > removed) {
event.setRemovedCount(0);
event.setAddedCount(1);
event.setFromIndex(length);
} else if (removed > added) {
event.setRemovedCount(1);
event.setAddedCount(0);
event.setFromIndex(length - 1);
} else {
return;
}
} else if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED) {
// The parent EditText class lets tts read "edit box" when this View has a focus, which
// confuses users on app launch (issue 5275935).
return;
}
super.sendAccessibilityEventUnchecked(event);
}
/**
* Interface to get callback from the Edittext copy, cut and paste event
* For time being only the Paste Event callback is generated
*/
public interface OnEditTextActionListener {
/**
* If Edittext get paste event then this method will be called
*/
void onPaste();
}
}
In your xml you can give like this,
<[package name].KeypadlessKeypad
android:id="#+id/dialnumbertv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00000000"
android:cursorVisible="false"
android:ellipsize="start"
android:gravity="center"
android:inputType="phone"
android:singleLine="true"
android:textIsSelectable="true"
android:textSize="30sp"
android:textStyle="italic"
android:visibility="visible"/>
And in your fragment you can implement like this,
public void onViewCreated(final View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mDialNumbertv = view.findViewById(R.id.dialnumbertv);
mDialNumbertv.setCursorVisible(false);
mDialNumbertv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isDigitsEmpty()) {
mDialNumbertv.setCursorVisible(true);
}
}
});
mDialNumbertv.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (isDigitsEmpty()) {
mDialNumbertv.setCursorVisible(false);
}
// updateDeleteButton();
}
});
mDialNumbertv.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// Ref https://android.googlesource.com/platform/packages/apps/Contacts/+/39948dc7e34dc2041b801058dada28fedb80c388/src/com/android/contacts/dialpad/DialpadFragment.java
// Right now EditText does not show the "paste" option when cursor is not visible.
// To show that, make the cursor visible, and return false, letting the EditText
// show the option by itself.
mDialNumbertv.setCursorVisible(true);
return false;
}
});
mDialNumbertv.setOnEditTextActionListener(
new KeypadlessKeypad.OnEditTextActionListener() {
#Override
public void onPaste() {
// If some content pasted on mDialNumbertv
// we need to run some search on Contact and Price
String mobileNumber = mDialNumbertv.getText().toString();
if (TextUtils.isEmpty(mobileNumber)) {
return;
}
// updateContactName(mobileNumber);
}
});
}
private KeypadlessKeypad mDialNumbertv;
private boolean isDigitsEmpty() {
return mDialNumbertv.length() == 0;
}
private void setClickedDigit(final String digitToSet) {
if (!TextUtils.isEmpty(digitToSet)) {
char digit = digitToSet.charAt(0);
String mobileNumber = mDialNumbertv.getText() + digitToSet;
mDialNumbertv.getText().insert(mDialNumbertv.getSelectionStart(), digitToSet);
// If the cursor is at the end of the text we hide it.
final int length = mDialNumbertv.length();
if (length == mDialNumbertv.getSelectionStart() && length == mDialNumbertv.getSelectionEnd()) {
mDialNumbertv.setCursorVisible(false);
}
}
}
I wanted the same behavior which I achieved as follows -
Make a custom class that will override 2 methods of AppCompatEditText.
class CustomEditText(context: Context?, attrs: AttributeSet) : AppCompatEditText(context, attrs) {
override fun onCheckIsTextEditor(): Boolean {
return true
}
override fun isTextSelectable(): Boolean {
return true
}
}
In the XML file, create EditText using this custom view.
<com.ui.custom.CustomEditText
android:id="#+id/et_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="none"
android:focusable="true"
android:gravity="center"
android:focusableInTouchMode="true"/>
Now, just add onFocusChangeListener and set editText.setKeyListener = null.
binding.etEmail.onFocusChangeListener = OnFocusChangeListener { v, hasFocus ->
if (hasFocus) {
binding.etEmail.keyListener = null
}
}
You can add the same on onTouch if that is the requirement.
The main issue here is that onCheckIsTextEditor() of View class always returns false, which leads to cursor never blinking or being visible even if setCursorVisible(true) was called in code.
I hope it helps.
You can use edittext.setselection(0)
or
maybe you can request focus using requestfocus()

My cardviews won't always dismiss when swiped to left or right?

I am using a FrameLayout to carry out the swipe gesture of each of my cardviews, but the cards do not always dismiss. And sometimes they just hang on the left or the right until the user swipes the card a second time.
How can I fix this?
MyFrameLayout:
public class MyFrameLayout extends FrameLayout {
private static int mWidth = 200;
MyFrameLayout touchFrameLayout;
// Constructors
// i call "initialize(context)" in all of them
private void initialize(Context context) {
setOnTouchListener(mTouchListener);
touchFrameLayout = this;
}
private float mDisplacementX;
private float mDisplacementY;
private float mInitialTx;
private boolean mTracking;
private OnTouchListener mTouchListener = new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
mWidth = (int) touchFrameLayout.getLayoutParams().width;
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
mDisplacementX = event.getRawX();
mDisplacementY = event.getRawY();
mInitialTx = getTranslationX();
return true;
case MotionEvent.ACTION_MOVE:
// get the delta distance in X and Y direction
float deltaX = event.getRawX() - mDisplacementX;
float deltaY = event.getRawY() - mDisplacementY;
// updatePressedState(false);
// set the touch and cancel event
if ((Math.abs(deltaX) > ViewConfiguration.get(getContext())
.getScaledTouchSlop() * 2 && Math.abs(deltaY) < Math
.abs(deltaX) / 2)
|| mTracking) {
mTracking = true;
if (getTranslationX() <= mWidth / 2
&& getTranslationX() >= -(mWidth / 2)) {
setTranslationX(mInitialTx + deltaX);
return true;
}
}
break;
case MotionEvent.ACTION_UP:
if (mTracking) {
mTracking = false;
float currentTranslateX = getTranslationX();
if (currentTranslateX > (mWidth/10)) {
rightSwipe();
} else if (currentTranslateX < -(mWidth*10)) {
leftSwipe();
}
// comment this line if you don't want your frame layout to
// take its original position after releasing the touch
setTranslationX(0);
return true;
} else {
// handle click event
setTranslationX(0);
}
break;
}
return false;
}
};
private void rightSwipe() {
Toast.makeText(this.getContext(), "Swipe to the right",
Toast.LENGTH_SHORT).show();
DeleteCard();
}
private void leftSwipe() {
Toast.makeText(this.getContext(), "Swipe to the left",
Toast.LENGTH_SHORT).show();
DeleteCard();
}
}
Xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.testing.android.layout.MyFrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/taskViewContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:cardElevation="8dp"
app:cardPreventCornerOverlap="false"
card_view:cardCornerRadius="8dp">
</android.support.v7.widget.CardView>
</com.example.testing.android.layout.MyFrameLayout>
</RelativeLayout>
I adapted romannurik's Android-SwipeToDismiss to do exactly that.
The code is on github with a woking sample application, and consists of:
A subclass of RecyclerView.OnItemTouchListener that listens to touch events and detects when an item is being swiped, animating it accordingly.
A SwipeListener that is called in order to know if an item can be dismissed and called again when items are dismissed.
To use it, copy the class SwipeableRecyclerViewTouchListener to your project and use it like this
mAdapter = new CardViewAdapter(mItems);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
SwipeableRecyclerViewTouchListener swipeTouchListener =
new SwipeableRecyclerViewTouchListener(mRecyclerView,
new SwipeableRecyclerViewTouchListener.SwipeListener() {
#Override
public boolean canSwipe(int position) {
return true;
}
#Override
public void onDismissedBySwipeLeft(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
mItems.remove(position);
mAdapter.notifyItemRemoved(position);
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onDismissedBySwipeRight(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
mItems.remove(position);
mAdapter.notifyItemRemoved(position);
}
mAdapter.notifyDataSetChanged();
}
});
mRecyclerView.addOnItemTouchListener(swipeTouchListener);
}
This can also be useful : http://www.getgoodcode.com/2013/06/swipe-to-dismiss-google-style/
Hope it works for you !

Layout is not Displayed as shown in the Graphical layout?

I have a Layout in my App Which has 5 Frame Layouts.I have Designed it in the Graphical Layout.It shows Perfect in the layout.But when I Run the App in the Device it is not showing the 2 green buttons with the Keyboard symbol.It Displays Only the Red Area in the App.
I Already Tested the Layout with another Activity.It works perfect.I think there is a Error in the below class.I can't find where it Happens ???
Nothing is shown in the LogCat...
So Help me in the Right Direction :)
Thanks for your Help ...
Layout Code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<FrameLayout
android:id="#+id/flKeyboardButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#drawable/keyboard_off"
android:maxHeight="100.0dip"
android:maxWidth="60.0dip"
android:minHeight="100.0dip"
android:minWidth="60.0dip" />
<FrameLayout
android:id="#+id/flLeftButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#id/flKeyboardButton"
android:background="#drawable/left_button_off"
android:maxHeight="100.0dip"
android:minHeight="100.0dip" />
<FrameLayout
android:id="#+id/flRightButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_toRightOf="#id/flKeyboardButton"
android:background="#drawable/left_button_off"
android:maxHeight="100.0dip"
android:minHeight="100.0dip" />
<FrameLayout
android:id="#+id/flAdvancedPanel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#drawable/advanced"
android:maxHeight="96dp" >
</FrameLayout>
<FrameLayout
android:id="#+id/flTouchPad"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_above="#id/flKeyboardButton"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#drawable/touchpad" />
<EditText
android:id="#+id/etAdvancedText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="-100dp"
android:inputType="textMultiLine"
android:maxHeight="32dp"
android:visibility="visible" />
</RelativeLayout>
Here is the Java Code
public class PadActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_mouse);
Settings.init(this.getApplicationContext());
// Hide the title bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
if (this.lock == null) {
Context appContext = this.getApplicationContext();
// get wake lock
PowerManager manager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
this.lock = manager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, this.getString(R.string.app_name));
// prepare sensor Listener
this.mSensorListener = new SensorEventListener() {
// #Override
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
int type = sensor.getType();
switch (type) {
case Sensor.TYPE_ACCELEROMETER:
onAccelerometer(event.values);
break;
case Sensor.TYPE_MAGNETIC_FIELD:
onMagnetic(event.values);
break;
// case Sensor.TYPE_ORIENTATION:
// break;
}
}
// #Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// no use for this
}
};
if (useOrientation) {
// enable Sensors
enableSensors();
}
/**
* Caches information and forces WrappedMotionEvent class to load at
* Activity startup (avoid initial lag on touchpad).
*/
this.mIsMultitouchEnabled = WrappedMotionEvent.isMutitouchCapable();
// Setup accelerations
mMouseSensitivityPower = 1 + ((double) Settings.sensitivity) / 100d;
mScrollStep = (sScrollStepMin - sScrollStepMax) * (sScrollMaxSettingsValue - Settings.scrollSensitivity) / sScrollMaxSettingsValue + sScrollStepMax;
Log.d(TAG, "mScrollStep=" + mScrollStep);
Log.d(TAG, "Settings.sensitivity=" + Settings.scrollSensitivity);
//
this.accel = new Point3D();
this.mag = new Point3D();
this.lastSpace = new CoordinateSpace();
this.currSpace = new CoordinateSpace();
// UI runnables
this.rLeftDown = new Runnable() {
public void run() {
drawButtonOn(flLeftButton);
}
};
this.rLeftUp = new Runnable() {
public void run() {
drawButtonOff(flLeftButton);
}
};
this.rRightDown = new Runnable() {
public void run() {
drawButtonOn(flRightButton);
}
};
this.rRightUp = new Runnable() {
public void run() {
drawButtonOff(flRightButton);
}
};
this.rMidDown = new Runnable() {
public void run() {
drawSoftOn();
}
};
this.rMidUp = new Runnable() {
public void run() {
drawSoftOff();
}
};
// window manager stuff
getWindow().setFlags(32, 32);
// this.getWindow().setFlags(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN,
// WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
//
try {
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = getApplicationContext().getResources().getDisplayMetrics().widthPixels;
int height = getApplicationContext().getResources().getDisplayMetrics().heightPixels;
Log.i("Width", "" + width);
Log.i("height", "" + height);
this.sender = new OSCPortOut(InetAddress.getByName(Settings.ip), OSCPort.defaultSCOSCPort());
//
this.initTouchpad();
this.initLeftButton();
this.initRightButton();
this.initMidButton();
this.initAdvancedPanel();
this.initAdvancedText();
} catch (Exception ex) {
Log.d(TAG, ex.toString());
}
}
private void initTouchpad() {
FrameLayout fl = (FrameLayout) this.findViewById(R.id.flTouchPad);
// let's set up a touch listener
fl.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent ev) {
return onMouseMove(ev);
}
});
}
private void initLeftButton() {
FrameLayout fl = (FrameLayout) this.findViewById(R.id.flLeftButton);
android.view.ViewGroup.LayoutParams lp = fl.getLayoutParams();
// if(!Settings.hideMouseButtons) lp.height=0;
fl.setLayoutParams(lp);
// listener
fl.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent ev) {
return onLeftTouch(ev);
}
});
this.flLeftButton = fl;
}
private void initRightButton() {
FrameLayout iv = (FrameLayout) this.findViewById(R.id.flRightButton);
android.view.ViewGroup.LayoutParams lp = iv.getLayoutParams();
// if(!Settings.hideMouseButtons) lp.height=0;
iv.setLayoutParams(lp);
// listener
iv.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent ev) {
return onRightTouch(ev);
}
});
this.flRightButton = iv;
}
private void initMidButton() {
FrameLayout fl = (FrameLayout) this.findViewById(R.id.flKeyboardButton);
android.view.ViewGroup.LayoutParams lp = fl.getLayoutParams();
// if(!Settings.hideMouseButtons) lp.height=0;
fl.setLayoutParams(lp);
// listener
fl.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent ev) {
return onMidTouch(ev);
}
});
this.flMidButton = fl;
}
Its Seems that your java file code is wrong. Your first function should be OnCreate() and rest of the code should be write after that.
Even you have set your view after long code which is totally wrong.
public class PadActivity extends Activity {
// set your variables & objects
..
..
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.pad_layout);
...
... //Other code
}
}
Please change your code position that will definitely work.
#id/flTouchPad's height is match_parent, which I think is the problem (it makes the View as big as its parent).
Atlast I Found why the Layout is not shown Properly in my App.
It is Due to the this line in my three Initialization Methods .
if(!Settings.hideMouseButtons) lp.height=0;
After Commenting this Line the layout shows properly.
Thanks for #chintan khetiya & #Robinhood who helped to Solve this.

How to set Min text (Mandatory) and Max text in EditText

In my EditText field, I want to give some min text as mandatory and max text as the limit, is there any way to achieve that?
If one is to type text, the numeric count has to decrease. How would I do that?
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="24dp"
android:maxLength="175"
android:ems="10" />
this is my adding activity.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_layout);
System.out.println(PRAYER_CATEGORY.length);
tvPrayer = (TextView) findViewById(R.id.mystate);
spinnerPrayers = (Spinner) findViewById(R.id.spinnerstate);
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, PRAYER_CATEGORY);
adapter_state
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerPrayers.setAdapter(adapter_state);
value=(EditText)findViewById(R.id.editText1);
value
.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
if (value.getText().toString().trim()
.length() < 3) {
value.setError("Failed");
} else {
value.setError(null);
}
}
else {
if (value.getText().toString().trim()
.length() < 3) {
value.setError("Failed");
} else {
value.setError(null);
}
}
}
});
btnSpeakprayer = (ImageButton) findViewById(R.id.btnSpeakprayer);
btn=(Button)findViewById(R.id.button1);
pb=(ProgressBar)findViewById(R.id.progressBar1);
pb.setVisibility(View.GONE);
btn.setOnClickListener(this);
You can try this code
First of all you set your maxlength in xml file like this
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:inputType="textPassword"
android:lines="1"
android:maxLength="15"
android:maxLines="1"
android:singleLine="true" />
Then in your code you can write like this
et_billamt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
if (et_billamt.getText().toString().trim().length() < 5) {
et_billamt.setError("Failed");
} else {
// your code here
et_billamt.setError(null);
}
} else {
if (et_billamt.getText().toString().trim().length() < 5) {
et_billamt.setError("Failed");
} else {
// your code here
et_billamt.setError(null);
}
}
}
});
I designed if after no focus, so here you can write for min length condition and max length condition
Change your code TO this:
instead of value.getText().trim().length() try using value.getText().length()<3
value.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
if (value.getText().toString().trim().length() < 3)
value.setError("Failed");
else
value.setError(null);
}
}
});
Try this
EditText value =(EditText) findviewbyId(R.id.urEditTextId);// this line must be oncreate
// place these line where u want to check
String ed1=value .getText().toString();
int size=ed1.length();
you can match the digit and perform appropriate action
if(size==0)
//Toast : kindly enter atleast one letter
if(size>175)
//Toast : max length 175 char
you can extend the EditText class, and override the onTextChanged method to monitor the text length change by yourself. Then you can control the limitation.
public class CustomEditText extends EditText{
public CustomEditText(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
#Override
protected void onTextChanged(CharSequence text, int start,
int lengthBefore, int lengthAfter) {
// TODO Auto-generated method stub
Log.i("length", "input text length = " + text.length());
super.onTextChanged(text, start, lengthBefore, lengthAfter);
}
}
Here's an EditText and a Button:
EditText myEditText;
Button button;
In your onCreate():
myEditText = (EditText) findViewById(R.id.edittext);
button = (Button) findViewById(R.id.button);
Say you submit or use the value that a user types in the myEditText using the button. Set an 'OnClickListener' to this button:
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (mEditText.length() < 1 ||
mEditText.length() > 175) {
mEditText.setError("Value should be between 1 and 175 characters in length");
mEditText.requestFocus();
} else {
// Value is valid (between 1 and 175 characters long)
String text = mEditText.getText().toString();
// submit
}
}
});

Categories

Resources