How do I add Spinner without extending Activity - android

I have a class that extends the Fragment. I want to add a Spinner but he needs to expand Activity. Can it be done differently?
The following should work if I expanded a class Activity but I can not do in this case.
public class Parameters extends Fragment implements AdapterView.OnItemSelectedListener{
Spinner spinner;
ArrayAdapter<CharSequence> adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.parameters_tab3, container, false);
return rootView;
spinner = (Spinner) findViewById(R.id.spinner);
adapter = ArrayAdapter.createFromResource(this.getContext(), R.array.strength_class_of_concrete, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TextView myText = (TextView) view;
Toast.makeText(this, "selected" + myText.getText(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
.
<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.kaminski.bartek.columnec2.MainActivity$PlaceholderFragment">
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="68dp"
android:id="#+id/spinner" />
</RelativeLayout>
.
<resources>
<string name="app_name">Column EC2</string>
<string name="action_settings">Settings</string>
<string-array name="strength_class_of_concrete">
<item>C12/15</item>
<item>C16/20</item>
<item>C20/25</item>
<item>C25/30</item>
<item>C30/37</item>
<item>C35/45</item>
<item>C40/50</item>
<item>C45/55</item>
<item>C50/60</item>
<item>C55/67</item>
<item>C60/75</item>
</string-array>
</resources>

You are exiting the function before it sets up spinner. Write return rootView after setting spinner up. Like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.parameters_tab3, container, false);
spinner = (Spinner) rootView.findViewById(R.id.spinner);
adapter = ArrayAdapter.createFromResource(this.getContext(), R.array.strength_class_of_concrete, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
return rootView;
}
EDIT
If you are working with fragments, then view is inflated in onCreate. Now you should find views in that inflated view. Like
spinner = (Spinner) rootView.findViewById(R.id.spinner);

Related

Spinner not showing drop-down in Fragment

I'm working with Fragments in my current app. I tried using a Spinner in one of the fragments, to sort the listview below it in a specific format. The Adapter is set correctly, but I'm unable to open the dropdown on touch to select the choices. How I know the adapter is set correctly, is that in the AVD, I'm able to navigate to it using the keyboard and open it.
Code:
public class Upcoming_Reminders extends Fragment {
private View view;
private ProgressDialog progressDialog;
private ListView listView;
private String TAG = "Loggin";
RemindersAdapter remindersAdapter;
private Spinner mSortSpinner;
private String[] test;
public Upcoming_Reminders() {
// Required empty public constructor
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mSortSpinner = (Spinner) view.findViewById(R.id.sort_spinner);
ArrayAdapter<CharSequence> mSortAdapter = new ArrayAdapter<CharSequence>(getContext(), android.R.layout.simple_spinner_item, test);
mSortAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSortSpinner.setAdapter(mSortAdapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_upcoming__reminders, container, false);
test = getActivity().getResources().getStringArray(R.array.sort_by);
listView = (ListView) view.findViewById(R.id.contracts_list);
return view;
}
I tried putting it in the OnCreateView method as well, below the view assignment. It still isn't clickable.
The XML
<FrameLayout 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"
tools:context="com.onerooftechnologiesamc.Upcoming_Reminders">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:paddingTop="70dp">
<TextView
android:id="#+id/te"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="bottom|end"
android:text="#string/sort_by" />
<Spinner
android:id="#+id/sort_spinner"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="10dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="10dp"
android:layout_weight="1"
/>
</LinearLayout></FrameLayout>
What could be the cause? I tried Googling a lot, haven't found someone with the exact same problem as me.
Thank you
Edit 1: The Resources file
<resources>
<array name="sort_by">
<item>Option 1</item>
<item>Option 2</item>
<item>Option 3</item>
<item>Option 4</item>
</array></resources>
public class SpinnerFragment extends Fragment {
private Spinner spinner;
private String[] test = {"1","2","3","4","5"};
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_spinner,container,false);
spinner = (Spinner) view.findViewById(R.id.spinner);
ArrayAdapter<CharSequence> mSortAdapter = new ArrayAdapter<CharSequence>(getActivity(), android.R.layout.simple_spinner_item, test);
mSortAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(mSortAdapter);
return view;
}
}
Try this:
public class SpinnerAdapter extends ArrayAdapter<String>
{
private Activity context;
String[] data = null;
public SpinnerAdapter(Activity context, int resource,
String[] data2)
{
super(context, resource, data2);
this.context = context;
this.data = data2;
}
...
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent)
{
View row = convertView;
if(row == null)
{
//inflate your customlayout for the textview
LayoutInflater inflater = context.getLayoutInflater();
row = inflater.inflate(R.layout.spinner_layout, parent, false);
}
//put the data in it
String item = data[position];
if(item != null)
{
TextView text1 = (TextView) row.findViewById(R.id.rowText);
text1.setTextColor(Color.WHITE);
text1.setText(item);
}
return row;
}
...
}
and then set the adapter for the spinner:
Spinner mySpinner = (Spinner) findViewById(R.id.mySpinner);
final String[] data = getResources().getStringArray(
R.array.data);
final ArrayAdapter<String> adapter = new SpinnerAdapter(
MainActivity.this, android.R.layout.simple_spinner_item,
data);
mySpinner.setAdapter(adapter);
The problem seems to have been with FrameLayout. I switched to a RelativeLayout and it started working perfectly.

