Two spinners change text in TextView - java

I'm trying to make this android app and I have some problems. I want to pick a card number in my left spinner, and in the right spinner is my dealers hand, and I pick a card number there aswell.(see Image below)
I can change my cards and the image updates no problem. But when I pick ex 17 and 2, how do I change the text in my Textview? I have a TextView, but cleared the text.
I tried this, but it doesn't work
if(plHand.equals("8") && dlHand.equals("2") || dlHand.equals("3")){
Toast.makeText(this, "IT WORKS!", Toast.LENGTH_LONG).show();
}
I made a Toast just to check if something happens. But nothing happens. But how do I do it? plHand and dlHand is a String Array. I also tried this
if(sp1.getSelectedItem().toString().equals("17") && (sp2).getSelectedItem().toString().equals("Ace"){
Toast.makeText(MainActivity.this, "IT WORKS!", Toast.LENGTH_LONG).show();
}
Hope you guys know what to do!
EDIT: added more code
final String[] plHand = getResources().getStringArray(R.array.yourHand_array);
final String[] dlHand = getResources().getStringArray(R.array.dealerHand_array);
final Spinner sp1 = (Spinner) findViewById(R.id.spinner1);
final Spinner sp2 = (Spinner) findViewById(R.id.spinner2);
The text I want to change is in a String Array aswell, but I don't have to use the String Array, if there is an easier way!
EDIT!!: It works now! Full code is here! http://pastebin.com/g3M2wbtL

Just attach the same OnItemSelectedListener to both spinners like the following:
AdapterView.OnItemSelectedListener listener = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String plHandText = sp1.getSelectedItem().toString();
String dlHandText = sp2.getSelectedItem().toString();
if ("17".equals(plHandText) && "2".equals(dlHandText)){
Toast.makeText(MyActivity.this, "It works!", Toast.LENGTH_LONG).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
sp1.setOnItemSelectedListener(listener);
sp2.setOnItemSelectedListener(listener);

Related

Get spinner selected item and passing data

What I want to do is set the texts depends on the spinner item selected by users. But there is nothing that showed up when running the app and there is no errors either. Did I miss any steps that cause the outcome didn't come out?? I'm still new to android.
UPDATE:
I forgot to say that I have three different spinners depending on which button users liked in 1st activity so I think its because I only declare for the spinner's item but didn't declare which spinner is "Japan" referring to.
So this is my code for 1st activity, I will just put only one first :
btnAsia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),MainActivity2.class);
intent.putExtra("continent", "asia");
startActivity(intent);
}
});
This is the string array in strings.xml:
<string-array name="asia">
<item>Japan</item>
<item>Thailand</item>
<item>Vietnam</item>
<item>South Korea</item>
</string-array>
and this is the code in 2nd activity:
private void DestinationSpinner()
{
Bundle bundle=getIntent().getExtras();
if(bundle!=null) {
String continent = bundle.getString("continent");
switch (continent) {
case "asia":
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(MainActivity2.this, R.array.asia, android.R.layout.simple_spinner_item); // Create an ArrayAdapter using the string array and a default spinner layout
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Specify the layout to use when the list of choices appears
spinnerDestination.setAdapter(adapter); // Apply the adapter to the spinner
break; }
and lastly this is the code for retrieve selected item from spinner:
public void AvailableAirlines()
{
spinnerDestination.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected=spinnerDestination.getItemAtPosition(position).toString();
if (continent.equals("asia") && selected.equals("Japan"))
{
availableAirlines.setText("Available airports");
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
and I also want to pass the keyidentifer from 1st activity to 2nd activity but I tried using getExtras and it didn't work maybe I do it wrongly or what.
I think the issue is this line if(selected=="Japan")
In Java you will need to use equals instead of the == operator.
The == checks if the two pointers are pointing to the same memory location.
Equals will compare their content.

Set Background Color of a List Item if it is Clicked

I want to change the background color of the List Item depending on whether the item is clicked or not. How can I achieve this! I did tried the following:
articleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// Find the current article that was clicked on
Article currentArticle = mAdapter.getItem(position);
if (currentArticle.getUrl() != null) {
TextView article_TV = (TextView) findViewById(R.id.post_title);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
article_TV.setBackgroundColor(getApplicationContext().getColor(R.color.colorItemClicked));
}
else
article_TV.setBackgroundColor(getResources().getColor(R.color.colorItemClicked));
}
}
});
Update :-
Silly mistake it was. As suggested by ak sacha should be
TextView article_TV = (TextView) view.findViewById(R.id.post_title);
As suggested by ak sacha we can achieve it simply by using
TextView article_TV = (TextView) view.findViewById(R.id.post_title);
This is because we are using that in a adapter, so we need to find the view within listview row.Hence we use view.findviewbyid

Android Java - Dropdown spinner sets the same text always, only want to change background color

