Android - Passing a search to a fragment - android

So I have an app that has tabs (4) that each have their own layout and class files. I also have a searchview widget in the actionbar.
What I am attempting to do is allow the user to search for something, get that as a string and then send it to the fragment so I can then use that string and update the UI after using it for a query.
Currently I have it so that the user enters in the text, a class handles the intent and so on a so forth, and then I get that variable in the fragment class that I need it in.
However, when I enter in something to the searchview and hit enter, a new window pops up but with a blank screen. No tabs. No searchview.
Surely I am doing something wrong. Does anyone have an suggestions or a change that I can make?
MainActivity.java
public class MainActivity extends FragmentActivity implements ActionBar.TabListener
{
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Home", "Most Recent", "Followed", "All Items" };
public String test = "test";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs)
{
actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position)
{
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2)
{
}
#Override
public void onPageScrollStateChanged(int arg0)
{
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
return super.onCreateOptionsMenu(menu);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft)
{
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft)
{
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft)
{
}
}
SearchResultsActivity.java
public class SearchResultsActivity extends Activity
{
public String query = "";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(false);
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent)
{
setIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent)
{
if(Intent.ACTION_SEARCH.equals(intent.getAction()))
query = intent.getStringExtra(SearchManager.QUERY);
}
}
companyFragment.java
public class companyFragment extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.company, container, false);
String temp = new SearchResultsActivity().query;
TextView tv = (TextView) rootView.findViewById(R.id.textView1);
tv.setText(temp);
return rootView;
}
}

I implemented a basic search example awhile back.
Hopefully this should put you in the right direction.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Locale;
import android.content.Context;
import android.content.Intent;
import android.database.AbstractCursor;
import android.database.Cursor;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class SearchActivity extends FragmentActivity {
public static Intent createIntent(Context context) {
return new Intent(context, SearchActivity.class);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search, menu);
return super.onCreateOptionsMenu(menu) | true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
final SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSuggestionsAdapter(new SearchSuggestionsAdapter(this));
searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
#Override
public boolean onSuggestionClick(int position) {
Toast.makeText(SearchActivity.this, "Position: " + position, Toast.LENGTH_SHORT).show();
searchView.clearFocus();
return true;
}
#Override
public boolean onSuggestionSelect(int position) {
return false;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Toast.makeText(SearchActivity.this, query, Toast.LENGTH_SHORT).show();
searchView.clearFocus();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
return super.onPrepareOptionsMenu(menu) | true;
}
public static class SearchSuggestionsAdapter extends SimpleCursorAdapter {
private static final String[] mFields = {"_id", "result"};
private static final String[] mVisible = {"result"};
private static final int[] mViewIds = {android.R.id.text1};
public SearchSuggestionsAdapter(Context context) {
super(context, android.R.layout.simple_list_item_1, null, mVisible, mViewIds, 0);
}
#Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
return new SuggestionsCursor(constraint);
}
private static class SuggestionsCursor extends AbstractCursor {
private ArrayList<String> mResults;
public SuggestionsCursor(CharSequence constraint) {
final int count = 100;
mResults = new ArrayList<String>(count);
for (int i = 0; i < count; i++) {
mResults.add("Result " + (i + 1));
}
if (!TextUtils.isEmpty(constraint)) {
String constraintString = constraint.toString().toLowerCase(Locale.ROOT);
Iterator<String> iter = mResults.iterator();
while (iter.hasNext()) {
if (!iter.next().toLowerCase(Locale.ROOT).startsWith(constraintString)) {
iter.remove();
}
}
}
}
#Override
public int getCount() {
return mResults.size();
}
#Override
public String[] getColumnNames() {
return mFields;
}
#Override
public long getLong(int column) {
if (column == 0) {
return mPos;
}
throw new UnsupportedOperationException("unimplemented");
}
#Override
public String getString(int column) {
if (column == 1) {
return mResults.get(mPos);
}
throw new UnsupportedOperationException("unimplemented");
}
#Override
public short getShort(int column) {
throw new UnsupportedOperationException("unimplemented");
}
#Override
public int getInt(int column) {
throw new UnsupportedOperationException("unimplemented");
}
#Override
public float getFloat(int column) {
throw new UnsupportedOperationException("unimplemented");
}
#Override
public double getDouble(int column) {
throw new UnsupportedOperationException("unimplemented");
}
#Override
public boolean isNull(int column) {
return false;
}
}
}
}
https://gist.github.com/slightfoot/5514856

