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();
}
};
}
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 :)
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.
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>
Related
trying to call method within a class extends Fragment, from a textview within
layout file. In an activity class I would use this:
setContentView(R.layout.activity_main);
What would I do to achieve similarity using a class extends Fragment?
Error from logcat:
java.lang.IllegalStateException: Could not find method mood(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatTextView with id 'moodtw'
Class :
public class Tab1 extends Fragment {
private View rootView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.tab1, container, false);
return (rootView);
}
public void mood() {
String tempo;
int a;
TextView moodouttw = (TextView) rootView.findViewById(R.id.moodouttw);
tempo = moodouttw.getText().toString();
a = Integer.parseInt(tempo);
if (a < 5) {
a = a + 1;
} else a = 0;
tempo = Integer.toString(a);
moodouttw.setText(tempo);
}
}
COULDN'T GET ABOVE TO WORK, so I tried using onclicklistner found in a link from an prev. answer. This also with same error posted above. Looks like app is looking for a method with parameter which, to my knowledge, cant be set in a xml layout file.(?). I might try another approach.Below is copy of last approach and snippet from layout xml file. Thanks to all for help given.
package com.example.android.xxxxx;
import android.os.Bundle;
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.TextView;
public class Tab1 extends Fragment implements View.OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab1, container, false);
TextView t = (TextView) v.findViewById(R.id.anxietyouttw);
t.setOnClickListener(this);
return v;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.anxietyouttw:
// do something
String tempo;
int a;
TextView anxietyouttw = (TextView) v.findViewById(R.id.anxietyouttw);
tempo = anxietyouttw.getText().toString();
a = Integer.parseInt(tempo);
if (a < 5) {
a = a + 1;
} else a = 0;
tempo = Integer.toString(a);
anxietyouttw.setText(tempo);
break;
}
}
}
XML LAYOUT FILE
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:id="#+id/headertw1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="18dp"
android:layout_toEndOf="#+id/anxietyleveltw"
android:layout_toRightOf="#+id/anxietyleveltw"
android:text="#string/input_of_general_data_1_of_2"
android:textAppearance="#style/TextAppearance.AppCompat"
android:textColor="#color/colorPrimaryDark"
android:textStyle="bold" />
<TextView
android:id="#+id/anxietyleveltw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/moodtw"
android:layout_alignStart="#+id/moodtw"
android:layout_below="#+id/moodtw"
android:layout_marginTop="15dp"
android:onClick="anxiety"
android:text="#string/anixiety"
android:textAppearance="#style/TextAppearance.AppCompat" />
<TextView
android:id="#+id/anxietyouttw"
android:layout_width="24dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/anxietyleveltw"
android:layout_alignBottom="#+id/anxietyleveltw"
android:layout_alignLeft="#+id/sleepouttw"
android:layout_alignStart="#+id/sleepouttw"
android:text="#string/_0"
android:textAlignment="center"
android:textAppearance="#style/TextAppearance.AppCompat"
android:textIsSelectable="false"
android:textSize="14sp" />
</RelativeLayout>
Set View as arg in method
public class Tab1 extends Fragment {
private View rootView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.tab1, container, false);
return (rootView);
}
public void mood(View view) {
String tempo;
int a;
TextView moodouttw = (TextView) rootView.findViewById(R.id.moodouttw);
tempo = moodouttw.getText().toString();
a = Integer.parseInt(tempo);
if (a < 5) {
a = a + 1;
} else a = 0;
tempo = Integer.toString(a);
moodouttw.setText(tempo);
}
}
please try this
setOnClickListener for the textview for which you are setting OnClick in xml layout.
For eg
private View rootView;
private TextView textView;
In onCreateView
rootView = inflater.inflate(R.layout.tab1, container, false);
textView = rootView.findViewById(R.id.<your textview id>);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mood();
}
});
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.
I want to use a spinner in my android fragment. For the purpose, I wrote the following code:
package com.example.shiza.dailyquranverses;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
*/
public class completeQuran extends Fragment implements AdapterView.OnItemSelectedListener {
Spinner spinner;
public completeQuran() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_complete_quran, container, false);
spinner = (Spinner)view.findViewById(R.id.selectChapter);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity().getApplicationContext(),R.array.chapters,android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
return view;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int quran_id;
String chapter_verse="";
TextView textView;
position++;
String chapter_array_name = "chapter_" + position;
quran_id = getResources().getIdentifier(chapter_array_name, "array", getActivity().getApplicationContext().getPackageName());
String[] chapter = getResources().getStringArray(quran_id);
for ( int item = 0 ; item < chapter.length ; item++ )
{
// if ( item > 0 )
// {
// chapter_verse += item + ". " ;
// }
chapter_verse += chapter[item] + "\n";
}
textView = (TextView)view.findViewById(R.id.verse);
textView.setText(chapter_verse);
textView.setMovementMethod(new ScrollingMovementMethod());
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
Toast.makeText(getActivity().getApplicationContext(),"Please enter your choice",Toast.LENGTH_LONG).show();
}
}
I am getting error at
textView.setText(chapter_verse);
in onItemSelected method. I am using its view to get values from xml. The xml corresponding to the fragment looks like:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Spinner
android:id="#+id/selectChapter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/backgroundColor"
android:orientation="vertical">
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:scrollbars="vertical"
tools:context="com.example.shiza.dailyquranverses.Quran">
<TextView
android:id="#+id/verse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="2000"
android:scrollbars="vertical"
android:text="Hello from Quran"
android:textSize="#dimen/verse_font_chapter" />
</LinearLayout>
</ScrollView>
</LinearLayout>
Please help me to solve this.
The onItemSelected callback tells you when a certain item in your Spinner has been selected. The View that exists as a parameter in that callback is the View in the Spinner that was selected. For this reason, I'm guessing that your textView variable will be null. The View that you are trying to access is not enclosed within the View that is being selected, it is enclosed in your layout in general. You should set the reference to that TextView inside of your OnCreateView like so:
public class completeQuran extends Fragment implements AdapterView.OnItemSelectedListener
{
Spinner spinner;
TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_complete_quran, container, false);
spinner = (Spinner)view.findViewById(R.id.selectChapter);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity().getApplicationContext(),R.array.chapters,android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
textView = (TextView)view.findViewById(R.id.verse); //notice the view that this is finding your textview within
return view;
}
}
Then you can use that reference to textView in your onItemSelected callback. You don't need to redefine the reference every time.
It's because setText eat a charSequence and you give a String
you need to use
textView.setText(String.valueOf(chapter_verse))
The issue was with:
textView = (TextView)view.findViewById(R.id.verse);
I need to use getView() method instead of view method.
I followed all the steps from various sources for getting listviews to work but my one
doesn't seem to display anything. This list view code(shown below) is activated with a tab fragment manager I won't put that here as to not bog you all down with code as there's a lot here already. It is most likely a problem with the ListFragment itself but I suppose it could be the adapter.
What happens is nothing gets displayed at all just the searchview that I have put in the main xml layout. I can switch freely between tabs with no crashes but just nothing displays in any of my listviews. I have another list which is a friends list(not included in this code snippet) and that uses a generic view holder interface and that one does not work either which suggests the problem is most likely in my ListFragment but I just can't pinpoint it. Any help is appreciated and I hope some can learn something from this, Thank you.
This is my adapter for the settings category list
package codeblox.com.listfragmentexample;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;
import java.util.ArrayList;
import codblox.com.listfragmentexample.R;
public class SettingsAdapter extends ArrayAdapter<Settings.SettingsCategories>
{
private final Activity context;
String[] text;
ArrayList<Settings.SettingsCategories> itemsCopy;
class ViewHolder
{
public TextView txt;
public CheckBox state;
public ImageView settingImg;
public EditText input;
public ToggleButton toggle;
public Button settingInfo; // click it to show what the setting does
}
public SettingsAdapter(Context context, ArrayList<Settings.SettingsCategories> items)
{
super(context, R.layout.settings_category_row, items);
this.context = (Activity) context;
this.itemsCopy = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = new ViewHolder();
int viewType = this.getItemViewType(position);
if(convertView == null)
{
// inflate the GridView item layout
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.settings_category_row, parent, false);
// initialize the view holder
holder = new ViewHolder();
holder.settingImg = (ImageView) convertView.findViewById(R.id.settingCategoryImg);
holder.txt = (TextView) convertView.findViewById(R.id.settingCategoryName);
convertView.setTag(holder);
} else {
// recycle the already inflated view
holder = (ViewHolder) convertView.getTag();
}
// fill data
holder = (ViewHolder) convertView.getTag();
String s = getItem(position).toString();
holder.txt.setText(itemsCopy.get(position).getSettingText());
holder.settingImg.setImageResource(itemsCopy.get(position).getImgResId());
return convertView;
}
}
This is my list fragment
package codeblox.com.listfragmentexample
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import codeblox.com.listfragmentexample.R;
public class Settings extends ListFragment implements View.OnLongClickListener
{
private ListView settingsList;
private ArrayList<SettingsCategories> mItems;
private ArrayAdapter<SettingsCategories> settingsAdapter;
private int numCategories;
String[] CategoryArray = new String[] {"Privacy and Security","Account","Networks","Camera Options","Storage","Accesibility","Features"};
int[] resIds = new int[] {R.drawable.security_settings_icon,R.drawable.account_settings_icon,
R.drawable.network_settings_icon,R.drawable.camera_settings_icon,R.drawable.storage_settings_icon,
R.drawable.accessibility_settings_icon,R.drawable.feature_settings_icon,};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View settingsView = inflater.inflate(R.layout.settings, container, false);
settingsList = (ListView)settingsView.findViewById(android.R.id.list);
// initialize the items list
return settingsView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
// remove the dividers from the ListView of the ListFragment
settingsList = getListView();
settingsList.setDivider(null);
mItems = new ArrayList<SettingsCategories>();
Resources resources = getResources();
for(int c = 0; c < numCategories; c++)
{
mItems.add(new SettingsCategories(CategoryArray[c],resIds[c]));
}
// initialize and set the list adapter
// settingsAdapter = new SettingsAdapter(this.getActivity(), mItems);
setListAdapter(new SettingsAdapter(getActivity(), mItems));
settingsList.setAdapter(settingsAdapter);
}
public Settings()
{
this.numCategories = CategoryArray.length;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public boolean onLongClick(View v)
{
return false;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
Object i = l.getItemAtPosition(position);
}
public class SettingsCategories
{
private String settingText;
private int imgResId;
SettingsCategories(String settingText,int imgResId)
{
this.settingText = settingText;
this.imgResId = imgResId;
}
public String getSettingText()
{
return this.settingText;
}
public int getImgResId()
{
return this.imgResId;
}
}
}
and finally these are my xml layouts (the first one is the main view and the second one is the view of a single item in the list
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<SearchView
android:id="#+id/searchFunction"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</SearchView>
<ListView
android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
</RelativeLayout>
this represents an individual item in the list
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView
android:layout_width="52dp"
android:layout_height="52dp"
android:id="#+id/settingCategoryImg"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="52dp"
android:text=""
android:id="#+id/settingCategoryName"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/settingCategoryImg"
/>
</RelativeLayout>
You are setting null adapter so it is not refreshing.
you are commented initialization part
check in the following method:
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
// remove the dividers from the ListView of the ListFragment
settingsList = getListView();
settingsList.setDivider(null);
mItems = new ArrayList<SettingsCategories>();
Resources resources = getResources();
for(int c = 0; c < numCategories; c++)
{
mItems.add(new SettingsCategories(CategoryArray[c],resIds[c]));
}
// initialize and set the list adapter
// settingsAdapter = new SettingsAdapter(this.getActivity(), mItems);
setListAdapter(new SettingsAdapter(getActivity(), mItems));
settingsList.setAdapter(settingsAdapter);
}
Your are using ListFragement and again inflating layout. that is not a good idea. when you are extending listfragment then inflating the layout is not required and and modify above method like:
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
// remove the dividers from the ListView of the ListFragment
settingsList = getListView();
settingsList.setDivider(null);
mItems = new ArrayList<SettingsCategories>();
Resources resources = getResources();
for(int c = 0; c < numCategories; c++)
{
mItems.add(new SettingsCategories(CategoryArray[c],resIds[c]));
}
// initialize and set the list adapter
settingsAdapter = new SettingsAdapter(this.getActivity(), mItems);
//setListAdapter(new SettingsAdapter(getActivity(), mItems));
settingsList.setAdapter(settingsAdapter);
}
Hi i am using view pager indicator with three fragments and in one of the i have a list view that show the content of my SQLite Database but when a add data to my table the list view doesn't show he new data that i have added here is my code:
public class caleryhistory extends SherlockListFragment {
List<calery_lagari> Calery_lagari;
calery_lagari_SQLiteData data;
ArrayAdapter<calery_lagari> adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.calery_history, null);
data = new calery_lagari_SQLiteData(getActivity());
data.open();
Calery_lagari = data.findall();
adapter = new ArrayAdapter<calery_lagari>(getActivity(),
R.layout.listback_layout, Calery_lagari);
adapter.notifyDataSetChanged();
setListAdapter(adapter);
adapter.notifyDataSetChanged();
return v;
}
so any help?
Thanks in advance! :)
Update
import java.util.List;
import mr.chag.va.lagar.R;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.actionbarsherlock.app.SherlockListFragment;
public class caleryhistory extends SherlockListFragment {
List<calery_lagari> Calery_lagari;
calery_lagari_SQLiteData data;
ArrayAdapter<calery_lagari> adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.calery_history, null);
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
data = new calery_lagari_SQLiteData(getActivity());
data.open();
Calery_lagari = data.findall();
adapter = new ArrayAdapter<calery_lagari>(getActivity(),
R.layout.listback_layout, Calery_lagari);
adapter.notifyDataSetChanged();
ListView listView = (ListView)view.findViewById(android.R.id.list);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
super.onViewCreated(view, savedInstanceState);
}
}
my layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
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="clear"
android:text="clear all" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
The best way when extending SherlockListFragments is to have onCreateView return the the inflated view, then override onViewCreated. And put your code that changes your view in there.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle b){
return inflater.inflate(R.layout.calery_history, null);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
data = new calery_lagari_SQLiteData(getActivity());
data.open();
Calery_lagari = data.findall();
adapter = new ArrayAdapter<calery_lagari>(getActivity(), view.R.layout.listback_layout, Calery_lagari);
adapter.notifyDataSetChanged();
setListAdapter(adapter);
adapter.notifyDataSetChanged();
}
First problem is that you set adapter in onCreateView. In onCreateView list view is not created yet. Second you need to set adapter to correct list view. Because you override oncreateview you can't use setListAdapter because it's referring to list view from default viet. Try this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.calery_history, null);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
data = new calery_lagari_SQLiteData(getActivity());
data.open();
Calery_lagari = data.findall();
adapter = new ArrayAdapter<calery_lagari>(getActivity(),
view.R.layout.listback_layout, Calery_lagari);
ListView listView = (ListView)view.findViewById(R.id.YOUR_LISTVIEW_ID);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
You cannot call setListAdapter at this point, as the view is not yet set.
You need to wait until onViewCreated.