I've searched everywhere and I also tried every code I looked into but unfortunately none of them worked. :( I already added registerForContextMenu() method but it still won't pop a menu when i click on an item in my list. Please help. I'm going crazy already. :( Here's what I got so far...
public class BorrowersFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
Button btnSearch,btnGetAll;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public BorrowersFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment BorrowersFragment.
*/
// TODO: Rename and change types and number of parameters
public static BorrowersFragment newInstance(String param1, String param2) {
BorrowersFragment fragment = new BorrowersFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
/*#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_borrowers, container, false);
}*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
View borrowerView = inflater.inflate(R.layout.fragment_borrowers, container, false);
btnSearch = (Button) borrowerView.findViewById(R.id.btnSearch);
//btnSearch.setOnClickListener(this);
btnGetAll = (Button) borrowerView.findViewById(R.id.btnGetAll);
//btnGetAll.setOnClickListener(this);
BorrowerDBHelper repo = new BorrowerDBHelper(this.getContext());
UserDBHelper repoUser = new UserDBHelper(this.getContext());
User user = repoUser.getUserInfo();
ArrayList<HashMap<String, String>> borrowerList = repo.getBorrowerList(user.getId());
if(borrowerList.size()!=0) {
ListView lv = (ListView) borrowerView.findViewById(R.id.borrowerListView);
ListAdapter adapter = new SimpleAdapter( BorrowersFragment.this.getContext(),borrowerList, R.layout.view_borrower, new String[] { "id","full_name"}, new int[] {R.id.borrower_Id, R.id.borrower_name});
lv.setAdapter(adapter);
registerForContextMenu(lv);
}else{
Toast.makeText(this.getContext(),"No student!",Toast.LENGTH_SHORT).show();
}
return borrowerView;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(Menu.NONE, R.id.view_profile_item, Menu.NONE, "View Profile");
menu.add(Menu.NONE, R.id.view_payments_item, Menu.NONE, "View Payment History");
menu.add(Menu.NONE, R.id.add_payment_item, Menu.NONE, "Add Payment");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.view_profile_item:
Log.i("ContextMenu", "Item 1a was chosen");
return true;
case R.id.view_payments_item:
Log.i("ContextMenu", "Item 1b was chosen");
return true;
case R.id.add_payment_item:
Log.i("ContextMenu", "Item 1b was chosen");
return true;
}
return super.onContextItemSelected(item);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
/*#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}*/
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Please do note that this fragment is called/shown when I choose it from a navigation drawer which is inside a MainActivity.
Hope you can help me. Thanks!
Do you want to open a menu when user clicks on a ListView item?
So you can simply set an OnLongClickListener (or a simple OnClickListener depending on what you are trying to do) on the items and open an :
android.support.v7.widget.PopupMenu:
#Override
public boolean onLongClick(View v) {
PopupMenu menu = new PopupMenu(YourActivity.this, listItem);
menu.getMenuInflater().inflate(R.menu.your_menu_file, menu.getMenu());
menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.your_first_menu_item:
// do something
break;
}
return false;
}
});
menu.show();
return false;
}
forgive my innocence... this is so embarassing. its actually working. I just have to long click it.
XD I'm so sorry for the waste of time. Cheers everyone.
Related
I am trying to save some information when I click a button from the "new project" page. Afterwards, I want to save this information in the "Projects" pages and display it in "My projects" page. For some reason, it doesn't display anything. Help, please?
new project page:
public class NewProjectFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
LinearLayout container;
TextView new_project;
String tv_project_name;
private OnFragmentInteractionListener mListener;
public NewProjectFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment NewProjectFragment.
*/
// TODO: Rename and change types and number of parameters
public static NewProjectFragment newInstance(String param1, String param2) {
NewProjectFragment fragment = new NewProjectFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
Button addButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_new_project, container, false);
new_project=(TextView) view.findViewById(R.id.textView_new_project);
tv_project_name= (String) new_project.getText();
addButton= (Button) view.findViewById(R.id.button_add_project);
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
addItem(tv_project_name);
}
});
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
public void addItem(String name) {
Projects project=new Projects();
project.addItem(tv_project_name);
}
}
my project page:
public class MyProjectsFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public MyProjectsFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment MyProjectsFragment.
*/
// TODO: Rename and change types and number of parameters
public static MyProjectsFragment newInstance(String param1, String param2) {
MyProjectsFragment fragment = new MyProjectsFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
ListView listView;
ArrayList<String> listItems= Projects.getArrayList();
ArrayAdapter<String> adapter;
#Override
public void onStart() {
super.onStart();
adapter= new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, listItems);
listView.setAdapter(adapter);
Create();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_my_projects, container, false);
listView=(ListView) view.findViewById(R.id.listview_projects);
listItems= new ArrayList<String>();
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
public void Create() {
/* listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
}
});*/
}
}
projects class:
public class Projects {
static ArrayList<String> names= new ArrayList<String>();
public void addItem(String name)
{
names.add(name);
}
public static ArrayList getArrayList()
{
return names;
}
}
Each time you enter My Project ,you did listItems= new ArrayList<String>() in onCreateView. It has no data definately.
And when you addItem each time, you initialize a new Project,which is weird.
My advice is:
public class Projects {
static ArrayList<String> names= new ArrayList<String>();
public static void addItem(String name)
{
names.add(name);
}
public static ArrayList getArrayList()
{
return names;
}
}
Project.getArrayList() to getList
Project.addItem("") to add data
This way is not very properly yet,but it should work.
I am just creating a simple List-fragment but my application won't run on AVD .Can't figure out error.
Here is my MainActivity.java
package in.blogspot.food_n_moreblog.recipes;
public class MainActivity extends Activity implements catagorylistfrag.OnFragmentInteractionListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void itemClicked(long id){
catagorydetailfragment detailfragment=new catagorydetailfragment();
FragmentTransaction ft=getFragmentManager().beginTransaction();
detailfragment.setWorkout(id);
ft.replace(R.id.fragment_container,detailfragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
}
DetailFragment(java code)
package in.blogspot.food_n_moreblog.recipes;
public class catagorydetailfragment extends Fragment {
private long workoutID;
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
if (savedInstanceState!=null)
{
workoutID=savedInstanceState.getLong("workoutID");
}
return inflater.inflate(R.layout.catagorydetails,container,false);
}
#Override
public void onStart()
{
super.onStart();
View view=getView();
if(view!=null){
TextView title=(TextView)view.findViewById(R.id.titleText);
CatagoryValues value=CatagoryValues.catagories[(int)workoutID];
title.setText(value.getName());
TextView des=(TextView)view.findViewById(R.id.detailText);
des.setText(value.getDescription());
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
savedInstanceState.putLong("workoutID",workoutID);
}
public void setWorkout(long id){
this.workoutID=id;
}
}
List item Fragment java code
package in.blogspot.food_n_moreblog.recipes;
public class catagorylistfrag extends ListFragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
// TODO: Rename and change types of parameters
public static catagorylistfrag newInstance(String param1, String param2) {
catagorylistfrag fragment = new catagorylistfrag();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public catagorylistfrag() {
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
/*if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}*/
String[] names=new String[CatagoryValues.catagories.length];
for(int i=0;i<names.length;i++){
names[i]=CatagoryValues.catagories[i].getName();
}
// TODO: Change Adapter to display your content
ArrayAdapter<String> adapter=new ArrayAdapter<String>(inflater.getContext(),android.R.layout.simple_expandable_list_item_2,names);
setListAdapter(adapter);
return super.onCreateView(inflater,container,savedInstanceState);
}
#Override
public void onAttach(Context context) {
/* super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
*/super.onAttach(context);
Activity a;
if (context instanceof Activity){
a=(Activity) context;
this.mListener=(OnFragmentInteractionListener)a;
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.itemClicked(id);
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
// public void onFragmentInteraction(String id);
void itemClicked(long id);
}
}
Try this array adapter in your list item Fragment java code:
ArrayAdapter<String> adapter=new ArrayAdapter<String>(inflater.getContext(),android.R.layout.android.R.layout.simple_list_item_1,names);
I want to write really cool program with fantastic code, so I decided to understand code created by Android studio (think it must be awesome, because wrote by professionals).
How can I change a fragments using navigation drawer? I added some code to onNavigationDrawerItemSelected, but it doesn't work (app crashes)
What is PlaceholderFragment? Can't understand what it does and how it works.
Here is a code of MainActivity.java. Help me please. Thank you.
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
private AlarmClockFragment mAlarmClockFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment fragment;
FragmentManager fragmentManager = getSupportFragmentManager();
fragment = new AlarmClockFragment();
fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
/*FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();*/
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return 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;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
AlarmClockFragment:
public class AlarmClockFragment extends Fragment implements AbsListView.OnItemClickListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/**
* The fragment's ListView/GridView.
*/
private AbsListView mListView;
/**
* The Adapter which will be used to populate the ListView/GridView with
* Views.
*/
private ListAdapter mAdapter;
// TODO: Rename and change types of parameters
public static AlarmClockFragment newInstance(String param1, String param2) {
AlarmClockFragment fragment = new AlarmClockFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public AlarmClockFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
// TODO: Change Adapter to display your content
mAdapter = new ArrayAdapter<DummyContent.DummyItem>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, DummyContent.ITEMS);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_alarmclock, container, false);
// Set the adapter
mListView = (AbsListView) view.findViewById(android.R.id.list);
((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);
// Set OnItemClickListener so we can be notified on item clicks
mListView.setOnItemClickListener(this);
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onFragmentInteraction(DummyContent.ITEMS.get(position).id);
}
}
/**
* The default content for this Fragment has a TextView that is shown when
* the list is empty. If you would like to change the text, call this method
* to supply the text it should use.
*/
public void setEmptyText(CharSequence emptyText) {
View emptyView = mListView.getEmptyView();
if (emptyView instanceof TextView) {
((TextView) emptyView).setText(emptyText);
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(String id);
}
}
What's is the code of your AlarmClockFragment()?
PlaceholderFragment is just a simple example of how Fragment should look like.
Your code looks reasonable, you're doing the right thing in onNavigationDrawerItemSelected. The PlaceholderFragment is just an example fragment - it's right to replace it with the actual fragment you want to use. Without the stack trace, it's difficult to say why your application is crashing, it's likely a problem with your AlarmClockFragment.
I have a layout with two fragments in my app (one listFragment containing the titles and one containing the details.)
After starting the everything works fine. The Detail-Fragment is updated each time I click on an entry in the listfragment.
Yet after changing the orientation every new detail-Fragment is just opened upon the old detail fragment. (Due to my low reputation I can't post any screenshots, I am sorry.)
My Activity containing the two fragments:
/**
* A fragment representing a list of Items.
* <p />
* Large screen devices (such as tablets) are supported by replacing the ListView
* with a GridView.
* <p />
*/
public class MedicationTitlesFragment extends ListFragment
implements AdapterView.OnItemClickListener, SearchView.OnQueryTextListener, SearchView.OnCloseListener, LoaderManager.LoaderCallbacks<Cursor> {
/**
* The Adapter which will be used to populate the ListView/GridView with
* Views.
*/
//private ListAdapter mAdapter;
private static final String TAG = MedicationTitlesFragment.class.getSimpleName();
private static final int LOADER_ID = 1;
//private OnFragmentInteractionListener mListener;
private OnMedicationSelectedListener mMedicationSelectedListener;
/**
* The fragment's ListView/GridView.
*/
private ListView mListView;
private LoaderManager.LoaderCallbacks<Cursor> mLoaderCallbacks;
private SearchView mSearchView;
private String mCurFilter;
private SimpleCursorAdapter mAdapter;
static final String[] RPINFO_SUMMARY_PROJECTION = new String[] {
RpEntry.Columns.SNAME, RpEntry.Columns._ID, RpEntry.Columns.ONAME, RpEntry.Columns.PHZNR,
RpEntry.Columns.ZNR_FORMATTED, RpEntry.Columns.RSIGN_P1, RpEntry.Columns.RSIGN_P5
};
// TODO: Rename and change types of parameters
public static MedicationTitlesFragment newInstance(String param1, String param2) {
MedicationTitlesFragment fragment = new MedicationTitlesFragment();
Bundle args = new Bundle();
return fragment;
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public MedicationTitlesFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "entered onCreate");
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item_list, container, false);
// Set the adapter
mListView = (ListView) view.findViewById(android.R.id.list);
((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);
// Set OnItemClickListener so we can be notified on item clicks
mListView.setOnItemClickListener(this);
setEmptyText("Keine Einträge");
return view;
}
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mMedicationSelectedListener = (OnMedicationSelectedListener) activity;
//this.getListView().setOnItemClickListener(this);
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mMedicationSelectedListener = null;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.d(TAG, "entered onListItemClick");
getListView().setItemChecked(position, true);
Uri rpDetailUri = Uri.parse(RpInfoContentProvider.CONTENT_URI + "/" + id);
Log.d(TAG, "rpDetailUri: " + rpDetailUri.toString());
mMedicationSelectedListener.onMedicationSelected(rpDetailUri);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (null != mMedicationSelectedListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
//mListener.onFragmentInteraction(DummyContent.ITEMS.get(position).id);
}
}
/**
* The default content for this Fragment has a TextView that is shown when
* the list is empty. If you would like to change the text, call this method
* to supply the text it should use.
*/
public void setEmptyText(CharSequence emptyText) {
View emptyView = mListView.getEmptyView();
if (emptyText instanceof TextView) {
((TextView) emptyView).setText(emptyText);
}
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// This is called when a new Loader needs to be created. This
// sample only has one Loader, so we don't care about the ID.
// First, pick the base URI to use depending on whether we are
// currently filtering.
Uri baseUri = null;
if (null != mCurFilter)
baseUri = Uri.withAppendedPath(RpEntry.CONTENT_URI, Uri.encode(mCurFilter));
else
baseUri = RpEntry.CONTENT_URI;
// Now create and return a CursorLoader that will take care of
// // creating a Cursor for the data being displayed.
return new CursorLoader(
getActivity().getBaseContext(),
baseUri,
RPINFO_SUMMARY_PROJECTION,
null,
null,
RpEntry.Columns.SNAME + " COLLATE LOCALIZED ASC");
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Der Loader hat fertig geladen, die Daten können nun im UI angezeigt werden
// switch to handle multiple loaders
switch(loader.getId()) {
case LOADER_ID:
mAdapter.swapCursor(data);
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
#Override
public boolean onClose() {
if (!TextUtils.isEmpty(mSearchView.getQuery())) {
mSearchView.setQuery(null, true);
}
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
Log.d(TAG, "entered onQueryTextSubmit");
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
Log.d(TAG, "enteredOnQueryTextChanged");
// Called when the action bar search text has changed. Update
// the search filter, and restart the loader to do a new query
// with this filter.
mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
getLoaderManager().restartLoader(LOADER_ID, null, mLoaderCallbacks);
return true;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnMedicationSelectedListener {
// TODO: Update argument type and name
public void onMedicationSelected(Uri uri);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setEmptyText("Keine Arzneimitteldaten geladen");
setHasOptionsMenu(true);
String[] dataColums = { RpEntry.Columns.SNAME };
int[] viewIDs = { android.R.id.text1};
mAdapter = new SimpleCursorAdapter(
getActivity().getBaseContext(),
android.R.layout.simple_list_item_1,
null,
dataColums,
viewIDs,
0);
this.setListAdapter(mAdapter);
// this.setListShown(false);
mLoaderCallbacks = this;
LoaderManager lm = getLoaderManager();
lm.initLoader(LOADER_ID, null, mLoaderCallbacks);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
Log.d(TAG, "entered onCreateOptionsMenu");
// Place an action bar item for searching.
MenuItem item = menu.add("Search");
item.setIcon(android.R.drawable.ic_menu_search);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
SearchView sv = new SearchView(getActivity());
sv.setOnQueryTextListener(this);
item.setActionView(sv);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_settings:
Log.d(TAG, "action_settings clicked");
Toast.makeText(getActivity().getApplicationContext(), "Einstellungen",
Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public static class MySearchView extends SearchView {
public MySearchView(Context context) {
super(context);
}
// The normal SearchView doesn't clear its search text when
// collapsed, so we will do this for it.
#Override
public void onActionViewCollapsed() {
setQuery("", false);
super.onActionViewCollapsed();
}
}
}
Thank you very much!
Make sure in your Activity's onCreate you have
void onCreate(Bundle savedState) {
...
if(savedState == null) {
// add your details fragment
} else {
// do not add your details fragment it's already there
}
}
[UPDATE]
Here is the code of AlsaceFragment class :
public class AlsaceNewsFragment extends ListFragment implements PullToRefreshAttacher.OnRefreshListener {
private static final String STATE_ACTIVATED_POSITION = "activated_position";
private int mActivatedPosition = ListView.INVALID_POSITION;
private RssServiceAlsace rssService;
private static final String URL_LALSACE = "http://www.lalsace.fr/actualite/alsace/rss";
private PullToRefreshAttacher mPullToRefreshAttacher;
/**
* Constructor
*/
public AlsaceNewsFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
refreshList(true);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (savedInstanceState != null && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
}
// CACHER SEPARATEURS
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
boolean enleverseparateur = settings.getBoolean("enleverseparateur", false);
if (enleverseparateur == true){
getListView().setDividerHeight(0);
getListView().setDivider(null);
}
// FIN CACHER SEPARATEURS
ListView listView = getListView();
mPullToRefreshAttacher = ((MainActivity) getActivity()).getPullToRefreshAttacher();
mPullToRefreshAttacher.setRefreshableView(listView, this);
}
public void setActivatedPosition(int position) {
if (position == ListView.INVALID_POSITION) {
getListView().setItemChecked(mActivatedPosition, false);
} else {
getListView().setItemChecked(position, true);
}
mActivatedPosition = position;
}
#Override
/**
* Called when pullToRefresh has been started
*/
public void onRefreshStarted(View view) {
refreshList(false); // We don't want to show progress dialog in this case
}
private void refreshList(boolean displayLoading){
rssService = new RssServiceAlsace(this, displayLoading);
// UNE SOURCE
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
boolean unesource = settings.getBoolean("unesource", false);
if (unesource == true) {
rssService.execute(URL_LALSACE);
} else {
rssService.execute(URL_LALSACE);
}
// FIN UNE SOURCE
}
public void notifyPullFinished() {
// Notify PullToRefreshAttacher that the refresh has finished
mPullToRefreshAttacher.setRefreshComplete();
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
ArticleAlsace article = (ArticleAlsace) this.getListAdapter().getItem(position);
Bundle arguments = new Bundle();
arguments.putString("URL", article.getUrl());
arguments.putString("TITRE", article.getTitle());
arguments.putString("SOURCE", article.getSource());
arguments.putString("DESCRIPTION", article.getDescription());
Fragment fragment = new WebBrowserFragment();
fragment.setArguments(arguments);
FragmentTransaction fragmentTransaction = getActivity().getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
I try to implement a new menu item in my Action Bar which will be visible when the user start the scroll in the listView of my app.
I would like to bind the click of the button with a method which will be responsible to scroll to the top of the listview.
To do this, i would like to use :
getListView().setSelectionAfterHeaderView();
Here is a piece of code of My main activity :
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_arrow_top :
// I would like to scroll to the top of my list here, but in this class (MainActivity) i don't have access to the list .. :(
AlsaceNewsFragment.goToTop();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
And here is the code of goToTop method in AlsaceNewFragment (which extends ListFragment) :
public static void goToTop() {
getListView().setSelectionAfterHeaderView();
}
But i get this error :
Cannot make a static reference to the non-static method getListView() from the type ListFragment
Maybe there is a better simple way to do what i want.
My app is composed on :
MainActivity which extends Activity
One ListFragment which create the list
An AlsaceAdapter which extends ArrayAdapter
Thanks a lot for your help
Try to remove the static keyword from goToTop() method. Static methods can't access instance data.