Related

SearchView in ActionBar with more fragment on android

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 { }
}

Click On An Item In RecyclerView Contained In A Fragment To Open New Activity With Passed Data

I have a MainActivity and Three Fragments with recyclerViews inside the three fragments, the recyclerview contain two textviews, i want the user to click on the recyclerview and the text in should be passed on to the new activity, i am a little bit new so i would appreciate it if you can give me detailed code and some explanation.
I want to click on an item in the recyclerview and that should open a new activity, data(text) should be passed from the recyclerview to the new activity.
Here is my code for the HymnModel.java
public class HymnModel {
String title;
String song;
HymnModel(String title, String song){
this.title=title;
this.song=song;
}
public String getTitle() {return title;
}
public String getSong() {
return song;
}
}
Here is the code for ItemVeiwHolder.java
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.tutorialsbuzz.recyclerview.R;
public class ItemViewHolder extends RecyclerView.ViewHolder {
public TextView title_textview;
public TextView song_textview;
public ItemViewHolder(View itemView) {
super(itemView);
itemView.setClickable(true);
title_textview = (TextView) itemView.findViewById(R.id.song_title);
song_textview = (TextView) itemView.findViewById(R.id.song);
}
public void bind(HymnModel hymnModel) {
title_textview.setText(hymnModel.getTitle());
song_textview.setText(hymnModel.getSong());
}
}
Here is my Adapter class
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.tutorialsbuzz.recyclerview.R;
import java.util.ArrayList;
import java.util.List;
public class RVAdapter extends RecyclerView.Adapter<ItemViewHolder> {
private List<HymnModel> mCountryModel;
private List<HymnModel> mOriginalCountryModel;
public RVAdapter(List<HymnModel> mCountryModel) {
this.mCountryModel = mCountryModel;
this.mOriginalCountryModel = mCountryModel;
}
#Override
public void onBindViewHolder(ItemViewHolder itemViewHolder, int i) {
final HymnModel model = mCountryModel.get(i);
itemViewHolder.bind(model);
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, viewGroup, false);
return new ItemViewHolder(view);
}
#Override
public int getItemCount() {
return mCountryModel.size();
}
public void setFilter(List<HymnModel> countryModels){
mCountryModel = new ArrayList<>();
mCountryModel.addAll(countryModels);
notifyDataSetChanged();
}
}
Here is the code for one my fragments
public class TabOneFragment extends Fragment implements SearchView.OnQueryTextListener {
private RecyclerView recyclerview;
private List<HymnModel> mHymnModel;
private RVAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_one_fragment, container, false);
recyclerview = (RecyclerView) view.findViewById(R.id.recyclerview);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerview.setLayoutManager(layoutManager);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
int numOfSongs = 32;
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
String [] titles = {HymnTitles.hymnTitle1, HymnTitles.hymnTitle2, HymnTitles.hymnTitle3, HymnTitles.hymnTitle4, HymnTitles.hymnTitle5,
HymnTitles.hymnTitle6, HymnTitles.hymnTitle7, HymnTitles.hymnTitle8, HymnTitles.hymnTitle9, HymnTitles.hymnTitle10, HymnTitles.hymnTitle11,
HymnTitles.hymnTitle12};
String [] songs = {Hymns.hymn1.substring(width/5), Hymns.hymn2, Hymns.hymn3, Hymns.hymn4, Hymns.hymn5, Hymns.hymn6, Hymns.hymn7, Hymns.hymn8, Hymns.hymn9, Hymns.hymn10, Hymns.hymn11, Hymns.hymn12};
mHymnModel = new ArrayList<>();
for (int i = 0; i < titles.length; i++) {
mHymnModel.add(new HymnModel(i + "." + " " + titles[i], " " + songs[i]));
}
adapter = new RVAdapter(mHymnModel);
recyclerview.setAdapter(adapter);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
MenuItemCompat.setOnActionExpandListener(item,
new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
adapter.setFilter(mHymnModel);
return true; // Return true to collapse action view
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
return true; // Return true to expand action view
}
});
}
#Override
public boolean onQueryTextChange(String newText) {
final List<HymnModel> filteredModelList = filter(mHymnModel, newText);
adapter.setFilter(filteredModelList);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
private List<HymnModel> filter(List<HymnModel> models, String query) {
query = query.toLowerCase();
final List<HymnModel> filteredModelList = new ArrayList<>();
for (HymnModel model : models) {
final String text = model.getSong().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
}
My MainActivity
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_action_person,
R.drawable.ic_action_group,
R.drawable.ic_action_call
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new TabOneFragment(), "Tab 1");
adapter.addFragment(new TabTwoFragment(), "Tab 2");
adapter.addFragment(new TabThreeFragment(), "Tab 3");
viewPager.setAdapter(adapter);
}
}
And lastly my ViewPageAdapter
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
}
Thank You.
Create an interface
public interface OnHymnClickListener {
void onHymnClick(HymnModel hymnModel);
}
Pass the listener to the adapter
public class RVAdapter extends RecyclerView.Adapter<ItemViewHolder> {
private OnHymnClickListener listener;
public void setListener(OnHymnClickListener listener) {
this.listener = listener;
}
#Override
public void onBindViewHolder(ItemViewHolder itemViewHolder, int i) {
final HymnModel model = mCountryModel.get(i);
itemViewHolder.bind(model);
itemViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(listener != null) {
listener.onHymnClick(model);
}
}
});
}
}
Let your fragment implement it
public class TabOneFragment extends Fragment implements SearchView.OnQueryTextListener, OnHymnClickListener {
#Override
public void onHymnClick(HymnModel hymnModel) {
//put data to bundle and startActivity
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
adapter = new RVAdapter(mHymnModel);
adapter.setListener(this);
recyclerview.setAdapter(adapter);
}
}
Hello first of all you always want to start your activity from activity or fragment.
Never start it from adapter.
So in your adapter constructor add this
public AdapterName(......,Context context){
...your code.
this.mContext=context;
}
pass context there.
and than inside this method
public ItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mContext instanceof YourActivityName){
((YourActivityName)mContext).yourDesiredMethod();
}
}
});

