I've implemented a ListView in the sense of a master detail view:onItemClick() calls new Activity with details according to the list item.
onItemLongClick calls ActionMode.Callback to provide the selection of multiple list items. I already solved the problem to avoid calling onItemClick() when an item should be selected by returning true in onItemLongClick().
The problem is the selection is made/is visualized after I clicked an item and returned from the activity.
Please not the standard listSelector. I'm not sure if this is the correct way/solution. I tried to implement a custom listSelector but it did not work properly.
Any suggestions?
XML of the ListView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ResultFragment" >
<!-- standard list_selector_background -->
<ListView
android:id="#+id/fragment_ergebnis_listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:choiceMode="multipleChoice"
android:divider="#color/gray_3"
android:dividerHeight="1dp"
android:listSelector="#android:drawable/list_selector_background"
android:saveEnabled="true" >
</ListView>
</LinearLayout>
Code of the Fragment
public class ResultPOJOFragment extends Fragment implements OnItemClickListener, OnItemLongClickListener {
private Activity mActivity;
private ActionModeCallback mActionModeCallback;
private ActionMode mActionMode;
private ListView mListView;
private ResultAdapter mAdapter;
private ResultDAO mResultDAO;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mActivity = getActivity();
mResultDAO = new ResultDAO(mActivity);
View fragmentView = inflater.inflate(R.layout.fragment_result, container, false);
mAdapter = new ResultAdapter(mActivity);
mListView = (ListView) fragmentView.findViewById(R.id.fragment_result_listView);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener((OnItemClickListener) this);
mListView.setOnItemLongClickListener((OnItemLongClickListener) this);
mActionModeCallback = new ActionModeCallback();
return fragmentView;
}
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
ResultPOJO result = new ResultPOJO();
result = mAdapter.getItem(position);
/* Show activity with details */
Intent resultDetailsIntent = new Intent(getActivity(), ResultPOJODetailsActivity.class);
if (resultDetailsIntent != null) {
resultDetailsIntent.putExtra(AppConstants.TAG_RESULT, result);
startActivity(resultDetailsIntent);
}
}
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (mActionMode != null) {
/* true: to avoid calling onItemClick() */
return true;
} else {
mActionMode = mActivity.startActionMode(mActionModeCallback);
view.setSelected(true);
}
mActionMode = mActivity.startActionMode(new ActionModeCallback());
return true;
}
private void selectAllEntries() {
for (int i = 0; i < mListView.getChildCount(); i++) {
mListView.setItemChecked(i, true);
}
}
private void deselectAllEntries() {
for (int i = 0; i < mListView.getChildCount(); i++) {
mListView.setItemChecked(i, false);
}
}
private void refreshView() {
mAdapter.notifyDataSetChanged();
}
private class ActionModeCallback implements ActionMode.Callback {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.result_fragment_cab, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_cab_result_fragment_select_all:
selectAllEntries();
break;
case R.id.menu_item_cab_result_fragment_deselect_all:
deselectAllEntries();
break;
default:
break;
}
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
}
}
Related
I have to implement action mode in fragment, but its gets nullpointer exception in action mode. I have tried so much but not gets any results, Please help me I am new in android. I have also tried startActionMode but not impact. I have wasted my time & searched lot of code not found any solution. Please help me
public class GalleryFragment extends Fragment {
private GalleryViewModel galleryViewModel;
private ActionModeCallback actionModeCallback;
private ActionMode actionMode;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
galleryViewModel =
ViewModelProviders.of(this).get(GalleryViewModel.class);
View root = inflater.inflate(R.layout.fragment_gallery, container, false);
final TextView textView = root.findViewById(R.id.text_gallery);
galleryViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
final Button btnLoad = root.findViewById(R.id.load);
btnLoad.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
enableActionMode(1, true );
}
});
return root;
}
public void enableActionMode(int position, boolean bool) {
int count = 4;
if(actionMode == null) {
actionMode = ((AppCompatActivity)getActivity()).startSupportActionMode(actionModeCallback);
}
if (count == 0) {
actionMode.finish();
actionMode = null;
} else {
actionMode.setTitle(String.valueOf(count));
actionMode.invalidate();
}
}
private class ActionModeCallback implements ActionMode.Callback {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.actionbar_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// getSupportActionBar().hide();
menu.findItem(R.id.action_delete).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
Log.d("API123", ""+item.getItemId());
switch (item.getItemId()) {
case R.id.action_delete:
// delete all the selected rows
//mode.finish();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
//clear selections
mode.finish();
actionMode = null;
}
}
}
This is mycode, null pointer in actionmode. please help me i wasting my time. searching lot of, no result found
I need Add SearchBar in ActionBar handle with more Fragments like whatsApp
when Search in Tab chats get data and when Search in Tab Status get another data
How do This?This is My Code there is 3 tabs i need every tab there is SearchView
This Activity which there is on Fragments
public class ActivityForIncludeFragments extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_for_include_fragments);
ViewPager viewPager = (ViewPager)findViewById(R.id.viewPager);
CategoryAdapter adapter = new CategoryAdapter(this,getSupportFragmentManager());
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout)findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
invalidateOptionsMenu();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem menuItemAddData = menu.findItem(R.id.add_data);
MenuItem menuItemActionSearch = menu.findItem(R.id.action_search);
menuItemAddData.setVisible(false);
menuItemActionSearch.setVisible(false);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.add_stocking_warehouse:
Intent intent = new Intent(ActivityForIncludeFragments.this,StockingWarehouse.class);
startActivity(intent);
break;
case R.id.add_reportes:
Intent intentReport = new Intent(ActivityForIncludeFragments.this,TableDaliyMovmentes.class);
startActivity(intentReport);
break;
}
return super.onOptionsItemSelected(item);
}
}
and This Fragment there is the data
public class AddPremissionFragment extends Fragment implements
LoaderManager.LoaderCallbacks<ArrayList<ItemsStore>>
,SearchView.OnQueryTextListener {
public AddPremissionFragment() {
// Required empty public constructor
}
public static final String ID_PERMISSION = "id";
public static final String NAME_PERMISION = "namePErmission";
public static final String NOTES_PERMISSION = "notes";
public static final String DIALOG_PERMISSION = "dialogPermission";
FloatingActionButton fab_add_permission;
ListView mListView;
public static AdapterAddPermission adapterAddPermission;
TaskDbHelper dbHelper;
ArrayList<ItemsStore> itemsPermissions = new ArrayList<ItemsStore>();
private ProgressBar progressBarPermission;
//Identifier for the category dataloader;
public static final int PERMISSION_LOADER = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_add_premission, container, false);
TextView namePremission = (TextView)view.findViewById(R.id.ETTypeStore);
dbHelper = new TaskDbHelper(getActivity());
mListView = (ListView) view.findViewById(R.id.listViewAddPermission);
progressBarPermission =(ProgressBar)view.findViewById(R.id.progressBarPermission);
adapterAddPermission = new AdapterAddPermission(getContext(), itemsPermissions);
View emptyView = view.findViewById(R.id.empty_view_permission);
mListView.setEmptyView(emptyView);
mListView.setAdapter(adapterAddPermission);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Toast.makeText(getContext(), "Click :"+ position, Toast.LENGTH_SHORT).show();
ItemsStore itemSPermision = itemsPermissions.get(position);
Bundle bundle = new Bundle();
bundle.putInt(ID_PERMISSION, itemSPermision.getId());
bundle.putString(NAME_PERMISION, itemSPermision.getNamePermission());
bundle.putString(NOTES_PERMISSION, itemSPermision.getNotes());
// startActivity(intent);
// long id = cursor.getLong(cursor.getColumnIndex(TaskContract.TaskEntry._ID));
EditPermissionFragment f = new EditPermissionFragment();
f.setArguments(bundle);
f.show(getFragmentManager(),DIALOG_PERMISSION);}});
// namePremission.setText("Name Permission");
fab_add_permission = (FloatingActionButton)view.findViewById(R.id.fab_add_permission);
fab_add_permission.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new EditPermissionFragment().show(getFragmentManager(),DIALOG_PERMISSION);
}
});
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Kick off the loader
getActivity().getSupportLoaderManager().initLoader(PERMISSION_LOADER, null, this);
}
#Override
public Loader<ArrayList<ItemsStore>> onCreateLoader(int id, Bundle args) {
return new LoaderPErmission(getContext().getApplicationContext(),itemsPermissions,dbHelper);
}
#Override
public void onLoadFinished(Loader<ArrayList<ItemsStore>> loader, ArrayList<ItemsStore> data) {
progressBarPermission.setVisibility(View.GONE);
mListView.setVisibility(View.VISIBLE);
adapterAddPermission.swapData(data);
}
#Override
public void onLoaderReset(Loader<ArrayList<ItemsStore>> loader) {
adapterAddPermission.swapData(Collections.<ItemsStore>emptyList());
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
// Inflate the menu; this adds items to the action bar if it is present.
getActivity().getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem menuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
searchView.setOnQueryTextListener(this);
super.onCreateContextMenu(menu, v, menuInfo);
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
itemsPermissions = dbHelper.getAllItemsPermissionBySearch(newText);
if (itemsPermissions !=null){
adapterAddPermission.setFilter(itemsPermissions);
// getSupportLoaderManager().restartLoader(Daily_LOADER,null,this);
}
return false;
}
}
Please check which fragment is visible using this
Fragment fragment = getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (fragment != null && fragment.isVisible()) {
if (fragment instanceof ChatFragment) {
....
}
else { }
}
I have created only tool bar in my fragment.I have implemented the action mode for multiple deleting the list view.But the action mode will open above the toolbar(i.e)action bar.How to display that action mode over the toolbar.I have tried <item name="windowActionModeOverlay">true</item> in my theme but it does not works.`
public class Event_notification extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
List<String> myList;
private List<FeedItem> feedsList= new ArrayList<FeedItem>();
ListView listView;
TextView emptyview;
String message;
EventNotification_adapter adapter;
String userID,userid_share;
CheckBox check;
ArrayList<String> list = new ArrayList<String>();
String EventStatus,date;
Dialog dialog;
public static ActionMode mActionMode;
ActionBar action;
private JSONObject EventJsonObject;
protected static final String TAG = "NOTIFICATION";
ProgressWheel pw;
ResetPasswordActivity obj = new ResetPasswordActivity();
Constants constants=new Constants();
private SwipeRefreshLayout swipeRefreshLayout;
public static final String MY_PREFS_NAME = "MyPrefsFile";
public Event_notification() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment Event_notification.
*/
// TODO: Rename and change types and number of parameters
#Override
public void onCreate(Bundle savedInstanceState) {
// getActivity().getWindow().requestFeature(Window.FEATURE_ACTION_MODE_OVERLAY);
super.onCreate(savedInstanceState);
// getActivity().getActionBar().hide();
SharedPreferences prefs1 = getContext().getSharedPreferences(MY_PREFS_NAME, getContext().MODE_PRIVATE);
userID= prefs1.getString("userid", null);
System.out.println("userid" + userID);
// actionBar.hide();
// setHasOptionsMenu(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
System.out.println("Notification Fragment");
View v=inflater.inflate(R.layout.fragment_event_notification, container, false);
//return inflater.inflate(R.layout.row_eventnotification, container, false);
FontChangeCrawler fontChanger = new FontChangeCrawler(getContext().getAssets(), "arial.ttf");
fontChanger.replaceFonts((ViewGroup) v);
emptyview=(TextView)v.findViewById(R.id.empty_view);
listView=(ListView)v.findViewById(R.id.recycler_view);
swipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(this);
check=(CheckBox)v.findViewById(R.id.check1);
pw = (ProgressWheel) v.findViewById(R.id.pw_spinner);
obj.styleRandom(pw, getContext());
getnotification();
adapter=new EventNotification_adapter(getContext(),feedsList,Event_notification.this);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
adapter.removeSelection();
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
mActionMode = mode;
mActionMode.getMenuInflater().inflate(R.menu.multiple_delete, menu);
return true;
}
#Override
public boolean onActionItemClicked(final ActionMode mode,
final MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.selectAll:
final int checkedCount = feedsList.size();
// If item is already selected or checked then remove or
// unchecked and again select all
for (int i = 0; i < checkedCount; i++) {
listView.setItemChecked(i, true);
// listviewadapter.toggleSelection(i);
}
mode.setTitle(checkedCount + " Selected");
return true;
case R.id.unselect:
mode.finish();
return false;
case R.id.delete:
// Add dialog for confirmation to delete selected item
// record.
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(getContext(), R.style.AppCompatAlertDialogStyle);
builder.setMessage("Do you want to delete selected record(s)?");
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
SparseBooleanArray selected = adapter
.getSelectedIds();
for (int i = (selected.size()); i >= 0; i--) {
if (selected.valueAt(i)) {
// String selecteditem=Integer.parseInt(selected.keyAt(i));
//
FeedItem movie = feedsList.get(selected.keyAt(i));
list.add(movie.getMessageid());
System.out.println("EVENT ID____"+list);
int selecteditem = selected.keyAt(i);
// String selecteditem1=Integer.toString(item.getItemId());
int selecteditem1=item.getItemId();
EventDelete();
dialog.dismiss();
// Remove selected items following the ids
adapter.remove(selecteditem);
System.out.println("FEEDLIST SIZE+++"+feedsList.size());
if(feedsList.size()==0){
emptyview.setVisibility(View.VISIBLE);
}
else{
emptyview.setVisibility(View.GONE);
}
}
}
// Close CAB
mode.finish();
selected.clear();
}
});
AlertDialog alert = builder.create();
//alert.setIcon(R.drawable.questionicon);// dialog Icon
alert.setTitle("Confirmation"); // dialog Title
alert.show();
return true;
default:
mode.finish();
return false;
}
}
`
try this.
android.view.ActionMode mMode = toolbar.startActionMode(new Callback() {
#Override
public boolean onPrepareActionMode(
ActionMode mode, Menu menu) {
return false;
}
#Override
public void onDestroyActionMode(
ActionMode mode) {
}
#Override
public boolean onCreateActionMode(
ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(
ActionMode mode, MenuItem item) {
return false;
}
});
if you want to Fininsh Action mode
if (mMode != null) {
mMode.finish();
}
And don't forget to add following in your main Theme under styles.xml
<item name="android:windowActionModeOverlay">true</item>
You are good to go.
Is it possible to implement search (filter ListView) in Fragments, which would filter ListView by the text, written to search query in Action Bar in the same layout immediately? Or does the search require activity class and it's impossible to deal with it?
Example: like these guys did (I'm not sure, if they used either Acitivity or Fragment)
When user adds some text to the searchbar
EDIT: what am I doing wrong?
public class AllLists extends Fragment /*implements SearchView.OnQueryTextListener*/{
private TypedArray navMenuIcons;
private Context context;
private int position = 0;
private String location;
private List<Item> items = new ArrayList<Item>();
private ListView listView;
private CustomListAdapter adapter;
public AllLists(Context context) {
this.context = context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.alllists, container, false);
View header = inflater.inflate(R.layout.list_header, null);
// View list_view = inflater.inflate(R.layout.list_item, null);
ImageView image = (ImageView) header.findViewById(R.id.small_icon);
header.setClickable(false);
// ImageView logo = (ImageView) list_view.findViewById(R.id.image);
navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
Bundle bundle = getArguments();
position = bundle.getInt("position");
location = bundle.getString("location");
image.setImageDrawable(navMenuIcons.getDrawable(position));
DatabaseHandler db = new DatabaseHandler(context);
items = db.getAllItems(location);
listView = (ListView) rootView.findViewById(R.id.list);
adapter = new CustomListAdapter(context, items);
listView.setAdapter(adapter);
listView.addHeaderView(header);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (location.equals("accommodation") || location.equals("eat") || location.equals("events")
|| location.equals("entertainment") || location.equals("places") || location.equals("cinema")) {
Intent i = new Intent(context, ItemScreen.class);
i.putExtra("position", position - 1);
i.putExtra("location", location);
startActivity(i);
}
}
});
setHasOptionsMenu(true);
return rootView;
}
/*SearchView.OnQueryTextListener(new SearchView.OnQueryTextListener){
}*/
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.main, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
/*public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
adapter.getFilter().filter(cs);
}*/
#Override
public boolean onQueryTextChange(String s) {
adapter.getFilter().filter(s);
return false;
}
});
}
}
what you are aiming to do is send the search query to the fragment containing list... and to do that you need a communication between the activity and the fragment which it contains.. so as the user types the search query fragment containing list will filter accordingly...
step 1 : define a public method in a fragment which will be accessed by the activity which it is attached to.
Class ExampleFragment {
public void refreshList(String search){
// code to refresh the list view
}
step 2 : find the fragment attached to your activity by below method
ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
step 3 : using the fragment access the public method of that fragment and which will refresh the list view for eg:
String searchQuery = "apple";
fragment.refreshList(searchQuery)
}
I'm trying to go to a specific fragment and I intialisate this in Activity. But I don't get any error on my screen but on my device, my app is stopped running, he doesn't go in Fragment. What can be the problem? Thanx for you help. Below you find my code:
public class SubCatActivity extends Activity {
int hoofdCat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subcat);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.replace(R.id.container, new SubCatFragment())
.commit();
}
hoofdCat = Integer.parseInt(getIntent().getStringExtra("hoofdCat"));
}
public int getHoofdCat(){return hoofdCat;}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.info, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
My Fragment:
public class SubCatFragment extends Fragment implements SubCatFragmentInteractionListener {
private SubCatFragmentInteractionListener mListener;
public SubCatFragment(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_subcat, container, false);
ListView lstSubcat = (ListView) rootView.findViewById(R.id.lvSubcat);
ArrayList<String> subcat = new ArrayList<String>();
SubCatActivity activity = (SubCatActivity)getActivity();
int hoofdcat =activity.getHoofdCat();
DBAdapter db = new DBAdapter(getActivity().getBaseContext());
db.open();
Cursor c = db.getAllSubcat(hoofdcat);
if(c.moveToFirst())
{
do{
subcat.add(c.getString(1));
}while (c.moveToNext());
}
db.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, subcat);
lstSubcat.setAdapter(adapter);
lstSubcat.setOnItemClickListener(lstSubcatItemClickListener);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (SubCatFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement HoofdCatFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
private ListView.OnItemClickListener lstSubcatItemClickListener = new ListView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
//mListener.showSubCatActivity(pos+1);
}
};
}
Use FragmentActivity.
public class SubCatActivity extends FragmentActivity{
....
}
FragmentActivity
Replace or add the fragment inside onPostCreate, not on onCreate.