I have 2 dropdown spinners that I would like to be color coded. I would like 1 to always be labeled as Apple and the other to be Banana. I'm using the dropdown menu to change the background color of the spinner. How do I set the text to always stay as Apple and Banana, but only have the background color of the spinner change based on what is selected? Whenever I use the dropdown to select a color, it changes the text to the color I selected. I feel like I would need a setText function somewhere...
Here is my code so far:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dropdown1 = (Spinner)findViewById(R.id.spinner1);
dropdown2 = (Spinner)findViewById(R.id.spinner2);
String[] colors = new String []{"red", "blue", "green"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, colors);
dropdown1.setAdapter(adapter);
dropdown2.setAdapter(adapter);
dropdown1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
text1 = dropdown1.getSelectedItem().toString();
if (text1.equals("red")) {
dropdown1.setBackgroundColor(Color.parseColor("#ff0000"));
} else if (text1.equals("green")) {
dropdown1.setBackgroundColor(Color.parseColor("#00ff00"));
} else if (text1.equals("blue")) {
dropdown1.setBackgroundColor(Color.parseColor("#0000ff"));
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
Add below code,
dropdown1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
text1 = dropdown1.getSelectedItem().toString();
if (text1.equals("red")) {
dropdown1.setBackgroundColor(Color.parseColor("#ff0000"));
adapter.notifyDataSetChanged();
} else if (text1.equals("green")) {
dropdown1.setBackgroundColor(Color.parseColor("#00ff00"));
adapter.notifyDataSetChanged();
} else if (text1.equals("blue")) {
dropdown1.setBackgroundColor(Color.parseColor("#0000ff"));
adapter.notifyDataSetChanged();
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
I hope I understood your question properly. Right now,
String[] colors = new String []{"red", "blue", "green"};
Is the spinner text, so you want to change it to:
String[] colors = new String []{ "Apple", "Apple", "Apple" };
Next, instead of
text1 = dropdown1.getSelectedItem().toString();
change it to:
int color = dropdown1.getSelectedItemPosition();
I recommend using constants or enums for the colors you would like.
I think there are better solutions (not using a spinner), but without context hopefully this is what you're looking for.
Note that the selected item is already passed as a parameter to onItemSelected(), so there is no need to call getSelectedItem(). Secondly, the selected item is a View, so calling toString() on it gives a text representation of the View object. This is not the same as the text which is displayed the view. Instead, you need to call getText(). Putting this all together means you should change
text1 = dropdown1.getSelectedItem().toString();
to
String text = selectedItemView.getText().toString()

Android Spinner Doesn't Return Id Properly

I'm having a difficulty in spinner android, more specifically in the data saving part.
First, I'm going to tell you what is the purpose behind the code below.
I want to create a spinner that user can choose which planet to buy, then when he/she hits the submit button, a toast will appear saying "You wanted to buy: ...." then followed by a purchase summary like username & price.
However, in the middle of the process I'm having a hard time to save the id of each spinner's element.
Every time I chose "Earth" (id= 1) & hit submit, the toast will always refer back to "Mars" which has id = 0. So it seems that the problem is my submit button will always reset the chosen id.
I intentionally set planetSpinner() method to return int, thus I could always track down the "id" being returned. But again, the submit button would always make it shows to id = 0.
Can anyone help me? I would really appreciate that. Thank you.
Spinner Code (MainActivity.java)
public int planetSpinner(){
context = this;
List<String> categories = new ArrayList<String>();
categories.add("Mars($12 billions)"); //0
categories.add("Earth ($99 billions)"); //1
categories.add("Jupiter ($13 billions)"); //2
cSpinner = (Spinner) findViewById(R.id.coffee_spinner);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cSpinner.setAdapter(dataAdapter);
cSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "You selected: " + cSpinner.getItemAtPosition(position), Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(MainActivity.this, "Nothing selected", Toast.LENGTH_LONG).show();
}
});
return cSpinner.getSelectedItemPosition();
}
Submit Purchase Code (MainActivity.java)
public void submitOrder(View view){
Toast.makeText(MainActivity.this, "You wanted to buy: " + planetSpinner(), Toast.LENGTH_LONG).show();
displayMessage(confirmationOrder(userName, price));
}
public class MySpinner extends Activity implements OnItemSelectedListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.coffee_spinner);
spinner.setOnItemSelectedListener(this);
List<String> categories = new ArrayList<String>();
categories.add("Mars($12 billions)"); //0
categories.add("Earth ($99 billions)"); //1
categories.add("Jupiter ($13 billions)"); //2
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Have you try this:
Toast.makeText(MainActivity.this, "You selected: " + categories.get(position), Toast.LENGTH_LONG).show();
It is because the spinner was reinitialized everytime you call the function. Thus, the selected value was the first item, that is why your function always returns 0. Hope that helps.

How to output text result in Android?

In an android website, I found an article about a widget similar to a drop-down list for selecting items. (Following is the link to the site; and it shows all the codes).
http://developer.android.com/resources/tutorials/views/hello-spinner.html
It uses the following code to display a message once you have selected a planet.
Toast.makeText(parent.getContext(), "Planet is Selected", Toast.LENGTH_LONG).show();
But this message "Planet is Selected" is only going to display for about 3 seconds and then it disappears. Can you please tell me how can I make the message stay on the screen for a longer time. Or how can I output the "Planet is Selected" message as a text layout in to the screen(So that it will stay on the screen permanently till I select another item from the list)? How can I use addView(tv) instead of setContentView(tv) Any help would be greatly appreciated.
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
if (parent.getItemAtPosition(pos).toString().equals("Mars"))
{ TextView tv = new TextView(HelloSpinner.this);
tv.setText(parent.getItemAtPosition(pos).toString() + "Planet is Selected");
setContentView(tv); //How can I use addView(tv); here?
//Toast.makeText(parent.getContext(), "Planet Selected", Toast.LENGTH_LONG).show();
}
}
public void onNothingSelected(AdapterView parent)
{
// Do nothing.
} }
If you want it to stay permanently on the screen, why not use a TextView and set your value to that instead of a Toast.
If you have any problems with not being able to use TextView, ie undefined. You should take a look at the textview documentation, as it is very well described there.
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
TextView tv = new TextView(this);
tv.setText(parent.getItemAtPosition(pos).toString());
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
third parameter Toast.LENGTH_LONG is time. so you can set any integer value ( not sure second or millisecond) ,. then on specific event call toast.hide() ;
toast is good choice for show message for some times only . so use textView if possible
create TextView with activity context :
TextView tv = new TextView(ActrivityName.this)
else if not an activity
TextView tv = new TextView(parent.getContext())

Categories

Resources