Android - Pass the parameters between fragments

I developed an android application, as you see in this picture,
I used sherlock action bar for searching, the only problem is that when the user search something in web tab if he/she wants to see the image result, he should type and search again in image tab, is there any way to pass the edittext parameter to other tabs and do searching when user changed the tabs?
MainActivity:
public class MainActivity extends SherlockFragmentActivity implements
TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private com.actionbarsherlock.app.ActionBar actionBar;
private String[] tabs = { "Sound", "Image", "Web" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
actionBar.setHomeButtonEnabled(false);
viewPager.setAdapter(mAdapter);
viewPager.setOffscreenPageLimit(3);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar.newTab().setText(tabs[0])
.setTabListener(this), false);
actionBar.addTab(actionBar.newTab().setText(tabs[1])
.setTabListener(this), false);
actionBar.addTab(actionBar.newTab().setText(tabs[2])
.setTabListener(this), true);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabSelected(com.actionbarsherlock.app.ActionBar.Tab tab,
android.support.v4.app.FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(com.actionbarsherlock.app.ActionBar.Tab tab,
android.support.v4.app.FragmentTransaction ft) {
}
#Override
public void onTabReselected(com.actionbarsherlock.app.ActionBar.Tab tab,
android.support.v4.app.FragmentTransaction ft) {
}
}
Adapter:
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new Sound();
case 1:
return new Image();
case 2:
return new Search();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
Sound Frgment:
public class Sound extends Fragment {
private String URL_ADDRESS, Servlet;
private ListView listview;
private ListViewAdapter adapter;
private List<Spanned> numberlist = new ArrayList<Spanned>();
private List<Ava2> avaList = new ArrayList<Ava2>();
private Boolean isInternetPresent = false;
private ConnectionDetector detector;
private View rootView;
private RelativeLayout loading, layout;
private int counter = 10;
private EditText editText;
private String a = "http://***";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.ava, container, false);
ImageButton voiceSearch = (ImageButton) rootView
.findViewById(R.id.imageButton2);
ImageButton buttonSearch = (ImageButton) rootView
.findViewById(R.id.imageButton1);
listview = (ListView) rootView.findViewById(R.id.listview);
loading = (RelativeLayout) rootView.findViewById(R.id.loading);
layout = (RelativeLayout) rootView.findViewById(R.id.layout);
editText = (EditText) rootView.findViewById(R.id.editText1);
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
search();
return true;
}
return false;
}
});
buttonSearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
search();
}
});
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long l) {
try {
Intent i = new Intent(getActivity(), Play.class);
startActivity(i);
} catch (Exception e) {
}
}
}
});
return rootView;
}
First,you could write a interface:
public interface OnProfileDataPass {
public String getCurrentSearchword();
public void setCurrentSearchword(String searchword);
}
Then in your fragments:
public class WebFragment extends Fragment {
private OnProfileDataPass dataPasser;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
dataPasser = (OnProfileDataPass) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnProfileDataPass");
}
searchword = dataPasser.getCurrentSearchword();
}
}
In your activity:
public class MainActivity implements OnProfileDataPass {
String currentSearchword;
#Override
public String getCurrentSearchword() {
return currentSearchword;
}
#Override
public String setCurrentSearchword(String searchword) {
this.currentSearchword = searchword;
}
}
That's my solution.When you change the tap,you could listen the proper event and set the word with getActivity.setCurrentSearchword(String newword),then you could get the newword in the fragment's dataPasser variable's method getCurrentSearchword() to get the search word. I have test it in my app. Wish that helps you a little.
you should save the value of the editText in your activity and then pass it as an argument when you call your fragment, using the same technique as the one described here: http://developer.android.com/reference/android/app/Fragment.html

