refresh and alter layout on click of checkbox - java

I didn't really know how to phrase this.
Basically I have this method:
private void uploadFile(int maxSpinner) {
setContentView(R.layout.upload);
CheckBox local = (CheckBox) findViewById(R.id.local_checkbox);
Spinner dropdown = (Spinner)findViewById(R.id.spinner1);
local.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkbox = isChecked;
if( isChecked){
uploadFile(6);
Log.i("checked", "yes");
}
else {
uploadFile(5);
Log.i("checked", "no");
}
}
});
ArrayList<String> categories = new ArrayList<>();
for( int category = 1; category <= maxSpinner+1; category++){
categories.add(Integer.toString(category));
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, categories);
dropdown.setAdapter(adapter);
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
category = arg2+1;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
The corresponding layout file has a checkbox and a spinner.
maxSpinner is the limit for the for-loop that sets the amount of Spinner elements. I want to change maxSpinner depending on whether the checkbox gets selected or not.
So in the beginning uploadFile() gets called elsewhere with 5 as the argument. When I click the checkbox local I want to call uploadFile again, but this time with either 6 or again 5 as an argument, so I get a different amount of elements for the spinner.
The way I tried it is seen above. Nothing happens when I click the checkbox, I can see in the log it always logs "yes", even though the checkbox never actually gets visibly checked.
any help would be appreciated,
thanks

sorry, it does work just as expected, it just doesn't update the checkbox because I'm not telling it to do so.

Related

How to set selected item for Spinner in Android

In an Android app, I have a SpinnerAdapter that I am using to display expiration years of credit cards. My variable expirationYears contains an array of Strings with years from "2020" to "2029". It was declared as String[] expirationYears = new String[10]; and then with a function I set the ten years as Strings, from current year and then the nine subsequent years after that for a total of ten elements in the array. When I run it, this is what I see:
Everything is perfect so far. The only problem is that when as you see in the image above, 2020 is the year selected by default. That is the first element in the expirationYears array. But I want to set 2021 as default (the second element of the array). This is what my code has:
Spinner spinnerYearCreditCardPayment;
SpinnerAdapter creditCardYearAdapter = new SpinnerAdapter(Payment.this, expirationYears);
creditCardYearAdapter
.setDropDownViewResource(android.R.layout.spinner_dropdown_item);
spinnerYearCreditCardPayment.setAdapter(creditCardYearAdapter);
spinnerYearCreditCardPayment
.setOnItemSelectedListener(new OnItemSelectedListener() {
..........
});
I was expecting to have some property available to define which element I want to show by default. Something like creditCardYearAdapter.setSelectedItem(INDEX_NUMBER). But that property does not exist. Do you know how I could set the default selected item so that it is not the first element of the array (2020) but the second (2021)? Thank you.
UPDATE 1:
Following The_Martian's answer, this was what I did:
spinnerYearCreditCardPayment
.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
arg0.setSelection(1);
cardYear = (String) spinnerYearCreditCardPayment
.getSelectedItem();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Now I correctly see the second element of the array ("2021") as the default selection.
The problem is that when I use arg0.setSelection(1);, I choose another year and it does not respond. The selected year remains "2021" even thought I am trying to change the year.
You can do similar to the following. I am just giving you an idea here.
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
parent.setSelection(position + 1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Try this snippet
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
int seleccion=parent.getSelectedItemPosition();
spinner.setSelection(position)
});
}
You can select the spinner item based on value instead of position. Can refer the example below-
String value = "to be selected value";
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.select_state, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
if (value != null) {
int spinnerPosition = adapter.getPosition(value);
mSpinner.setSelection(spinnerPosition);
}

How to setText in selected textView

Needed some help here. In my map test app I have 2 Autocomplete textViews. First textView gets the address of marker on load as well as chages the address if map is dragged.
But I am struggling for second textView where I need the same feature depending which textView is active.
I tried it like:
private AutoCompleteTextView mFromAddress;
private AutoCompleteTextView mToAddress;
mFromAddress = (AutoCompleteTextView) findViewById(R.id.fromAddress);
mToAddress = (AutoCompleteTextView) findViewById(R.id.toAddress);
// Decoder Coding.. str prints address
if (mFromAddress.isSelected()) {
mFromAddress.setText(str);
} else if (mToAddress.isSelected()) {
mToAddress.setText(str);
}
But no expected results. Even the first textView stops working.
I am new to java and Android Studio. I am looking for some suggestions here.
Try hasFocus() function
if (mFromAddress.hasFocus()) {
mFromAddress.setText(str);
} else if (mToAddress.hasFocus()) {
mToAddress.setText(str);
}
Another way is that define another TextView in code and set it as active TextView when focus change in OnFocusChangeListener
AutoCompleteTextView activeET;
activeET = mFromAddress; // set mFromAddress as active text in start
mFromAddress.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean hasFocus) {
if(hasFocus)
activeET = mFromAddress;
}
});
mToAddress.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean hasFocus) {
if(hasFocus)
activeET = mToAddress;
}
});
Now you just need to set text to activeET
activeET.setText(str);

Android spinner location not updating

