I am using an Adapter to generate buttons in a GridView.
Using an OnClickListener, whenever I click a button from the GridView, it is possible to get the String of the button in a variable. However, I want to click a button, store its text in a variable, then click a different button, store its text in another variable so later I can compare the two texts. How could I do that?
gI'm using OnClickListener, therefore my previous implementation for one button was the following:
public void onClick(View v) {
Button b = (Button)v;
String text = b.getText.toString();
With this approach, I can only get and store text from first button clicked, unless I store all the values in an array.
Ok so from what I can understand, you want to compare the strings of the two items in a grid view. If this is what you want, heres how I would do it(just a psuedocode):
String mValue1, mValue2;
boolean isOneClicked = false;
onItemClickedListener(item, position){
if(!isOneClicked){
mValue1 = item.stringValue;
isOneClicked = true;
}
else{
mValue2 = item.stringValue;
//do whatever you want here
//Reset when done
mValue1 = "";
mValue2 = "";
isOneClicked = false;
}
}
Please you can share your code to turn the things more comprehensible? Edit your question please... Anyways:
MainActivity.java
public class MainActivity extends Activity {
private Button button1;
private Button button2;
private String butString, butString2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
butString = (String) button1.getText();
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
butString2 = (String) button1.getText();
}
});
}
}
After that you can compare the two strings.
Related
In my Android activity, I have one EditText, a '+' button, a '-' button, 'Save' button and 'Load' button. When I press '+', the value in EditText increases by 1, similarly on pressing '-' value decreases by 1. I used SharedPreferences to save the data when I click on 'Save'. When I click 'Load', I want to reload this data onto the EditText field.
Now the problem is, when I completely exit the application (even from recently used apps), and click 'Load' on relaunching it, the saved number doesn't appear. I included the onClick() action for the 'Load' method in onRestart() method. It still doesn't work. What am I missing here? I even tried out all other suggestions for the similar questions asked previously here.
Also, is it really onRestart() or onRestoreInstanceState() ?
public class MainActivity extends Activity {
Button btn1;
Button btn2;
Button btn3;
Button btn4;
EditText scoreText;
int counter = 0;
TextView textTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button)findViewById(R.id.add);
btn2 = (Button)findViewById(R.id.subtract);
btn3 = (Button)findViewById(R.id.save);
btn4 = (Button)findViewById(R.id.load);
scoreText = (EditText)findViewById(R.id.total);
textTitle = (TextView)findViewById(R.id.title);
btn1.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
counter++;
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.GREEN);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
counter=counter-1;
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.RED);
}
});
btn3.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
//store data using sharedprefernces
SharedPreferences sharedPreferences=getSharedPreferences("Data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
//Edit method allow to write the data in sharedpreferences
editor.putString("count",scoreText.getText().toString());
//For commit changes commit() method is used
editor.commit();
Toast.makeText(getApplicationContext(),"Data Saved",Toast.LENGTH_SHORT).show();
}
});
btn4.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences=getSharedPreferences("Data", Context.MODE_PRIVATE);
String strcount=sharedPreferences.getString("name",scoreText.getText().toString());
// scoreText.setText(strcount);
scoreText.setBackgroundColor(Color.YELLOW);
}
});
}
#Override
protected void onRestart(Bundle savedInstanceState){
super.onRestart(savedInstanceState);
btn4.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences=getSharedPreferences("Data", Context.MODE_PRIVATE);
String strcount=sharedPreferences.getString("name",scoreText.getText().toString());
if (strcount.equals(""))
{
Toast.makeText(getApplicationContext(), "Data Was Not Found", Toast.LENGTH_SHORT).show();
}
else
{
scoreText.setText(strcount);
}
scoreText.setBackgroundColor(Color.YELLOW);
}
});
}
You using using count as key to save the value
editor.putString("count",scoreText.getText().toString());
but using name as key to retrieve the value so you need to use count key while getting the previously stored data so use
sharedPreferences.getString("count",scoreText.getText().toString());
instead of
sharedPreferences.getString("name",scoreText.getText().toString());
You are using different keys to save and retrieve the data from SharedPrefernces.
editor.putString("count",scoreText.getText().toString());
String strcount=sharedPreferences.getString("name",scoreText.getText().toString());
You should be using the same key in both the cases otherwise it would return default value which is the text in TextView and that would be empty at the start of the app, you just need to change the key and that would do the trick for you.
Just change the below line like it is mentioned
String strcount=sharedPreferences.getString("count",scoreText.getText().toString());
I am trying to make an app and I have the code for a button inside of a different class. When I start my app and click the first button it brings me to a different layout where the button is located. But when I click this button it doesn't do anything, just the little click down animation.
First Button Code:
public class TextAdd extends AppCompatActivity {
public static EditText Text;
public static Button Set;
public static String[] Checkagainst = new String[1000];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.Text_Checker);
Text = (EditText) findViewById(R.id.LPN);
Set = (Button) findViewById(R.id.Set);
Set.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Text_Value = Text.getText().toString();
if (!Arrays.asList(Checkagainst).contains(Text_Value) && Text_Value.length() >= 1 && Text_Value.length() <= 7) {
setContentView(R.layout.add);
for (int i = 0; i < Checkagainst.length; i++) {
if (Checkagainst[i] == null) {
Checkagainst[i] = Text_Value;
break;
}
}
} else if (Arrays.asList(Checkagainst).contains(Text_Value) && Text_Value.length() >= 1 && Text_Value.length() <= 7) {
setContentView(R.layout.have);
}
}
});
}
}
Second Button Code:
public class Have extends AppCompatActivity {
private Button HaveBack;
private TextView Have;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.have);
HaveBack = (Button) findViewById(R.id.HaveBack);
Have= (TextView) findViewById(R.id.Have);
String Text_Value= TextAdd.License.getText().toString();
String Extra = Text_Value + " is already part of Your license plates";
Have.setText(Extra);
HaveBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.Text_Checker);
}
});
}
}
Does anyone know what is wrong? If so can you please help me.
You should use setContentView() only once in your onCreate() method. Calling it multiple times is not correct. If you want to show a small layout above your current layout, you should use a Dialog and if you want to show a completely different layout above everything, you have to use Intents to go to another activity and do the rest of the work in that one.
besides, use lowercase letters at start of your variables' and objects' names and start Class names with Uppercase letters. That's the standard for knowing what is a class and what is an object. e.g.
Button firstButton, secondButton;
i am new to development. i am creating an android calculator app with advanced functionality.The thing is i am using text view for taking and displaying inputs/outputs. My question is, how can i take Multiple inputs in multiple Textviews.
For example i have 3 text views,when user will enter 1st input in first textview(by default) and when user press the specific button it moves automatically to next textview . In some cases i want to take 2 inputs and in some cases i want to take 3 ,
How can i achieve this
Note: I dont want to use edit text , coz all buttons of already available in my app.Using Edit text will make softkeyboard to appear, and then for hiding the softkeyboard, i need to use hiding code lines in every class
You can do something like following:
private TextView[] textViews;
private TextView tvCurrentEditing;
private Button btnNext;
private Button btnPrev;
private Button btnSetText;
private int index = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
textViews = new TextView[3];
//Initialize all your textviews like textViews[0] = findViewById(<textview-id1>);
//textViews[1] = findViewById(<textview-id2>);
//textViews[2] = findViewById(<textview-id3>);
tvCurrentEditing = textViews[index];// I am assuming this is your first
//initialzie btnSettext
btnSettext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvCurrentEditing.setText("<what ever you want");
}
});
//initialize next buton
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(index < textViews.length) {
index++;
}
tvCurrentEditing = textViews[index];
}
});
//Initialize previous button
btnPrev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(index > 0) {
index--;
}
tvCurrentEditing = textViews[index];
}
});
}
The names of the views could be different. The point is always use tvCurrentEditing whenever you want to change data of TextView. And update tvCurrentEditing whenever needed.
I may be going about this all wrong, but I have a view that contains a few ToggleButtons and a Save button. When the Save button is pressed, I want to collect the states of the various toggles as boolean values. I have tried the following in the onClickHandler for the Save button:
ToggleButton tb = (ToggleButton) findViewById(R.id.button1);
boolean pol = tb.isChecked();
and I would expect pol to be set to the state of button1, but it keeps being set to true. Of course I have tried this with the button in both states.
Thanks
you can try this
ToggleButton tb = (ToggleButton) findViewById(R.id.button1);
boolean pol = false;
tb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(tb.isChecked()) {
pol = true;
} else {
pol = false;
}
}
});
}
I'm new to Java (coming from Python) and I'm trying to pass a method as a parameter in order to convert this code:
Button button1;
Button button2;
...
Button buttonN;
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick_button1(v);
}
});
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick_button2(v);
}
});
(...)
buttonN = (...)
To something like:
public AssignListener( integer tButton, Method tMethod )
{
button_view = (Button) findViewById(tButton);
button_view.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
tMethod(view);
}
}
}
(...)
AssignListener( R.id.button1, onClick_button1 );
AssignListener( R.id.button2, onClick_button2 );
(...)
AssignListener( R.id.buttonN, onClick_buttonN );
I've read that you can't pass methods to functions, and some advice to wrap my function using Runnable to achieve this.
I have not clear idea about how to do it. Any idea on how do it easily? :?
Thanks.
EDIT: Should I wrap "AssignListener" in its own class and pass the class itself? :?
You can call findViewById() and seOnClickListener into onCreate method, and OnClickListenet outside the onCreate.
Button button1 = (Button)findViewById(R.id.button1);
or
findViewById(R.id.button1).seOnClickListener(mClickListener);
findViewById(R.id.button2).seOnClickListener(mClickListener);
findViewById(R.id.button3).seOnClickListener(mClickListener);
findViewById(R.id.button4).seOnClickListener(mClickListener);
private OnClickListener mClickListener = new View.OnClickListener(
public void onClick(View view){
switch(view.getId()){
case R.id.button1:
//button1 click handle here...
break;
case R.id.button2:
//button2 click handle here...
break;
case R.id.button3:
//button3 click handle here...
break;
case R.id.button4:
//button4 click handle here...
break;
}
});
Try it, hope it will helpful to you.
You could define and pass an onClickListener like this:
public AssignListener( integer tButton, OnClickListener listener ){
tButton.setOnClickListener(listener);
}
The simplest way is to create listener implementation for each button, as is written in your first snippet.
I don't see any reasonable benefit of having universal method like AssignListener(). Don't reinvent bicycle, use existing setOnClickListener() method and pass listener specific for button.
An easy solution would be to create a function called tMethod that takes a button id, and has a switch statement that allows for a certain action to be performed for the given button id. This would then be called inside the onClick function like tMethod(view.getId()).
Btw, Python has methods. Java has functions. Pedant mode turned off!
public class MyClass implements OnClickListener, OnLongClickListener {
Button button1;
Button button2;
...
Button buttonN;
. . .
setButtonsListener(findViewById(<your top view id>));
. . .
void setButtonsListener(ViewGroup vg) {
int count = vg.getChildCount();
Button btn;
View v;
for(int i=0; i < count ; i++) {
v = vg.getChildAt(i);
if( v instanceof Button ) {
btn = (Button)v;
btn.setOnClickListener(this);
btn.setOnLongClickListener(this);
} else if( v instanceof ViewGroup ) {
setButtonsListener((ViewGroup) v);
}
}
}
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}