What should i use to create custom ListView in Fragment to suit my need?

I've been creating News application. I used this tutorial to create good-looking Navigation Drawer. It uses fragments for every category in Navigation List. I will be using provided API to get news (in the JSON format), and i need customized List View to show the list of news. When you click list item, it will open new view to show details of news. I've found several tutorials, but none of them worked for fragment. Please, tell me way to do it.
I'm new to Android Programming. This is my first project, though it is too hard for being first project. But i have to do it. Please, help!
Thanks beforehand!
Assuming you know how to create an adapter and a custom row layout from a tutorial that works for activities. Minor modifications will help you using fragments.
Your fragment should look like this:
public class NewFragment extends Fragment{
CustomAdapter listAdapter;
ListView listView;
ArrayList<Data> yourData; // Should be filled with data from your JSONParser;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
/*
* Use your custom adapter. in this example the adapter need
* the context and an array that contains your data
*/
listAdapter = new CustomAdapter(getActivity(),yourData);
...
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.new_fragment, container, false);
listView = (LsitView)view.findViewById(R.id.your_list);
listView.setAdapter(listAdapter);
...
}
}
You can use for this ListFragment:
Here is a fully customized example:
activity_main.xml
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/frameLayout"/>
</RelativeLayout>
mylist.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">
<ListView android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FF00"
android:layout_weight="1"
android:drawSelectorOnTop="false"/>
<TextView android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"
android:text="No data"/>
</LinearLayout>
myitem.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">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text=""
android:id="#+id/txt_mytext" />
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Fragment fr = mListFragment.newInstance();
FragmentManager fm = getFragmentManager();
fm.beginTransaction().add(R.id.frameLayout, fr, "tag").commit();
}
}
mListFragment.java
public class mListFragment extends ListFragment {
public static mListFragment newInstance() {
mListFragment f = new mListFragment();
//Bundle args = new Bundle();
//f.setArguments(args);
return f;
}
public mListFragment() {}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String[] strings = {"a", "b", "c"};
ArrayAdapter<String> adapter = new LstAdapter(
getActivity(), R.layout.myitem,
strings);
setListAdapter(adapter);
return inflater.inflate(R.layout.mylist, null);
}
public class LstAdapter extends ArrayAdapter<String> {
private String[] mArray;
public LstAdapter(Context context, int textViewResourceId, String[] mList) {
super(context, textViewResourceId, mList);
mArray = mList;
}
#Override
public int getCount() {
return mArray.length;
}
#Override
public String getItem(int position) {
return mArray[position];
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.myitem, null);
}
TextView tvName = (TextView) v.findViewById(R.id.txt_mytext);
tvName.setText(mArray[position]);
return v;
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.d("123", position + "");
super.onListItemClick(l, v, position, id);
}
}

Spinner, setOnItemSelectedListener is not working for Spinner when items are selected

