-1

Can I use a spinner in a fragment? I want to use a spinner in one of the fragment of my activity to set the time on my countdown timer. All the tutorials and videos I've seen uses activity and not fragment and i'm not sure if its the same way to make a spinner in a fragment.

package com.softeng.applockerproject;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.concurrent.TimeUnit;



public class page2 extends Fragment {
    private static final String TAG =   "page2";

    private Button btntest;
    private TextView timer;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.page2_fragment,container,false);

        btntest = (Button) view.findViewById(R.id.button2);
        timer = (TextView) view.findViewById(R.id.Timer);
        btntest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                countDownTimer.start();
            }
        });

        return view;
    }

    //timer part
    private CountDownTimer countDownTimer = new CountDownTimer(7200000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            long millis= millisUntilFinished;
            String hms= String.format("%02d:%02d",

                    TimeUnit.MILLISECONDS.toHours(millis),
                    TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))
                    //TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
            );
            timer.setText(hms);
        }

        @Override
        public void onFinish() {
            Toast.makeText(getActivity(), "timer stopped",Toast.LENGTH_SHORT).show();
        }
    };
}
PotatoREX
  • 37
  • 1
  • 8
  • 1
    Possible duplicate of [basic spinner example](https://stackoverflow.com/questions/13097784/basic-spinner-example) – Sabid Habib Jan 02 '18 at 04:07

3 Answers3

3

The following is how you'd set a spinner in a fragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.manual, container, false);

    String [] values = 
        {"Time at Residence","Under 6 months","6-12 months","1-2 years","2-4 years","4-8 years","8-15 years","Over 15 years",};
    Spinner spinner = (Spinner) v.findViewById(R.id.spinner1);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, values);
    adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
    spinner.setAdapter(adapter);

    return v;

}

Replace the layout files with the ones in which you are using, good luck :)

beastlyCoder
  • 2,349
  • 4
  • 25
  • 52
1

In terms of adding components, Fragments and Activities behave in a similar way. Fragments can be thought of mini-activities with there own lifecycle methods with some additional methods like onCreateView() and onDestroyView(). You can add a spinner to the fragment in the following way:

Here's the code for Fragment's Java File:

public class MainFragment extends Fragment {

// Default Constructor to instantiate a Fragment object
public MainFragment(){

}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.main_fragment,container,false);

    Spinner spinner = (Spinner) view.findViewById(R.id.spinner);

    // Creating an Array Adapter to populate the spinner with the data in the string resources
    ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(getContext(),R.array.spinner_choices
                                                ,android.R.layout.simple_spinner_item);
    // Specify the layout to use when the list of choices appears
    spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // Apply the adapter to the spinner
    spinner.setAdapter(spinnerAdapter);

    return view;
}
}

The code for the layout file used for the Fragment is :

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="match_parent"
 android:layout_height="match_parent">

<Spinner
    android:id="@+id/spinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="20dp"/>

</LinearLayout>

Now to attach the fragment to an activity the code is as follows:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    MainFragment fragment = new MainFragment();
    FragmentManager manager = getSupportFragmentManager();

    manager.beginTransaction().add(R.id.fragment_container,fragment).commit();
}
}

The string resource used to provide the ArrayAdapter with data is in the strings.xml file. It is as follows:

<string-array name="spinner_choices">
    <item>Deafult Choice</item>
    <item>Choice 1</item>
    <item>Choice 2</item>
    <item>Choice 3</item>
    <item>Choice 4</item>
    <item>Choice 5</item>
</string-array>

The only difference between adding a spinner item to a Fragment and an Activity is here:

ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(getContext(),R.array.spinner_choices
                                     ,android.R.layout.simple_spinner_item);

In an Activity you would have to replace the getContext() with this or ActivityName.this. Rest of the code will be same.

Note: You should write the code to fetch the Spinner from Fragment Layout file in the onCreateView() method only because it is called before the Parent Activity's onCreate() method to ensure that all views are created before the fragment being attached to the parent activity.

Sudhanshu Vohra
  • 1,345
  • 2
  • 14
  • 21
0

Try this in your fragment to set and use spinner

public class ExamsFragment extends Fragment {
        private static final String[] spinner_data= {"Term I", "Term II", "Term III"};
        View view;
    Spinner mySpinner;

  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_layout, container, false);
        setSpinnerData();
        mySpinner.setEnabled(true);
        //Setting the  UI.
            return view;
    }

method to initialize spinner and set adapter

    private void setSpinnerData() {
        mySpinner= (Spinner) getActivity().findViewById(R.id.spinner_sp);
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(getActivity(),
                R.layout.spinner_item_layout, testTypes);

        mySpinner.setAdapter(spinnerAdapter);
    }

spinner_item_layout.xml //your spinner item layout

<?xml version="1.0" encoding="utf-8"?>    
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/white"
    android:gravity="start"
    android:paddingLeft="@dimen/padding_10"
    android:paddingRight="@dimen/padding_10"
    android:paddingTop="@dimen/padding_3"
    android:paddingBottom="@dimen/padding_3"
    android:background="@color/colorPrimary"
    android:textSize="16sp"/>

fragment_layout.xml // put this in your main layout

 <Spinner
            android:id="@+id/spinner_sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20sp"
            android:textStyle="bold">

        </Spinner>
Android Geek
  • 8,956
  • 2
  • 21
  • 35