SherlockFragments inflating wrong menu

I have one SherlockFragmentActivity with 3 fragments. Everything works fine but when I swipe from fragment to fragment, wrong menus are shown. Fragment1 is showing menu from fragment2, SearchView on Fragment1 is filtering data on Fragment2. Here is the code for SherlockFragmentActivity
public class MainHolder extends SherlockFragmentActivity {
private static final String[] CONTENT = new String[] { "FRAGMENT1", "FRAGMENT2", "FRAGMENT3" };
FragmentAdapter mAdapter;
ViewPager mPager;
TabPageIndicator mIndicator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_holder);
mAdapter = new FragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TabPageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
class FragmentAdapter extends FragmentPagerAdapter {
public FragmentAdapter(FragmentManager fm) {
super(fm);
}
public Fragment getItem(int position) {
switch(position)
{
case 0:
return Fragment1.newInstance(CONTENT[position % CONTENT.length]);
case 1:
return Fragment2.newInstance(CONTENT[position % CONTENT.length]);
case 2:
return Fragment3.newInstance(CONTENT[position % CONTENT.length]);
default:
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
return CONTENT[position % CONTENT.length].toUpperCase();
}
#Override
public int getCount() {
return CONTENT.length;
}
}
#Override
public void onBackPressed() {
Fragment fragment = (Fragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":"+mPager.getCurrentItem());
if (fragment != null) // could be null if not instantiated yet
{
if (fragment.getView() != null) {
// Pop the backstack on the ChildManager if there is any. If not, close this activity as normal.
if (!fragment.getChildFragmentManager().popBackStackImmediate()) {
finish();
}
}
}
}
}
And here is for the fragment
public class Fragment1 extends SherlockFragment {
private static final String KEY_CONTENT = "Fragment1:Content";
LazyAdapter fragment1adapter;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.fragment1, menu);
MenuItem searchItem = menu.findItem(R.id.menu_search);
final SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint("Pretraga ...");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
if (newText.length() != 0) {
fragment1adapter.getFilter().filter(newText);
return true;
}
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
fragment1adapter.getFilter().filter("");
return false;
}
});
}
public static Fragment1 newInstance(String content) {
Fragment1 fragment = new Fragment1();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 20; i++) {
builder.append(content).append(" ");
}
builder.deleteCharAt(builder.length() - 1);
fragment.mContent = builder.toString();
return fragment;
}
private String mContent = "???";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
mContent = savedInstanceState.getString(KEY_CONTENT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment1, container, false);
setRetainInstance(true);
setHasOptionsMenu(true);
setMenuVisibility(true);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_CONTENT, mContent);
}
}
Other fragments are the same, with their separate menus and layouts. Can anyone give me some hints why is this happening?
The solution is to remove setMenuVisibility(true); from fragments onCreateView.

Actionbar retaining menu item in Gingerbread and below

