I have made different fragments inside one Activity (Home.java) on which toolbar and navigation drawer is there.
Right now I thought to put searchview inside fragment.We usually write all code related to searchview inside oncreateoption menu. I have done the same thing but oncreateoption is made inside fragment.
I'm not getting any error but searchbar is not be shown over the toolbar.
package com.example.foody;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
public class fitem extends Fragment implements SearchView.OnQueryTextListener
{
RecyclerView rv1;
fitemAdapter adapter;
ArrayList<All_Data> item;
Cursor cr;
Storage sob;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v=inflater.inflate(R.layout.fragment_fitem, container, false);
sob=new Storage(getContext());
Bundle bundle = this.getArguments();
if (bundle == null)
cr=sob.allData(); //if called from home page
else
cr=sob.categorisedData(bundle.getString("category")); // if called from category page
inData();
rv1=v.findViewById(R.id.rv1);
rv1.setHasFixedSize(true);
rv1.setLayoutManager(new LinearLayoutManager(getContext()));
adapter=new fitemAdapter(getContext(),item);
rv1.setAdapter(adapter);
return v;
}
void inData()
{
item=new ArrayList<>();
while(cr.moveToNext())
{
item.add(new All_Data(cr.getString(0),cr.getString(2),cr.getString(3)));
}
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.tool_menu, menu);
MenuItem searchItem = menu.findItem(R.id.search1);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(fitem.this);
searchView.setQueryHint("Search");
}
#Override
public boolean onQueryTextChange(String s)
{
String userInput=s.toLowerCase();
ArrayList<All_Data> filterlist=new ArrayList<>();
for(int i=0;i<item.size();i++)
{
String st=item.get(i).getName().toLowerCase();
if(st.contains(userInput))
filterlist.add(item.get(i));
}
adapter=new fitemAdapter(getContext(),filterlist);
rv1.setAdapter(adapter);
return true;
}
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
}
Inside your fragment's onCreate()/onCreateView() call setHasOptionsMenu(true);
This will allow your fragment to show the menu items you inflate inside the fragment's onCreateOptionsMenu(); otherwise it uses the host Activity's menu.
Related
So I have had asked this multiple times but I can't get a decent answer to my question.
Can someone please tell me why my menu is not showing in my custom toolbar?
PurchaseItemList.java
package com.example.devcash.Fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.SearchView;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.devcash.R;
/**
* A simple {#link Fragment} subclass.
*/
public class PurchaseItemListFragment extends Fragment implements SearchView.OnQueryTextListener, MenuItem.OnActionExpandListener {
Toolbar itemListToolbar;
Spinner itemListSpinner;
public PurchaseItemListFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//inflate the menu
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_purchase_item_list, container, false);
itemListToolbar = (Toolbar) view.findViewById(R.id.toolbar_purchaseitemlist);
itemListSpinner = (Spinner) view.findViewById(R.id.spinner_allcategories);
///
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(getActivity(),
R.layout.custom_spinner_item,
getResources().getStringArray(R.array.dropdownitempurchase));
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
itemListSpinner.setAdapter(myAdapter);
itemListSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(),
itemListSpinner.getSelectedItem().toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return view;
}
//handles the search menu
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.searchmenu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(this);
searchView.setQueryHint("Search..");
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
return true;
}
}
and this is a snippet of my custom toolbar in my fragment_purchase_item_list.xml
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_purchaseitemlist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
style="#style/PrimaryHeaderBar"
android:elevation="4dp">
<Spinner
android:id="#+id/spinner_allcategories"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
</android.support.v7.widget.Toolbar>
I have tried checking all the related posts from the internet and can't find a decent tutorial on YT. Can someone tell me what is going on here?
Add following line in onCreateView() method
setHasOptionsMenu(true)
Also add below line in onViewCreated() method
(activity as AppCompatActivity?)!!.setSupportActionBar(customToolbar as Toolbar?)
Where customToolBar is the id of the toolbar added in xml file
Add this in your onCreateView method
setHasOptionsMenu(true);
I Implemented the Navigation Drawer in my Fragment but it always shows a grey padding above it .Same was the case with Fragment but i removed it by adding android:fitsSystemWindows="false". But this fails to remove the padding above the Navigation Drawer . How can i avoid this ?
This is my Fragment :
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.dummy.R;
public class QueriesActivity extends Fragment {
Context context;
DrawerLayout mDrawerLayout;
boolean mSlideState=false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_queries, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
context = getActivity();
mDrawerLayout = (DrawerLayout)view.findViewById(R.id.queries_drawer_layout);
setHasOptionsMenu(true);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View view, float v) {
}
#Override
public void onDrawerOpened(View view) {
mSlideState=true;
}
#Override
public void onDrawerClosed(View view) {
mSlideState=false;
}
#Override
public void onDrawerStateChanged(int i) {
}
});
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
menuInflater.inflate(R.menu.menu_filter, menu);
super.onCreateOptionsMenu(menu, menuInflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search:
if(mSlideState){
mDrawerLayout.closeDrawer(Gravity.END);
}else{
mDrawerLayout.openDrawer(Gravity.END);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
I want to implement this as attached in the image.
https://i.stack.imgur.com/BtHKx.png
I have been following the Android Development course on Udacity, and got to a lesson where we were to implement a ShareActionProvider. After attempting it myself, and then following what they did--I'm certain it's not working properly.
I'm putting the code in a Fragment; the correct item is present in the overflow menu, but when I click "Share", nothing happens. I noticed when I open the DetailsActivity, that the following appears in the logs:
17493-17493/com.dummy.sunshine.app W/MenuItemCompat﹕ setActionProvider: item does not implement SupportMenuItem; ignoring
I'm not sure what that means, but I couldn't find anything about it online. I would assume that clicking it is supposed to do something--however, they never go over what's supposed to happen after that lesson--so I'm a tad confused.
DetailActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
public class DetailActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
}
#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_detail, 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();
switch (id) {
case R.id.action_settings:
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
DetailFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A placeholder fragment containing a simple view.
*/
public class DetailFragment extends Fragment {
private static String mForecastStr;
private final String TAG = DetailActivity.class.getSimpleName();
public DetailFragment() {
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
Intent intent = getActivity().getIntent(); //allows us to get data from the screen that sent us to this activity
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
mForecastStr = intent.getStringExtra(Intent.EXTRA_TEXT); //we get the EXTRA_TEXT that the ForecastFragment sent us
((TextView) rootView.findViewById(R.id.detail_text))
.setText(mForecastStr);
}
return rootView;
}
private Intent shareDetailForecast() {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, mForecastStr + "#SunshineApp");
return sendIntent;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.menu_detail_fragment, menu);
MenuItem menuItem = menu.findItem(R.id.action_share);
ShareActionProvider mShareActionProvider = new ShareActionProvider(getActivity());
mShareActionProvider.setShareIntent(shareDetailForecast());
MenuItemCompat.setActionProvider(menuItem, mShareActionProvider);
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareDetailForecast());
} else {
Log.d(TAG, "mShareActionProvider is null...");
}
}
}
menu_detail_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/action_share"
android:title="#string/action_share"
android:orderInCategory="5"
app:showAsAction="ifRoom"
app:actionProviderClass="android.support.v7.widget.ShareActionProvider" />
</menu>
menu_detail.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.nxt3.sunshine.app.DetailActivity">
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:orderInCategory="100"
app:showAsAction="never" />
</menu>
This is what the app looks like on the DetailActivity page:
I believe your problem is that on your DetailActivity you are extending a FragmentActivity while you should be extending an AppCompatActivity (which is a subclass of the FragmentActivity), as you are using an action bar on your activity and using the support library.
so you should replace this:
public class DetailActivity extends FragmentActivity {
by this:
public class DetailActivity extends AppCompatActivity {
and import the support library:
import android.support.v7.app.AppCompatActivity;
I don't know if you already have it set, but you also need to set your AppTheme to be Theme.AppCompat or something similar on your AndroidManifest.xml. Something like below:
</manifest>
<application
...
android:theme=""Theme.AppCompat.Light" >
...
</application>
</manifest>
I'm doing the same exercise in the Udacity and that worked for me, I hope it helps.
I assume you want the share view appears beside the toolbar menu!
If yes, here is the right solution for your issue :
DetailActivity.java
package com.example.android.sunshine.app;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DetailActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new DetailFragment())
.commit();
}
}
#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_detail, 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) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
DetailFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public static class DetailFragment extends Fragment {
private static final String LOG_TAG = DetailFragment.class.getSimpleName();
private static final String FORECAST_SHARE_HASHTAG = " #SunshineApp";
private String mForecastStr;
public DetailFragment() {
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
// The detail Activity called via intent. Inspect the intent for forecast data.
Intent intent = getActivity().getIntent();
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
mForecastStr = intent.getStringExtra(Intent.EXTRA_TEXT);
((TextView) rootView.findViewById(R.id.detail_text))
.setText(mForecastStr);
}
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.menu_detail_fragment, menu);
// Retrieve the share menu item
MenuItem menuItem = menu.findItem(R.id.action_share);
// Get the provider and hold onto it to set/change the share intent.
ShareActionProvider mShareActionProvider =
(ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
// Attach an intent to this ShareActionProvider. You can update this at any time,
// like when the user selects a new piece of data they might like to share.
if (mShareActionProvider != null ) {
mShareActionProvider.setShareIntent(createShareForecastIntent());
} else {
Log.d(LOG_TAG, "Share Action Provider is null?");
}
}
private Intent createShareForecastIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,
mForecastStr + FORECAST_SHARE_HASHTAG);
return shareIntent;
}
}
menu_detail_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/action_share"
android:title="#string/action_share"
app:showAsAction="always"
app:actionProviderClass="android.support.v7.widget.ShareActionProvider" />
</menu>
menu_detail.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.android.sunshine.app.DetailActivity" >
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:orderInCategory="100"
app:showAsAction="never" />
</menu>
I am trying to use the new RecyclerView widget inside a Fragment but I am getting this error:
Unable to start activity
ComponentInfo{com.example.myapplication/com.example.myapplication.MyActivity}:
java.lang.NullPointerException: Attempt to invoke interface method
'boolean java.util.List.add(java.lang.Object)' on a null object
reference
What am I doing wrong?
This is my Fragment:
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
public class RecyclerviewFragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerviewAdapter mRecyclerviewAdapter;
private LinearLayoutManager mLinearLayoutManager;
private List<ViewModel> viewModel;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_recyclerview, container, false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mRecyclerviewAdapter = new RecyclerviewAdapter(viewModel);
mLinearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setAdapter(mRecyclerviewAdapter);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
}
}
And my Activity:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.util.List;
public class MyActivity extends Activity {
private List<ViewModel> viewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
RecyclerviewFragment recyclerviewFragment = new RecyclerviewFragment();
getFragmentManager().beginTransaction().add(android.R.id.content, recyclerviewFragment).commit();
viewModel.add(new ViewModel("View"));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, 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);
}
}
Thanks!
You didn't initialize private List<ViewModel> viewModel
I am new to android development.I am trying to create an activity method on clicking a button.
Below is my MainActivity.java file code.
I am getting errors
1."cannot resolve method'setVisibility (int)'" and
2."cannot resolve symbol 'TextView'"
please guide.
MainActivity.java
package com.AndroidLove;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
public void onLoveButtonClicked(View view) {
TextView textView =(TextView) findViewById(R.id.textView);
textView.setVisibility(View.VISIBLE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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.
switch (item.getItemId()) {
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
Import this package as well
import android.widget.TextView;