I have a spinner that populated with a string array. The spinner is populated when a button is pressed. the output is always game_0 even if I use the spinner and select say game_3. Is this because it's in a function?
public void game(View view) throws IOException {
myText="";
TextView myTextView= (TextView)findViewById(R.id.textView1);
String game_list[] = {"game_0","game_2","game_3","game_3","game_4","game_5"};
for(int i=0; i<game_list.length; i++){
myText = myText + game_list[i] +"\n";
}
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_item, game_list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
String text = spinner.getSelectedItem().toString();
myTextView.setText("");
myTextView.append(text);
}
When are you calling your game(View v) method? There's no space for user action between the spinner initialization spinner.setAdapter(adapter); and the line that extract the selected value which is obviously (by default) the first of the array..."game_0".
You can use an OnItemSelectedListener to listen for user action on the spinner, or use a button with a click listener to check the spinner value upon submit.
Here's an example of a selected listener applied to a spinner:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// here get the selected value and do whatever you want
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// ignore this if you're not going to provide a "no-selection" option
}
});

how to change the string array of a spinner at runtimeHow to use the selected item of a spinner in an if statement (Android in eclipse)

Hi I have a spinner (spinner1) and when the user selects an item from it (example: "Canada" I want the spinner2 to populate with Provinces of "canada". I have tried the following but it doesnt work. I tried to do this by using:
if (spinner1.getSelectedItem().toString().equals("Canada"))
{
addItemsOnSpinner2();
}
public void addItemsOnSpinner2() {
spinner2 = (Spinner) findViewById(R.id.spinner2);
List list = new ArrayList();
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
list.add("Item 4");
ArrayAdapter dataAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
}
for some reason the items aren't being added to spinner2. please help
This code
if (spinner1.getSelectedItem().toString().equals("Canada"))
{
addItemsOnSpinner2();
}
will only run the first time the Activity is created since it is in your onCreate(). You need to add this code to your onItemSelected() for spinner1. So you first need to implement an OnItemSelected listener to that spinner.
spinner1.setOnItemSelected(new OnItemSelected()
{
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id)
{
TextView tv = (TextView)v; // cast the View to a TextView
if ("Canada".equals(tv.getText().toString())
{
addItemsOnSpinner2();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Something like this should work. Although, you will probably be safer to use position instead of getting the text.
OnItemSelected Docs

Perform click event on Spinner to execute code in onItemSelected

I want to perform a click on a Spinner element automatically after my activity has been loaded completely.
I use this code to set up the spinner and adapter:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read_data);
getActionBar().setDisplayHomeAsUpEnabled(true);
mSpinnerDay = (Spinner) mTable.findViewById(R.id.spieltag_choice);
mAdapterSpinnerDay = new ArrayAdapter<CharSequence>(this, R.layout.custom_spinner);
mAdapterSpinnerDay.setDropDownViewResource(R.layout.custom_spinner);
mSpinnerDay.setAdapter(mAdapterSpinnerDay);
}
private void setUpSpinnerListener(final IGameData data) {
mSpinnerDay.post(new Runnable() {
public void run() {
mSpinnerDay.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
for (GameDayData d : data.getGameDay()) {
if (d.getName().equals(adapterView.getSelectedItem().toString())) {
TableRow row = (TableRow) mTable.findViewById(R.id.row_punkte_tag);
TextView t = (TextView) row.findViewById(R.id.punkte_tag);
t.setText("Punkte: " + d.getScore());
TableRow row2 = (TableRow) mTable.findViewById(R.id.row_position_tag);
TextView t2 = (TextView) row2.findViewById(R.id.position_tag);
t2.setText("Position: " + d.getPosition());
return;
}
}
}
public void onNothingSelected(AdapterView<?> adapterView) {
return;
}
});
}
});
}
public void onTeamCheckReadComplete(IGameData data) {
for (GameDayData d : data.getGameDay()) {
mAdapterSpinnerDay.add(d.getName());
}
}
I try to perform the click with following code after I have set the adapter to the spinner:
mSpinnerDay.setSelection(0, true);
View view = (View) mSpinnerDay.getChildAt(0);
long id = mSpinnerDay.getAdapter().getItemId(0);
mSpinnerDay.performItemClick(view, 0, id);
But this does not work. Could somebody tell me how I can perfom a click on a spinner element automatically? When I select the spinner item over touch event in the application everything works fine.
Regards,
Sandro
Corrected Solution
As I understand it, you have a spinner with items A, B, C, and D. You want item A pre-selected. You also want the user to be able to select A, B, C, and D and perform an action based on that.
In the onCreate() method:
mSpinner.setAdapter(myAdapter);
mSpinner.setOnItemSelectedListener(this); // have the activity implement
// OnItemSelectedListener interface
doAction(0);
Then implement the onItemSelected action like so:
#Override
void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
doAction(position);
}
You must implement the doAction(int position) method to handle how to update your activity based on the position of the item in your adapter. Clear?
Read more about this item and how to use it here:
http://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html
I dont think you are calling setUpSpinnerListener from the code that you have posted. Even if you are calling it, i dont think it is advantageous to post a runnable to setuplistener.
Move all the code in runnable to just after setAdapter

Categories

Resources