setOnItemSelecctedListener is not working for the spinner. Following is the code in mainactivity.java. I have populated spinner in xml file using entries option. When an item is selected, toast message is not displayed showing the item selected.
public class MainActivity extends ActionBarActivity{
String[] presidents;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
presidents = getResources().getStringArray(R.array.presidents);
Spinner s1 = (Spinner) findViewById(R.id.spinner1);
if(s1 != null){
s1.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3)
{
int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(), presidents[index], Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0){
}
});
}
}
}
activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- Spinner Element -->
<Spinner
android:id="#+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:entries="#array/presidents"
android:drawSelectorOnTop="true"
/>
</LinearLayout>
Strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My First App</string>
<string-array name = "presidents">
<item>eisenhower</item>
<item>kennedy</item>
</string-array>
</resources>
That's because your Spinner s1 is null.
Your xml code:
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="true"
/>
In Activity, you use id spinner1
Spinner s1 = (Spinner) findViewById(R.id.spinner1);
So here s1 will be null.
And you check this:
if(s1 != null){
s1.setAdapter(adapter);
...
}
Just change your id to spinner here:
Spinner s1 = (Spinner) findViewById(R.id.spinner);
So s1 won't be null, and it will be populated with data using adapter.
Hope it helps.
NOTE:
If you have spinner1 in a fragment, you would need to do something like:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.fragment_main, container, false);
Spinner s1 = (Spinner) v.findViewById(R.id.spinner1);
return container;
}

spinner defined in main activity is null

I have populated a spinner with items in xml file using entries option. I have defined the spinner in main activity class as "s1". In debug mode i found that s1 is null. That is why setOnItemSelectedListener is not working for spinner. When an item is selected, toast message is not displayed. I am giving mainactivity.java, activity_main.xml and strings.xml files.
MainActivity.java
public class MainActivity extends ActionBarActivity{
String[] presidents;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
presidents = getResources().getStringArray(R.array.presidents);
Spinner s1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.presidents, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
if(s1 != null){
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3)
{
int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(), presidents[index], Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0){
}
});
}
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
activity_main.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Spinner
android:id="#+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop= "true"
android:entries="#array/presidents" />
strings.xml
<resources>
<string-array name = "presidents">
<item>eisenhower</item>
<item>kennedy</item>
</string-array>
</resources>
your setContentView(R.layout.activity_main); is wrong, use R.layout.fragment_main instead
You have initialized your Spinner at the class level. At this point, the Spinner object is null. You should instead initialize your Spinner within the onCreate() method. So you can have it like this:
Spinner s1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Only here is the layout inflated and only after this can Android see the Spinner
s1 = (Spinner) findViewById(R.id.spinner);
// Other statements
}
Try this way,hope this will help you to solve your problem.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity.java
public class MainActivity extends ActionBarActivity {
private Spinner s1;
private String[] presidents;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
s1 = (Spinner) findViewById(R.id.spinner1);
presidents = getResources().getStringArray(R.array.presidents);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.presidents, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
if(s1 != null){
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0,View arg1, int arg2, long arg3)
{
Toast.makeText(MainActivity.this, presidents[arg2], Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0){
}
});
}
}
}

ListView OnClickListener is not working within Fragment

I'm trying to put a listener to my listview, which is inside my fragment. I've tried a few ways to do it, but still not working. I cannot make the other view focusable="false" because there is an EditText above the listview. Everytime I click the item, it calls the getView in the JSONAdapter that I created. Here is my 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">
<ImageView
android:focusable="false"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"/>
<EditText
android:id="#+id/searchquery"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="Search"
/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#android:id/list">
</ListView>
</LinearLayout>
Here is my Fragment :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
mJSONAdapter = new JSONAdapter(getActivity(), inflater);
View v = inflater.inflate(R.layout.header, container, false);
return v;
}
#Override
public void onViewCreated(View view,Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ListView lv = (ListView) getView().findViewById(android.R.id.list);
// Set the ListView to use the ArrayAdapter
lv.setAdapter(mJSONAdapter);//isi datany pk json adapter
lv.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(),Integer.toString(position),Toast.LENGTH_SHORT).show();
JSONObject jsonObject = (JSONObject) mJSONAdapter.getItem(position);//ambil item yg diclick
String raceid = jsonObject.optString("id","");//ambil cover id yg diklik, argumen kedua itu klo null defaultny apa
// create an Intent to take you over to a new DetailActivity
Intent detailIntent = new Intent(getActivity(), DetailActivity.class);
// pack away the data about the cover
// into your Intent before you head out
detailIntent.putExtra("raceid", raceid);
// start the next Activity using your prepared Intent
startActivity(detailIntent);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
new RetrieveFeedTask().execute();
}
You can try this code.
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
// do your work
}
});
It appears that I choose the wrong method. It should be OnItemClickListener(), instead I choose OnItemSelectedListener()

Categories

Resources