Duplicating an element when a button is pressed - android

Is it possible to duplicate an element, (such as a spinner that I already have on my activity screen) by pressing a button? And I'll be able to use both spinners and add as many as I want?

This code show you how to create spinner programmatically and add it to a LinearLayout.
You can call makeSpinner method and get a duplicated spinner.
Then add it to your ViewGroup as a child view by calling addView method.
Tip: you should store reference of added spinner for accessing them later. I stored them in mSpinners.
public class MainActivity extends AppCompatActivity {
private LinearLayout mLinearLayout;
private ArrayList<Spinner> mSpinners; // to hold reference of added spinner for reading purposes
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSpinners = new ArrayList<>();
mLinearLayout = findViewById(R.id.my_linearLayout);
mLinearLayout.addView(makeSpinner()); // First spinner
Button duplicateSpinner = findViewById(R.id.bt_duplicate);
duplicateSpinner.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Spinner spinner = makeSpinner();
mLinearLayout.addView(spinner); // Add another spinner
}
});
Button getSpinner = findViewById(R.id.bt_getSpinner);
getSpinner.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = 0; i < mSpinners.size(); i++) { // Read all spinners
Spinner spinner = mSpinners.get(i);
Log.i("TAG", spinner.getSelectedItem().toString());
}
}
});
}
private Spinner makeSpinner() {
Spinner spinner = new Spinner(this, Spinner.MODE_DROPDOWN);
// Setup layout
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
spinner.setLayoutParams(layoutParams);
// Prepare data
ArrayList<String> data = new ArrayList<>(); // change it based on your code
data.add("Item 1");
data.add("Item 2");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
mSpinners.add(spinner); // store it
return spinner;
}
}
This is the activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="match_parent"
android:layout_height="match_parent"
android:id="#+id/my_linearLayout"
android:orientation="vertical"
tools:context="com.khahani.app.stack.MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bt_duplicate"
android:text="Duplicate"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bt_getSpinner"
android:text="Get Selected Item"/>
</LinearLayout>
Enjoy it.

Related

The spinner is empty when no new object is being generated for an ArrayAdapter

