I have this code but the problem is that this continually showing toast of each string line when I pressed my desired button.
Like this:
Clicked the button once:
Toast shows continually:
A
B
C
What I want is to get string from a single line once I click the button.
Like this:
EditText value:
A
B
C
Result first click:
A only
Result second click:
B only
Result third click:
C only
Like that
Btw this is the code I use:
Button checkButton = (Button) findViewById(R.id.check_Button);
checkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText editBox = (EditText) findViewById(R.id.edit_Text);
String items = editBox.getText().toString();
Scanner scanner = new Scanner(items);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
Toast.makeText(getApplicationContext(), line, Toast.LENGTH_SHORT).show();
}
scanner.close();
}
}
);
I know it's hard to understand but please bare with me.
I think you can go for an approach like this.
int clicks = 0;
Button checkButton = (Button) findViewById(R.id.check_Button);
checkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText editBox = (EditText) findViewById(R.id.edit_Text);
String items = editBox.getText().toString();
if (i == 0) {
Toast.makeText(getApplicationContext(), items , Toast.LENGTH_LONG).show();
i++;
editBox.setText("");
} else if (i == 1) {
Toast.makeText(getApplicationContext(), items , Toast.LENGTH_LONG).show();
i++;
editBox.setText("");
} else if (i==2) {
Toast.makeText(getApplicationContext(), items , Toast.LENGTH_LONG).show();
i = 0;
}
}
}
Just enter a value in the editText when the value is reset after a single button click.
int position=0;
EditText editText=findViewById(R.id.editText);
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable editable) {
}
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
if(charSequence.length()<=0)
{
position=-1;
}
else{
position=0;
}
}
});
Button button=findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
int length=editText.getText().length();
if(position==-1){
Toast.makeText(getApplicationContext(),"Nothing in EditText box",Toast.LENGTH_LONG).show();
return;
}
if(position==length){
position=0;
}
Toast.makeText(getApplicationContext(),editText.getText().charAt(position),Toast.LENGTH_LONG).show();
position++;
}
});
Related
How can I make a button that scrambles the letter every time I click it? When I try to make another button and then click it, it will scramble the letter. Then, when I got another word, when I clicked again on the scramble button, it was back to the first word I answered. (I'm just new. I'm sorry for my code).
public static String wordJumble(String word )
{
Random random = new Random();
char wordArray[] = word.toCharArray();
for(int i=0; i< wordArray.length; i++ )
{
int j = random.nextInt(wordArray.length);
char temp = wordArray[i];
wordArray[i] = wordArray[j];
wordArray[j] = temp;
}
if(wordArray.toString().equals(word)){
wordJumble(word);
}
return new String(wordArray);
}
#Override
protected void onResume() {
super.onResume();
final String [] str=quesWord.toArray(new String[quesWord.size()]);
attemptsLeft.setText("Attempts left: "+chances);
points.setText("Score: "+score);
jumbleWord.setText(wordJumble(str[0]));
b.setOnClickListener(new OnClickListener() {
int j=0;
int len=str.length;
#Override
public void onClick(View v) {
try{
if(answerText.getText().toString().trim().equalsIgnoreCase(str[j])){
score++;
if(score==len){
dbHandler.addScore2("JL",score);
countDownTimer.cancel();
adb.setTitle("You Won!");
adb.setMessage("Score: "+score);
adb.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
adb.show();
}
j++;
points.setText("Score: "+score);
jumbleWord.setText((wordJumble(str[j])));
}
My shuffle Button
shuffle.setOnClickListener(new View.OnClickListener() {
int j=0;
#Override
public void onClick(View v) {
j++;
jumbleWord.setText((wordJumble(str[j])));
}
});
while(i < numCourses){
final int index = i;
//Create a Dialog
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.input_dialog);
TextView textView = (TextView) dialog.findViewById(R.id.textView4);
textView.setText("" + i);
dialog.show();
//Button for the dialog.
Button b = (Button) dialog.findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Get input Course Numbers, numCourses times
EditText editText = (EditText) dialog.findViewById(R.id.editText2); //EditText
String getInput = editText.getText().toString(); //String input
try {
courseNumbers[index] = Integer.parseInt(getInput);
Toast.makeText(MainActivity.this, "" + courseNumbers[index], Toast.LENGTH_SHORT).show();
}catch (Exception ex){}
//Dismiss dialog
dialog.dismiss();
}
});
i++;
}
This is what my variable int = i shows up in the Dialog, suppose numCourses was 4:
3
2
1
0
My question is why is decrementing backwards, instead of incrementing forward from 0 to 3. And to receive an array of inputs from a dialog, how can I efficiently ask for input, numCourses times? Instead of me having a while loop and incrememnting i, which I feel is not efficient.
Not using loop, after each input has been clicked, then show the next dialog.
public void showCourseDialog(final int i, final int numCourses){
final int index = i;
//Create a Dialog
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.input_dialog);
TextView textView = (TextView) dialog.findViewById(R.id.textView4);
textView.setText("" + i);
dialog.show();
//Button for the dialog.
Button b = (Button) dialog.findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Get input Course Numbers, numCourses times
EditText editText = (EditText) dialog.findViewById(R.id.editText2); //EditText
String getInput = editText.getText().toString(); //String input
try {
courseNumbers[index] = Integer.parseInt(getInput);
Toast.makeText(MainActivity.this, "" + courseNumbers[index], Toast.LENGTH_SHORT).show();
}catch (Exception ex){}
//Dismiss dialog
dialog.dismiss();
if(i < numCourses)
showCourseDialog(++i, numCourses);
}
});
}
After declaring and creating the textWatcher object, I would like to disable the send button and set it to gray if the chatText (edit text) is empty
I think it's a problem of ranking. Please help.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
list = (ListView)findViewById(R.id.listView);
list.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
chatText = (EditText)findViewById(R.id.editText);
//chatText.setOnKeyListener(this);
me = true;
send = (Button)findViewById(R.id.button);
change = (Button)findViewById(R.id.button2);
list.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
adp = new TheAdapter(getApplicationContext(),R.layout.chat);
list.setAdapter(adp);
chatText.addTextChangedListener(textWatcher);
checkFieldsForEmptyValues();
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
envoyer();
}
});
change.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
me = !me;
if (!me) {
change.setText(R.string.sender2);
} else {
change.setText(R.string.sender);
}
}
});
}
public void envoyer(){
adp.add(new messages(me, chatText.getText().toString()));
chatText.setText("");
}
private void checkFieldsForEmptyValues(){
String s1 = chatText.getText().toString();
if (s1.length() < 0 ) {
send.setEnabled(false);
} else {
send.setEnabled(true);
send.setBackgroundColor(Color.BLUE);
//send.setBackgroundColor((getResources().getColor(R.color.blue)));
}
}
In the onTextChanged is where you would check to see if the text field is empty:
chatText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 0) { //enable}
else if (s.length() == 0 { //disable }
In your code, you have if (s1.length() < 0 ) which I don't think will ever be true because the text size will never be less than 0.
// Disable on init
send.setEnabled(false);
// add text changer
chatText.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) {
// Enable when input is != null and not empty. You can check string lenght too
send.setEnabled(s != null && !s.toString().isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
}
});
disable button before and add textwatch. You can also check if edittext value is not empty or verify string length.
I hope it will help you
I have an app here which adds the number. I have 4 edittexts here. What I want to happen is that when i entered none in one of the edittexts, it will assume that I entered 0. How can it be done? Here is my code:
public class Order extends Activity {
Button GoBackHome;
private Button button1;
private EditText txtbox1,txtbox2,txtbox3,txtbox4;
private TextView tv;
Button PayNow;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.order);
GoBackHome = (Button) findViewById(R.id.gohomebutton);
PayNow = (Button) findViewById(R.id.button2);
txtbox1= (EditText) findViewById(R.id.editText1);
button1 = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.editText5);
txtbox2= (EditText) findViewById(R.id.editText2);
txtbox3= (EditText) findViewById(R.id.editText3);
txtbox4= (EditText) findViewById(R.id.editText4);
button1.setOnClickListener(new clicker());
GoBackHome.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent i = new Intent(Order.this, MainActivity.class);
startActivity(i);
}
});
PayNow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent i = new Intent(Order.this, Payment.class);
startActivity(i);
}
});
}
class clicker implements Button.OnClickListener
{
public void onClick(View v)
{
String a,b,c,d;
Integer vis;
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
c = txtbox3.getText().toString();
d = txtbox4.getText().toString();
vis = Integer.parseInt(a)*2+Integer.parseInt(b)*3+Integer.parseInt(c)*4+Integer.parseInt(d)*5;
tv.setText(vis.toString());
}
}
}
You can do as Tushar said or you can initialize the value in the XML. Something like
<EditText
android:name="#+id/editText1"
android:text="0"/>
FYI you might also find it cleaner to handle your button clicks on xml like:
<Button
android:name="#+id/btn1"
android:onClick="handleClicks"/>
and then in java you'd have a public void method:
public void handleClicks(View clickedView){
if(clickedView.getId() == btn1.getId(){
...
} else if (...){}
}
initialize as :
txtbox1.setText("0");
Check the EditText length when you get it
String value = null;
if(ed.getText().length()){
value = textBox.getText().toString();
} else
value = 0+"";
You can set android:hint="0" in your XML file, then, in your code, you can check if it's empty (maybe using TextUtils.isEmpty()) and setting some variable to 0.
android:hint="0" will make a "0" appear in your EditTexts, but the "0" will disappear when anything is inputted.
Then you can change the onClick() to this:
class clicker implements Button.OnClickListener {
public void onClick(View v) {
String a,b,c,d;
Integer vis;
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
c = txtbox3.getText().toString();
d = txtbox4.getText().toString();
try {
vis = Integer.parseInt(a)*2+Integer.parseInt(b)*3+Integer.parseInt(c)*4+Integer.parseInt(d)*5;
tv.setText(vis.toString());
} catch (NumberFormatException e) {
vis = "0";
}
// Do something with "vis"
}
}
Or you can create a method to check a value, try to parse to an int or return a default value.
public int getInt(String edtValue, int defaultValue) {
int value = defaultValue;
if (edtValue != null) {
try {
value = Integer.parseInt(edtValue);
} catch (NumberFormatException e) {
value = defaultValue;
}
}
return value;
}
Then you change your call to
vis = this.getInt(a, 0) * 2 + this.getInt(b, 0) * 3 + this.getInt(c, 0) * 4 + this.getInt(d, 0) * 5;
Ok so i have the following situation : I create some Editexts dynamically and i want to add another row of Editexts when one of the EditTexts from the last row is clicked.
I tried doing it the following way :
When the last row of EditTexts is created,i assign each of them an id
et.setId(997);
et.setId(998);
et.setId(999);
I declared each of them ;
public EditText camp1;
public EditText camp2;
public EditText camp3;
camp1 = (EditText) findViewById(997);
camp2 = (EditText) findViewById(998);
camp3 = (EditText) findViewById(999);
camp1.setOnClickListener(this);
camp2.setOnClickListener(this);
camp3.setOnClickListener(this);
And when i try to do this
case R.id.camp1:
inside a switch i get "camp1 cannot be resolved or is not a field"
What am i doing wrong ?
Is there a better way to detect when the last Edittext is clicked and create a new one ?
EDIT:
public class MainActivity extends Activity implements OnClickListener,
TextWatcher {
public Button paginanoua;
// public Button calculeaza;
public Button produsnou;
public EditText camp1;
public EditText camp2;
public EditText camp3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
produsnou();
paginanoua = (Button) findViewById(R.id.paginanoua);
// calculeaza = (Button) findViewById(R.id.calculeaza);
produsnou = (Button) findViewById(R.id.produsnou);
camp1 = (EditText) findViewById(997);
camp2 = (EditText) findViewById(998);
camp3 = (EditText) findViewById(999);
paginanoua.setOnClickListener(this);
// calculeaza.setOnClickListener(this);
produsnou.setOnClickListener(this);
camp1.setOnClickListener(this);
camp2.setOnClickListener(this);
camp3.setOnClickListener(this);
}
public void onClick(View view) {
switch(view.getId())
{
case R.id.paginanoua:
ShowDialog();
case R.id.produsnou:
produsnou();
case R.id.997:///error
produsnou();
}
}
private void ShowDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Pagina noua..");
dialogBuilder.setMessage("Sigur doriti o pagina noua?");
dialogBuilder.setPositiveButton("Da",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),
"Am inceput o lista noua", Toast.LENGTH_SHORT)
.show();
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
dialogBuilder.setNegativeButton("Nu",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),
"Ramanem la lista curenta", Toast.LENGTH_SHORT)
.show();
}
});
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
}
List<EditText> allpret = new ArrayList<EditText>();
List<EditText> allcant = new ArrayList<EditText>();
List<Float> alltotal = new ArrayList<Float>();
float totaltest = 0;
public void produsnou() {
LinearLayout l1 = (LinearLayout) findViewById(R.id.layout1);
EditText et = new EditText(this);
et.setHint("Produs");
l1.addView(et);
et.addTextChangedListener(this);
et.setId(997);
LinearLayout l2 = (LinearLayout) findViewById(R.id.layout2);
EditText et2 = new EditText(this);
et2.setHint("Cantitate");
et2.setInputType(InputType.TYPE_CLASS_NUMBER
| InputType.TYPE_NUMBER_FLAG_DECIMAL);
et2.setId(998);
allcant.add(et2);
l2.addView(et2);
et2.addTextChangedListener(this);
LinearLayout l3 = (LinearLayout) findViewById(R.id.layout3);
EditText et3 = new EditText(this);
et3.setHint("Pret");
et3.setInputType(InputType.TYPE_CLASS_NUMBER
| InputType.TYPE_NUMBER_FLAG_DECIMAL);
l3.addView(et3);
et3.setId(999);
allpret.add(et3);
et3.addTextChangedListener(this);
}
float temp = 0;
public void calculeaza() {
totaltest = 0;
String[] cant = new String[allcant.size()];
for (int j = 0; j < allcant.size(); j++) {
cant[j] = allcant.get(j).getText().toString();
if (cant[j].matches("")) {
Toast.makeText(this,
"Ati omis cantitatea de pe pozitia " + (j + 1),
Toast.LENGTH_SHORT).show();
cant[j] = Float.toString(0);
}
}
String[] pret = new String[allcant.size()];
for (int k = 0; k < allpret.size(); k++) {
pret[k] = allpret.get(k).getText().toString();
if (pret[k].matches("")) {
Toast.makeText(this,
"Ati omis pretul de pe pozitia " + (k + 1),
Toast.LENGTH_SHORT).show();
pret[k] = Float.toString(0);
}
}
for (int l = 0; l < allpret.size(); l++) {
Float temp = Float.parseFloat(cant[l]) * Float.parseFloat(pret[l]);
alltotal.add(temp);
totaltest = totaltest + temp;
// totaluri[l] = temp ; }
TextView totalf = (TextView) findViewById(R.id.total);
totalf.setText(String.format("Total: %.2f", totaltest));
}
}
// Float[] totaluri = new Float[allcant.size()];
public void reload(View v) {
Intent intent = getIntent();
finish();
startActivity(intent);
calculeaza();
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
calculeaza();
}
}
All you care about is the last editText, right? Just give the last editText an onClickListener that creates another editText. Then give the new editText the onClickListener and remove it from the the previous "last one".
like this:
camp1 = (EditText) findViewById(997);
camp2 = (EditText) findViewById(998);
camp3 = (EditText) findViewById(999);
camp1.setOnClickListener(this);
camp2.setOnClickListener(this);
camp3.setOnClickListener(new myListener());
...
//put this private class in the same activity as the stuff above
private class myListener implements View.OnClickListener {
#Override
public void onClick(View view) {
EditText editText = new EditText(YourActivityName.this);
editText.setOnClickListener(new myListener());
//TODO put it in your viewGroup
//Give the old EditText your standard onClickListener
view.setOnClickListener(YourActivityName.this);
//To change body of implemented methods use File | Settings | File Templates.
}
}
setId() does not add any variables to the R.id class because setId() executes at run-time, but R is generated at compile-time. Since you are creating dynamic views, you need to rethink your onClick() method. You might want to consider using a ListView to help you. You can also set up the three TextViews using a separate XML file, such as row.xml.