I'm having a strange problem using an ActionView in my Actionbar (specifically ActionbarSherlock). This issue is only happening in devices below SDK 3.0 (basically Gingerbread devices is all I'm testing on).
My app has a ViewPager and I am animating one of my menu items while an AsyncTask is running. If I touch the ActionView before swiping everything is ok, if I swipe to any of the views, then go back to the first view, which is the only view to have the ActionView, and touch the ActionView the icon is doubling up on itself, like so:
I had this same issue previously, before I implemented a ViewPager, and I fixed it by stopping and starting the animation in onCreateOptionsMenu and calling invalidateMenuOptions, which is why I have ActivityCompat.invalidateOptionsMenu(this); in onResume of the Activity. I was hoping, by calling that, the menu would refresh itself and fix the duplicating, but it isn't.
UPDATE Using getSherlock().dispatchInvalidateOptionsMenu(); seems to, at least, get the menu to refresh itself, but it causing the ActionView to go nuts.
ViewPager:
public class Main extends SherlockFragmentActivity
{
private static List<Integer> mIds;
private static SparseArray<Fragment> mPageReferenceMap = new SparseArray<Fragment>();
#Override
public void onCreate(final Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
mViewPager = (ViewPager)findViewById(R.id.viewpager);
mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mMyFragmentPagerAdapter);
mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
GetListingFragment().StopAnimation(); //needed to add this because the ActionView was showing on the other views when swiping
}
#Override
public void onPageScrolled(int position, float offset, int offsetPixel) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
mIds = new ArrayList<Integer>();
mIds.add(0);
mIds.add(1);
mIds.add(2);
}
#Override
public void onResume()
{
super.onResume();
ActivityCompat.invalidateOptionsMenu(this);
}
private ListingFragment GetKeywordsFragment()
{
ListingFragment lf = (ListingFragment)getSupportFragmentManager().findFragmentById(R.id.fragmentListing);
if (lf == null)
{
final MyFragmentPagerAdapter fpa = (MyFragmentPagerAdapter)mViewPager.getAdapter();
lf = (ListingFragment)fpa.getFragment(0);
}
return lf;
}
private static class MyFragmentPagerAdapter extends FragmentStatePagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
if (index == 0)
{
final ListingFragment lf = ListingFragment.newInstance();
mPageReferenceMap.put(index, lf);
return lf;
}
else
{
final DetailFragment df = DetailFragment.newInstance(mIds.get(index));
mPageReferenceMap.put(index, df);
return df;
}
}
public Fragment getFragment(int key) {
return mPageReferenceMap.get(key);
}
#Override
public int getCount() {
return 3;
}
}
}
Fragment:
public class ListFragment extends SherlockListFragment
{
private int mId;
private MenuItem refreshItem;
private AsyncTask<Void, String, Void> gi;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
public static ListingFragment newInstance(int id) {
ListingFragment lf = new ListingFragment();
Bundle bundle = new Bundle();
bundle.putInt("id", id);
lf.setArguments(bundle);
return lf;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (getArguments() != null)
mId = getArguments().getInt("id");
return inflater.inflate(R.layout.listing, container, false);
}
private class GetItems extends AsyncTask<Void, String, Void> {
#Override
protected void onPreExecute()
{
StartAnimation();
}
#Override
protected Void doInBackground(Void... unused)
{
//background process to get items
}
protected void onPostExecute(final Void unused)
{
StopAnimation();
}
}
#Override
public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
inflater.inflate(R.menu.keyword_menu, menu);
StopAnimation();
refreshItem = menu.findItem(R.id.refresh);
if (fi != null && fi.getStatus() == AsyncTask.Status.RUNNING)
StartAnimation();
super.onCreateOptionsMenu(menu, inflater);
}
private void StartAnimation() {
if (refreshItem != null && refreshItem.getActionView() == null)
{
final LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ImageView ivRefresh = (ImageView)inflater.inflate(R.layout.refresh_view, null);
final Animation rotation = AnimationUtils.loadAnimation(activity, R.anim.refresh);
ivRefresh.startAnimation(rotation);
refreshItem.setActionView(ivRefresh);
}
}
public void StopAnimation()
{
if (refreshItem != null && refreshItem.getActionView() != null)
{
refreshItem.getActionView().clearAnimation();
refreshItem.setActionView(null);
}
}
#Override
public boolean onOptionsItemSelected(final MenuItem item)
{
if (item.getItemId() == R.id.getitems) {
gi = new GetItems(getActivity(), null);
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
}
Looks like this is a known bug in ABS:
https://github.com/JakeWharton/ActionBarSherlock/issues/331

Categories

Resources