To assign data of an ArrayList<String> alKategorien to a spinner auswahl_kategorie, I am using this snippet:
ad = new ArrayAdapter(
this,
android.R.layout.simple_spinner_item,
alKategorien);
ad.setDropDownViewResource(
android.R.layout
.simple_spinner_dropdown_item);
auswahl_kategorie.setAdapter(ad);
I tried to reuse the ArrayAdapter by phrasing it like
if (ad == null) {
ad = new ArrayAdapter(
this,
android.R.layout.simple_spinner_item,
alKategorien);
ad.setDropDownViewResource(
android.R.layout
.simple_spinner_dropdown_item);
auswahl_kategorie.setAdapter(ad);
}
else
{
ad.clear();
ad.addAll(alKategorien);
ad.notifyDataSetChanged();
}
Yet unless ad is null, this yields an empty spinner.
How do I reuse the ArrayAdapter properly?
I have just made a very simple sample.
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 1"
android:id="#+id/bt1" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 2"
android:id="#+id/bt2" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 3"
android:id="#+id/bt3" />
<Button
android:id="#+id/btGetSpinnersValues"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Get Spinners Values" />
</LinearLayout>
item_schreiben.xml:
<?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:padding="10dp">
<TextView
android:id="#+id/tvSample"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Spinner
android:layout_marginBottom="20dp"
android:layout_width="match_parent"
android:layout_height="70dp"
android:id="#+id/auswahl_kategorie" />
</LinearLayout>`
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private final int NO_OF_ITEMS = 3;
Button bt1, bt2, bt3, btGetSpinnersValues;
//Spinner auswahl_kategorie;
ArrayList<String> alKategorien = new ArrayList();
ArrayList<Integer> alDynamicChildren = new ArrayList();
ArrayAdapter ad;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout rootLayout = findViewById(R.id.rootLayout);
bt1 = findViewById(R.id.bt1);
bt2 = findViewById(R.id.bt2);
bt3 = findViewById(R.id.bt3);
btGetSpinnersValues = findViewById(R.id.btGetSpinnersValues);
alKategorien.add("a");
alKategorien.add("b");
alKategorien.add("c");
alKategorien.add("d");
alKategorien.add("e");
setSpinnerAdapter();
for (int i = 0; i < NO_OF_ITEMS; i++) {
View dl_item_schreiben = getLayoutInflater().inflate(R.layout.item_schreiben, null);
rootLayout.addView(dl_item_schreiben);
alDynamicChildren.add(rootLayout.indexOfChild(dl_item_schreiben));
TextView textView = dl_item_schreiben.findViewById(R.id.tvSample);
textView.setText("Spinner " + (i + 1));
Spinner auswahl_kategorie = dl_item_schreiben.findViewById(R.id.auswahl_kategorie);
auswahl_kategorie.setAdapter(ad);
auswahl_kategorie.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alKategorien.clear();
alKategorien.add("A");
alKategorien.add("B");
alKategorien.add("C");
alKategorien.add("D");
alKategorien.add("E");
ad.notifyDataSetChanged();// or setSpinnerAdapter();
}
});
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alKategorien.clear();
alKategorien.add("1");
alKategorien.add("2");
alKategorien.add("3");
alKategorien.add("4");
alKategorien.add("5");
ad.notifyDataSetChanged();// or setSpinnerAdapter();
}
});
bt3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alKategorien = new ArrayList<>();
alKategorien.add("A");
alKategorien.add("B");
alKategorien.add("C");
alKategorien.add("D");
alKategorien.add("E");
setSpinnerAdapter();
}
});
btGetSpinnersValues.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String msg = "";
LinearLayout parent = (LinearLayout) view.getParent();
for (int i = 0; i < NO_OF_ITEMS; i++) {
Spinner auswahl_kategorie = parent.getChildAt(alDynamicChildren.get(i)).findViewById(R.id.auswahl_kategorie);
msg += "Spinner " + (i +1) + ": " + auswahl_kategorie.getSelectedItem().toString() + "\n";
}
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
private void setSpinnerAdapter() {
if (ad == null) {
ad = new ArrayAdapter(this, android.R.layout.simple_spinner_item, alKategorien);
ad.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//auswahl_kategorie.setAdapter(ad);
} else {
//ad.clear();
//ad.addAll(alKategorien);
ad.notifyDataSetChanged();
}
}
}
I tested the code and spinner changed content for bt1/bt2 clicked. But after bt3 clicked, no more change.
First, when the adapter is created, it is set with alKategorien as the data list, so call ad.clear() just clear alKategorien and ad.addAll(alKategorien); add back an empty list. Therefore those two lines should be removed.
Second, data list cannot be created again (i.e. = new ArrayList<>() and so no more change after bt3 clicked) but can be modified (clear, add, remove) because it acts like a linkage between activity and adapter. If data list is created again by new, then the adapter needs to be created again as linkage broken. There may be other conditions that can break the linkage. Since the code that I mentioned in first point is removed, so issue should be caused by the way of modifying data list which is not shown in the snippet.

Program ImageView[][] With ID - GridLayout

I used those code to make 2x2 Image on a GridLayout and it works, but there is one problem, each ImageView has the same ID, -1, so when I use OnClick it does not work. What can I do?
Here the codes
activity_main.xml :
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/gridLayout"
tools:context=".MainActivity"
android:orientation="horizontal"
android:columnCount="2"
android:rowCount="2" />
MainActivity.java :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridLayout gridLayout = (GridLayout) findViewById(R.id.gridView);
ImageView[][] imageViews = new ImageView[2][2];
for (int i=0;i<2;i++){
for (int j=0;j<2;j++){
imageViews[i][j] = new ImageView(MainActivity.this);
imageViews[i][j].setImageResource(R.mipmap.ic_launcher);
gridLayout.addView(imageViews[i][j]);
}
}
}
}
Your view IDs only need to be positive integers, so could set them like this:
imageViews[i][j].setId(100); // or whatever you prefer
OR you could set a click listener programmaticaly:
// Create the click listener
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// do what you want
}
};
for (int i=0;i<2;i++){
for (int j=0;j<2;j++){
imageViews[i][j] = new ImageView(MainActivity.this);
imageViews[i][j].setImageResource(R.mipmap.ic_launcher);
imageViews[i][j].setOnClickListener(clickListener);
gridLayout.addView(imageViews[i][j]);
}
}

ListView not showing text on items

I want to display text input from an editText and show it in a listView using an ArrayAdapter, when clicking a button, the listView does gets an item added but without the text :
here is the code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.blink.blink.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="61dp">
<EditText
android:layout_width="280dp"
android:layout_height="60dp"
android:hint="Type a quote .. "
android:id="#+id/quoteField" />
<Button
android:layout_width="wrap_content"
android:layout_height="60dp"
android:text="Add Quote"
android:id="#+id/addQuote"
android:fontFamily="sans-serif-condensed"
android:background="#f6546a"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#id/quoteField" />
</RelativeLayout>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/quotelistView"
android:foreground="#f6546a"/>
</LinearLayout>
and :
public class MainActivity extends AppCompatActivity {
Button createBtn ;
EditText quoteField;
ListView quotesListView;
ArrayList<String> quotesArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createBtn = (Button) findViewById(R.id.addQuote);
quoteField = (EditText) findViewById(R.id.quoteField);
quotesListView = (ListView) findViewById(R.id.quotelistView);
quotesArrayList = new ArrayList<>();
createBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
quotesArrayList.add(quoteField.getText().toString());
SetAdapter();
quoteField.setText(" ");
}
});
}
private void SetAdapter()
{
ArrayAdapter<String> Adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, quotesArrayList);
quotesListView.setAdapter(Adapter);
}
}
You do not need to reset the adapter everytime you change the data in the array. What you should do is keep a reference to the adapter and call adapter.notifyDataSetChanged() when you change the data in the list
public class MainActivity extends AppCompatActivity {
Button createBtn ;
EditText quoteField;
ListView quotesListView;
ArrayList<String> quotesArrayList;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createBtn = (Button) findViewById(R.id.addQuote);
quoteField = (EditText) findViewById(R.id.quoteField);
quotesListView = (ListView) findViewById(R.id.quotelistView);
quotesArrayList = new ArrayList<>();
adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, quotesArrayList);
quotesListView.setAdapter(adapter);
createBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
quotesArrayList.add(quoteField.getText().toString());
adapter.notifyDataSetChanged();
quoteField.setText(" ");
}
});
}
}
Try it!
createBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
quotesArrayList.add(quoteField.getText().toString());
SetAdapter(quotesArrayList);
quoteField.setText(" ");
}
});
}
private void SetAdapter(ArrayList<String> quotesArrayList)
{
ArrayAdapter<String> Adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, quotesArrayList);
quotesListView.setAdapter(Adapter);
Adapter.notifyDataSetChanged();
}

How to show Spinner-List when we tapped on button in android?

Hi I recently came to the android technology and in my app I have two buttons(one for showing movies-list and another one for showing countrieslist)
When I tap on the second button I want to display movies-list in spinner-list as in the first image bellow.
But according to my code, when I tap on the button first spinner is appearing and I selected any one item and set that to my button title but after selection spinner still visible B/w two button as like my second screen how can remove it.
How can I resolve this problem?
Please help me.
I want to show directly spinner-list when I tap on button.
xml:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="10dp"
android:id="#+id/parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="Button1Action"
android:text="CountiesList"/>
<Spinner
android:visibility="gone"
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/mainLayout"
android:layout_alignParentRight="true"
android:paddingRight="0dp"
android:layout_marginTop="5dp"
/>
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="Button2Action"
android:text="MoviesList"/>
<Spinner
android:visibility="gone"
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/mainLayout"
android:layout_alignParentRight="true"
android:paddingRight="0dp"
android:layout_marginTop="5dp"
/>
</LinearLayout>
activity:-
public class spinnerListProgramatically extends AppCompatActivity{
String [] countriesList = {"india","usa","england"
};
String [] moviesList = {"fury","300 rise of an empire","troy"
};
Spinner spinner1,spinner2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinnerlist_runtime);
}
public void Button1Action(View view){
spinner1 = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, countriesList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
spinner1.setVisibility(View.VISIBLE);
}
public void Button2Action(View view){
spinner2 = (Spinner)findViewById(R.id.spinner2);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, moviesList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
spinner2.setVisibility(View.VISIBLE);
}
}
---
Why not remove Spinner and have just a Button instead. Having a Spinner and Button both, makes no sense.
As per the image you have shown, you require PopupMenu:
public void Button2Action(View view){
showFilterPopup(view);
}
private void showPopup(View v) {
PopupMenu popup = new PopupMenu(this, v);
// Inflate the menu from xml
popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());
// Setup menu item selection
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.troy:
Toast.makeText(MainActivity.this, "troy", Toast.LENGTH_SHORT).show();
return true;
case R.id.rise:
Toast.makeText(MainActivity.this, "300 Rise of Empire", Toast.LENGTH_SHORT).show();
return true;
default:
return false;
}
}
});
// Handle dismissal with: popup.setOnDismissListener(...);
// Show the menu
popup.show();
}
Your R.menu.popup will contain every item you need.
This approach will be useful when you have static set of data.
With few more steps you can make it dynamic. Hope this helps.
Use this it work
public void Button1Action(View view){
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, countriesList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
spinner1.setVisibility(View.INVISIBLE);
spinner1.performClick();
}
public void Button2Action(View view){
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, moviesList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
spinner2.setVisibility(View.INVISIBLE);
spinner2.performClick();
}
View this Screen
Can set this as the screen Display.
OK, Finally I knew what you really meant to say after a long discussion. I have provided you full source codes which are optimized and modified a little bits from yours.
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="10dp"
android:layout_marginTop="50dp"
android:id="#+id/parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="Button1Action"
android:text="CountiesList"/>
<Spinner
android:visibility="invisible"
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
/>
<Spinner
android:visibility="gone"
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
/>
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="Button2Action"
android:text="MoviesList"/>
</LinearLayout>
Your Activity
public class spinnerListProgramatically extends AppCompatActivity {
Button button1, button2;
String [] countriesList = {"NONE","india","usa","england"};
String [] moviesList = {"NONE","fury","300 rise of an empire","troy" };
Spinner spinner1,spinner2;
#Override
protected void onCreate(Bundle savedInstanceState) {
//Your other setup codes
spinner1 = (Spinner)findViewById(R.id.spinner1);
spinner2 = (Spinner)findViewById(R.id.spinner2);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
}
public void Button1Action(View view){
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, countriesList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
spinner1.setVisibility(View.VISIBLE);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position!=0) {
button1.setText(countriesList[position]);
spinner1.setVisibility(View.GONE);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void Button2Action(View view){
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, moviesList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
spinner2.setVisibility(View.VISIBLE);
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position!=0) {
button2.setText(moviesList[position]);
spinner2.setVisibility(View.GONE);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
show Spinner-List item without tap on spinner
Spinner spi_type = findViewById(R.id.spi_type);
Button button = findViewById(R.id.button);
imgVIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// performClick() this method show Spinner-List item without tap on spinner
spi_type.performClick();
}
});
cant comment cause am not having that much reputation.. can u be more specific of what you want to achieve??
The problem was that
if(spinner2.getSelectedItem() == null)
is not null.. it by default tasks the first value
so use this code instead
if(spinner2.getSelectedItem() == "fury") {
// for checking user havent selected anything
spinner2.performClick();
}
if(spinner1.getSelectedItem() == "india") {
// for checking user havent selected anything
spinner1.performClick();
}
and for setting the title for button
public void Button1Action(View view){
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, countriesList);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter1);
spinner1.setVisibility(View.VISIBLE);
String s = (String) spinner1.getSelectedItem();
spinner1.performClick();
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
button.setText(""+ spinner1.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
in the button onCLick
and also intialize the buttons on onCreate
button = (Button) findViewById(R.id.button1);
button1 = (Button) findViewById(R.id.button2);
and placing adaptor is not an issue..
find spinner and set adapetr before Button onClick method

Android- Data is allocated in spinner but when selected not showing the value in spinner

Problem
I am fetching some product category from mysql using Retrofit. The data is coming and allocated in spinner but when I select an item its not displayed. In the drop down menu the items are allocated and the setOnItemSelected listener is also working. But the selected item not showing up in the spinner.
I have tried almost everything also related stackoverflow questions but not working. Pls help me. Thanks in advance.
Code
This is the OrderActivity
public class OrderActivity extends AppCompatActivity {
Spinner sp_category,sp_product;
public static final String ROOT_URL = "http://10.0.2.2/sizzle/";
private List<Product> books;
List<String> prod_cat = new ArrayList<String>();
ArrayAdapter<String> adapter_prod_cat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
//sp_product = (Spinner)findViewById(R.id.spinner_product);
getBooks();
sp_category = (Spinner)findViewById(R.id.spinner_category);
sp_category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String category = parent.getSelectedItem().toString();
Toast.makeText(getApplicationContext(),category,Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void getBooks(){
final ProgressDialog loading = ProgressDialog.show(this, "Fetching Data", "Please wait...", false, false);
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(ROOT_URL)
.build();
ProductAPI api = adapter.create(ProductAPI.class);
api.getProduct(new Callback<List<Product>>() {
#Override
public void success(List<Product> list, Response response) {
//Dismissing the loading progressbar
loading.dismiss();
books = list;
for (int i = 0; i < books.size(); i++) {
prod_cat.add(books.get(i).getProductCategory());
System.out.println("added");
}
Set<String> citySet = new HashSet<String>(prod_cat);
prod_cat.clear();
prod_cat.addAll(citySet);
prod_cat.add("Select Category");
showListinSpinner();
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
}
});
}
private void showListinSpinner(){
//String array to store all the book names
String[] items = new String[prod_cat.size()];
//Traversing through the whole list to get all the names
for(int i=0; i<prod_cat.size(); i++){
//Storing names to string array
items[i] = prod_cat.get(i);
}
//Spinner spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, items);
//setting adapter to spinner
adapter.notifyDataSetChanged();
sp_category.setAdapter(adapter);
//Creating an array adapter for list view
}
}
This is the layout file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res /android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.skipper.ash.ashtet.OrderActivity">
<Spinner
android:layout_width="300dp"
android:layout_height="80dp"
android:id="#+id/spinner_category"
android:spinnerMode="dropdown"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"
android:textAlignment="center"
android:visibility="visible" />
</RelativeLayout>
Create xml file in layout folder named item_spinner and write the code below in it
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:textColor="#000000" >
and change in your code while creating adapter.
adapter = new ArrayAdapter<String>(getApplicationContext(),
R.layout.item_spinner, items);
also change the sequence of the statements
sp_category.setAdapter(adapter);
adapter.notifyDataSetChanged();
First set adapter to spinner and then fire data set changed event.
Hope it'll help you.
EDIT
I observed lot of time that if we set the adapter to ListView or Spinner programatically using ArrayAdapter and uses android.R.layout.simple_spinner_item_1 or any other build in layout, then it sets the text color of item to white. I didn't get it why it sets the white color to text by default.

Categories

Resources