I changed my App from all Activities to a NavigationDrawer Setup with Fragments. One of my Activities has a menu on top, this is not shown anymore with this new setup. Here is my Code:
Java
public class BurgerMenu extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_burger_menu);
Toolbar toolbar = setToolBar();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// Check that the activity is using the layout version with
// the fragment_container FrameLayout
if (findViewById(R.id.fragment_container) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}
// Create a new Fragment to be placed in the activity layout
LoginFragment firstFragment = new LoginFragment();
// In case this activity was started with special instructions from an
// Intent, pass the Intent's extras to the fragment as arguments
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}
private Toolbar setToolBar() {
Toolbar tb = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(tb);
ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
return tb;
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.burger_menu, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<include layout="#layout/toolbar"/>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_burger_menu"
app:menu="#menu/activity_burger_menu_drawer" />
And here is the Fragment with the Menu:
public class MainActivity extends Fragment {
public List<MoodEntry> moodList;
private MoodEntryDataSource dataSource;
public Date month_year_date;
private int status = 0;
private View v;
private FragmentActivity fragmentActivity;
private Context context;
private LineChart chart;
private TextView textTop;
private TextView textMid;
private TextView textBot;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragmentActivity = super.getActivity();
v = inflater.inflate(R.layout.activity_main, container, false);
context = fragmentActivity.getApplicationContext();
dataSource = new MoodEntryDataSource(context);
month_year_date = new Date();
final RadioGroup radioGroup = (RadioGroup) v.findViewById(R.id.radioButtonGroupStatus);
final RadioButton private_radio = (RadioButton) v.findViewById(R.id.radioButtonPrivatStart);
final RadioButton business_radio = (RadioButton) v.findViewById(R.id.radioButtonBusinessStart);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (private_radio.isChecked()) {
status = MoodEntry.PRIVATE;
} else if (business_radio.isChecked()) {
status = MoodEntry.BUSINESS;
}
loadListEntries();
}
});
// Graph
textTop = (TextView) v.findViewById(R.id.textView7);
textMid = (TextView) v.findViewById(R.id.textView9);
textBot = (TextView) v.findViewById(R.id.textView8);
setYLabelVisibility(false);
chart = (LineChart) v.findViewById(R.id.chart);
chart.setTouchEnabled(false);
chart.setDescription("Datum");
chart.setNoDataText(this.getString(R.string.no_data_to_show));
XAxis xAxis = chart.getXAxis();
//xAxis.setLabelsToSkip(5);
xAxis.setDrawAxisLine(true);
xAxis.setDrawGridLines(false);
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setAvoidFirstLastClipping(true);
YAxis left = chart.getAxisLeft();
left.setAxisMinValue(-5);
left.setAxisMaxValue(5);
left.setDrawZeroLine(true);
left.setLabelCount(0, false);
left.setDrawLabels(false);
//left.setShowOnlyMinMax(true);
chart.getAxisRight().setEnabled(false);
return v;
};
#Override
public void onResume() {
super.onResume();
dataSource.open();
loadListEntries();
}
#Override
public void onPause() {
super.onPause();
dataSource.close();
}
/**
* Shows the entries for month in month_year_date in diagram and list
*/
private void loadListEntries() {
TextView textView = (TextView) v.findViewById(R.id.textView_MonthYear);
textView.setText(new SimpleDateFormat("MMMM yyyy", Locale.GERMAN).format(month_year_date));
List<MoodEntry> moodListForGraph = dataSource.getMoodEntriesByMonthAndByStatus(month_year_date, MoodEntry.SORT_BY_DATE,status);
updateData(moodListForGraph);
moodList = dataSource.getMoodEntriesByMonthAndByStatus(month_year_date, MoodEntry.SORT_BY_MOOD,status);
MoodEntryListAdapter adapter = new MoodEntryListAdapter(fragmentActivity, moodList);
ListView moodListView = (ListView) v.findViewById(R.id.listview_moods);
moodListView.setAdapter(adapter);
moodListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
showDetailView(position);
}
});
}
/**
* Shows the entries of the month selected by date
* #param date date within month that should be shown
*/
public void setMonthYear(Date date) {
month_year_date = date;
loadListEntries();
}
/**
* Opens the Detail View of list item on pos
* #param pos pos of selected item
*/
public void showDetailView(int pos) {
Bundle bundle = new Bundle();
bundle.putLong("entry_id", moodList.get(pos).getId());
Fragment moodDetail = new MoodDetailActivity();
moodDetail.setArguments(bundle);
FragmentTransaction transaction = fragmentActivity.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, moodDetail);
transaction.addToBackStack(null);
transaction.commit();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add_entry:
Fragment addEntry = new AddEntryActivity();
FragmentTransaction transaction = fragmentActivity.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, addEntry);
transaction.addToBackStack(null);
transaction.commit();
return true;
case R.id.action_date_picker:
Calendar cal = Calendar.getInstance();
cal.setTime(month_year_date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = 1;
// TODO 0 durch Theme ersetzen. 0 war: AlertDialog.THEME_HOLO_LIGHT
DatePickerDialog dpd = new DatePickerDialog(getActivity(), 0,datePickerListener,year, month, day){
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
int day = getContext().getResources().getIdentifier("android:id/day", null, null);
if(day != 0){
View dayPicker = findViewById(day);
if(dayPicker != null){
dayPicker.setVisibility(View.GONE);
}
}
}
};
dpd.show();
//DatePickerFragment datePickerFragment = new DatePickerFragment();
//datePickerFragment.show(fragmentActivity.getFragmentManager(), "Date Picker");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int month, int day) {
Calendar cal = Calendar.getInstance();
cal.set(year, month, 1);
setMonthYear(cal.getTime());
}
};
// Graph
public void updateData(List<MoodEntry> moodEntries) {
chart.clear();
ArrayList<Entry> entryList = new ArrayList<Entry>();
ArrayList<String> xVals = new ArrayList<String>();
for (int i = 0; i < moodEntries.size(); i++) {
MoodEntry moodEntry = moodEntries.get(i);
int mood_value = moodEntry.getMood();
xVals.add(moodEntry.getDisplayDateOnly());
entryList.add(new BarEntry(mood_value, i));
}
LineDataSet dataSet = new LineDataSet(entryList, "Einträge");
dataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
dataSet.setLineWidth(2f);
dataSet.setColor(getColor(R.color.graph_line));
dataSet.setCircleColor(getColor(R.color.graph_line));
ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
dataSets.add(dataSet);
LineData data = new LineData(xVals, dataSets);
data.setDrawValues(false);
if (moodEntries.size()!=0) {
chart.setData(data);
Legend legend = chart.getLegend();
legend.setEnabled(false);
setYLabelVisibility(true);
chart.notifyDataSetChanged();
chart.invalidate();
} else {
setYLabelVisibility(false);
}
}
private int getColor(int colorRes) {
return ContextCompat.getColor(getContext(), colorRes);
}
private void setYLabelVisibility(boolean visible) {
if (visible) {
textTop.setVisibility(View.VISIBLE);
textMid.setVisibility(View.VISIBLE);
textBot.setVisibility(View.VISIBLE);
} else {
textTop.setVisibility(View.INVISIBLE);
textMid.setVisibility(View.INVISIBLE);
textBot.setVisibility(View.INVISIBLE);
}
}
}
The Toolbar from the Navigationdrawer isnt shown with this fragment, neither is the fragments Menu.
Any Solution?
Found the Answer myself, had to change sth. in the XML:
<?xml version="1.0" encoding="utf-8"?>
<StackLayout>
<include layout="#layout/toolbar"/>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</StackLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_burger_menu"
app:menu="#menu/activity_burger_menu_drawer" />
Related
I want to implement SearchView on the toolbar in Navigation-Drawer and there is Fragment Activity like in the picture. I've tried SearchView on regular Activity and I succeeded, but when I implement it to Fragment Activity, why its code can not run.
This is my Main Activity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public static final String MAKAN = "makanan";
public static String WHERE = "makanan";
public static int WHERE2;
String mQuery;
ArrayList<Makanan> mlist = new ArrayList<>();
ArrayList<Makanan> mlistAll = new ArrayList<>();
public String mQuery2;
boolean isFiltered;
MakananAdapter mAdapter;
ArrayList<Integer> mListMapFilter = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = ((NavigationView)findViewById(R.id.nav_view)).getHeaderView(0);
ImageButton ib = (ImageButton)header.findViewById(R.id.imageButton);
ib.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MapsActivity.class);
startActivity(intent);
}
});
setTitle("Beranda");
Hal1 fragment = new Hal1();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, fragment, "fragment1");
//WHERE = "11";
fragmentTransaction.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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) {
setTitle("About");
Hal2 fragments = new Hal2();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, fragments, "fragment1");
fragmentTransaction.commit();
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.frag_all) {
setTitle("Rekomendasi");
SecondFragment fragment = new SecondFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, fragment, "fragment1");
WHERE = "11";
fragmentTransaction.commit();
} ...
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}}
And My SecondFragment.java
public class SecondFragment extends Fragment implements MakananAdapter.IMakananAdapter, SearchView.OnQueryTextListener {
public static final String MAKAN = "makanan";
private AppCompatActivity compat;
private RecyclerView recyclerView;
private MakananAdapter adapter;
public SecondFragment() {
// Required empty public constructor
}
ArrayList<Makanan> mList = new ArrayList<>();
//MakananAdapter mAdapter;
String mQuery;
ArrayList<Makanan> mlist = new ArrayList<>();
ArrayList<Makanan> mlistAll = new ArrayList<>();
boolean isFiltered;
MakananAdapter mAdapter;
ArrayList<Integer> mListMapFilter = new ArrayList<>();
private SearchView searchView = null;
private SearchView.OnQueryTextListener queryTextListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.activity_calling, container, false);
recyclerView = (RecyclerView) rootview.findViewById(R.id.recyclerView);
GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);
recyclerView .setHasFixedSize(true);
recyclerView .setItemAnimator(new DefaultItemAnimator());
recyclerView .setLayoutManager(gridLayoutManager);
recyclerView.setLayoutManager(gridLayoutManager);
adapter = new MakananAdapter(mList);
recyclerView.setAdapter(adapter);
return rootview;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
fillData1();
//if i use this call method, the function is work
//[enter image description here][1]doFilter("roker");
}
private void fillData1() {
Resources resources = getResources();
String[] arJudul = resources.getStringArray(R.array.recommend);
String[] arDeskripsi = resources.getStringArray(R.array.recommend_desc);
String[] arHarga = resources.getStringArray(R.array.recommend_price);
String[] arDetail = resources.getStringArray(R.array.recommend_details);
String[] arLokasi = resources.getStringArray(R.array.recommend_locations);
String[] arLat = resources.getStringArray(R.array.recommend_lat);
String[] arLng = resources.getStringArray(R.array.recommend_longi);
TypedArray a = resources.obtainTypedArray(R.array.recommend_pict);
String[] arFoto = new String[a.length()];
for (int i = 0; i < arFoto.length; i++) {
int id = a.getResourceId(i, 0);
arFoto[i] = ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
+ resources.getResourcePackageName(id) + '/'
+ resources.getResourceTypeName(id) + '/'
+ resources.getResourceEntryName(id) + '/';
}
a.recycle();
for (int i = 0; i < arJudul.length; i++) {
mList.add(new Makanan(arJudul[i], arDeskripsi[i], arFoto[i], arHarga[i], arDetail[i], arLokasi[i], arLat[i], arLng[i]));
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setQueryHint("Cari");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
//Log.i("onQueryTextSubmit", query);
//mQuery = query.toLowerCase();
//doFilter(mQuery);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
Log.i("onQueryTextChange", newText);
mQuery = newText.toLowerCase();
doFilter(mQuery);
return true;
}
});
return;
}
//My filter function goes here
public boolean doFilter(String query) {
if (!isFiltered) {
mlistAll.clear();
mlistAll.addAll(mList);
isFiltered = true;
}
mList.clear();
if (query.isEmpty()) {
mList.addAll(mlistAll);
isFiltered = false;
return false;
} else {
mListMapFilter.clear();
for (int i = 0; i < mlistAll.size(); i++) {
Makanan makanan = mlistAll.get(i);
if (makanan.judul.toLowerCase().contains(query) ||
makanan.deskripsi.toLowerCase().contains(query)) {
mList.add(makanan);
mListMapFilter.add(i);
}
}
return true;
}
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return true;
}
#Override
public void doClick(int pos) {
Intent intent = new Intent(getContext(), DetailActivity.class);
intent.putExtra(MAKAN, mList.get(pos));
startActivity(intent);
}}
So, my question is how to run the doFilter function with query by user input ? Is that possible ? thanks in advance
Image link
[1]: https://ibb.co/fFO3gQ - doFilter not work
[2]: https://ibb.co/dYXw1Q - static doFilter work
Assuming that you have added searchable.xml into res/xml/ project directory and in your AndroidManifest.xml, you have declared the MainActivity as searchable activity.
1. Add menu.xml into res/menu folder containing menu item that uses SearchView using app:actionViewClass="android.support.v7.widget.SearchView"
<item
android:id="#+id/action_search"
android:icon="#drawable/ic_action_search"
android:title="#string/search_hint"
app:showAsAction="collapseActionView|ifRoom"
app:actionViewClass="android.support.v7.widget.SearchView" />
2. Setup SearchView and add SearchView.setOnQueryTextListener to your MainActivity.
3. Ony add a static Filter function into your Fragment class. For example:
public static void doFilter(String searchQuery) {
...........
....................
}
Update your MainActivity as below:
public class MainActivity extends AppCompatActivity {
Context mContext;
// Default active navigation menu
int mActiveMenu;
// TAGS
public static final int MENU_FIRST = 0;
public static final int MENU_SECOND = 1;
// Action bar search widget
SearchView searchView;
String searchQuery = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
................
...........................
// FirstFragment will show when app launch
mActiveMenu = MENU_FIRST;
displayViewWithFragment(mActiveMenu);
// NavigationView
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId())
{
case R.id.navigation_item_first:
{
// First
displayViewWithFragment(MENU_FIRST);
return true;
}
case R.id.navigation_item_second:
{
// Second
displayViewWithFragment(MENU_SECOND);
return true;
}
default:
return true;
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
// Getting search action from action bar and setting up search view
MenuItem searchItem = menu.findItem(R.id.action_search);
searchView = (SearchView)searchItem.getActionView();
// Setup searchView
setupSearchView(searchItem);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar actions click
switch (item.getItemId())
{
case R.id.action_search:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// Search widget
private void setupSearchView(MenuItem searchItem)
{
SearchManager searchManager = (SearchManager) this.getSystemService(Context.SEARCH_SERVICE);
if (searchManager != null)
{
SearchableInfo info = searchManager.getSearchableInfo(getComponentName());
searchView.setSearchableInfo(info);
}
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText)
{
searchQuery = newText;
// Load search data on respective fragment
if(mActiveMenu == MENU_FIRST) // First
{
FirstFragment.doFilter(newText);
}
else if(mActiveMenu == MENU_SECOND) // Second
{
SecondFragment.doFilter(newText);
}
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
//searchView.clearFocus();
return false;
}
});
// Handling focus change of search view
searchView.setOnQueryTextFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// Focus changed after pressing back key or pressing done in keyboard
if (!hasFocus) {
searchQuery = "";
}
}
});
}
/**
* Displaying fragment view for selected nav drawer list item
* */
private void displayViewWithFragment(final int position) {
// Active menu
mActiveMenu = position;
Fragment fragment = null;
switch (position)
{
case MENU_FIRST:
{
// First
fragment = new FirstFragment();
}
break;
case MENU_SECOND:
{
// Second
fragment = new SecondFragment();
}
break;
default:
break;
}
if (fragment != null)
{
mFragmentTransition = getSupportFragmentManager().beginTransaction();
mFragmentTransition.replace(R.id.frame_container, fragment);
mFragmentTransition.commit();
}
}
}
Add filter function to FirstFragment:
public static void doFilter(String searchQuery)
{
// Filter codes here
...................
.............................
// Update RecyclerView
adapter.notifyDataSetChanged();
}
Hope this will help~
There is some information that I want to display in the NavigationDrawer. This information is entered by the user in a previous activity. I use an intent to send the information to the Main Activity for the Drawer.
MainActivity (After user entered details)
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
String info = intent.getStringExtra("info");
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#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;
}
if(id == R.id.action_search){
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.nav_item_dashboard);
break;
......
}
I have a specific layout for the navigation drawer and it contains a textview which I want to update with the String test. This is the fragment code and the xml for it.
FragmentDrawer Class
public FragmentDrawer() {
}
public void setDrawerListener(FragmentDrawerListener listener) {
this.drawerListener = listener;
}
public static List<NavDrawerItem> getData() {
List<NavDrawerItem> data = new ArrayList<>();
// preparing navigation drawer items
for (int i = 0; i < titles.length; i++) {
NavDrawerItem navItem = new NavDrawerItem();
navItem.setTitle(titles[i]);
navItem.setIcon(icons.getResourceId(i,-1));
data.add(navItem);
}
return data;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// drawer labels
titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
icons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
TextView userID = (TextView) layout.findViewById(R.id.nav_title_user);
adapter = new NavigationDrawerAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
drawerListener.onDrawerItemSelected(view, position);
mDrawerLayout.closeDrawer(containerView);
}
#Override
public void onLongClick(View view, int position) {
}
}));
return layout;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
toolbar.setAlpha(1 - slideOffset / 2);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
FramgentDrawer.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white">
<RelativeLayout
android:id="#+id/nav_header_container"
android:layout_width="match_parent"
android:layout_height="140dp"
android:layout_alignParentTop="true"
android:background="#color/colorPrimary">
......
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceInverse"
android:text="#string/welcome_user"
android:id="#+id/nav_title_user"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"/>
</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/drawerList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_below="#id/nav_header_container" />
I have managed to update the list in the drawer with Icons, Labels and a Header. I have done so by using a RecyclerViewAdapter.
The problem that I am having is that these details were from the resources (strings.xml).
How can I update a textview on a NavigationFragment when it has been created? How can I send a value to the fragment so that it will be used during OnCreateView of the fragment?
I was looking too much into it. The solution was quite simple...Even though it took me 3 hrs to figure this out :/
In the NavigationFragment, I created a method to update a textview with a string. In the MainActivity where I get the information from the intent, I just called the method like this:
drawerFragment.setUserTextView(info);
This is why taking breaks are important... ^^
I'm building a base activity for navigation and want something flexible so the Activity dictates to the Base Activity which layout to inflate.
I have the following
public abstract class BaseActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private int mLayoutRes;
protected void setLayout(int layoutRes) {
mLayoutRes = layoutRes;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(mLayoutRes);
// Layout implements toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null){
setSupportActionBar(toolbar);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// The layout implements the nav
if (drawer != null){
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
}
// Other Nav code ommitted as its too verbose
}
Then the Layout is passed from the activity as folows
public class Home extends BaseActivity {
private final String TAG = "Home";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.setLayout(R.layout.activity_home);
super.onCreate(savedInstanceState);
// Other Activity code
}
}
Is there a better way to achieve this?
Maybe setting a base layout with a content frame and inflating into that?
Any suggestions would be appreciated.
You can follow BaseActivity from Google IO application. Just override setContentView and you dont need setLayout
Here is my BaseActivity
package com.vtcmobile.kqviet.activity;
public class BaseActivity extends AppCompatActivity {
private Toolbar toolbar;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private NavigationView navigationView;
protected Context mContext;
public NavigationView getNavigationView() {
return navigationView;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = BaseActivity.this;
}
#Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
initToolbar();
}
private void initToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
private void setUpNav() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle(BaseActivity.this, drawerLayout, R.string.app_name, R.string.app_name);
drawerLayout.setDrawerListener(drawerToggle);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
navigationView = (NavigationView) findViewById(R.id.navigation);
// Setting Navigation View Item Selected Listener to handle the item
// click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Checking if the item is in checked state or not, if not make
// it in checked state
if (menuItem.isChecked())
menuItem.setChecked(false);
else
menuItem.setChecked(true);
// Closing drawer on item click
drawerLayout.closeDrawers();
// Check to see which item was being clicked and perform
// appropriate action
Intent intent;
switch (menuItem.getItemId()) {
case R.id.xxxx:
return true;
}
return false;
}
});
// Setting the actionbarToggle to drawer layout
// calling sync state is necessay or else your hamburger icon wont show
// up
drawerToggle.syncState();
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setUpNav();
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#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) {
if (drawerToggle.onOptionsItemSelected(item))
return true;
// 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);
}
}
I make some changes in BaseActivity class using inflating layout of baseactivity and reuse, you can use following class for extend only into any one of your activity class.
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.FrameLayout;
public class BaseActivity extends AppCompatActivity {
public Toolbar toolbar;
public DrawerLayout drawerLayout;
public ActionBarDrawerToggle drawerToggle;
public NavigationView navigationView;
public Context mContext;
public NavigationView getNavigationView() {
return navigationView;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = BaseActivity.this;
setContentView(R.layout.base_activity);
}
#Override
public void setContentView(int layoutResID) {
DrawerLayout fullView = (DrawerLayout)getLayoutInflater().inflate(R.layout.base_activity, null);
FrameLayout activityContainer = (FrameLayout) fullView.findViewById(R.id.activity_content);
getLayoutInflater().inflate(layoutResID, activityContainer, true);
super.setContentView(fullView);
initToolbar();
}
private void initToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
private void setUpNav() {
drawerLayout = (DrawerLayout) findViewById(R.id.activity_container);
drawerToggle = new ActionBarDrawerToggle(BaseActivity.this, drawerLayout, R.string.app_name, R.string.app_name);
drawerLayout.setDrawerListener(drawerToggle);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
navigationView = (NavigationView) findViewById(R.id.navigation);
// Setting Navigation View Item Selected Listener to handle the item
// click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Checking if the item is in checked state or not, if not make
// it in checked state
if (menuItem.isChecked())
menuItem.setChecked(false);
else
menuItem.setChecked(true);
// Closing drawer on item click
drawerLayout.closeDrawers();
// Check to see which item was being clicked and perform
// appropriate action
Intent intent;
switch (menuItem.getItemId()) {
case R.id.xxxx:
return true;
}
return false;
}
});
// Setting the actionbarToggle to drawer layout
// calling sync state is necessay or else your hamburger icon wont show
// up
drawerToggle.syncState();
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setUpNav();
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#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) {
if (drawerToggle.onOptionsItemSelected(item))
return true;
// 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);
}
}
This is my base_activity.xml,
<android.support.v4.widget.DrawerLayout
android:id="#+id/activity_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
/>
<FrameLayout
android:id="#+id/activity_content"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
/>
</android.support.v4.widget.DrawerLayout>
You can refer to my following code, pay attention to addContentView in my base activity (here I name it NavigationDrawerActivity)
Base activity:
public class NavigationDrawerActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
mDrawerLayout.setDrawerListener(toggle);
toggle.syncState();
}
/**
* called in extending activities instead of setContentView...
*
* #param layoutId The content Layout Id of extending activities
*/
public void addContentView(int layoutId) {
LayoutInflater inflater = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(layoutId, null, false);
mDrawerLayout.addView(contentView, 0);
}
}
Then in other activities, for example, MainActivity:
public class MainActivity extends NavigationDrawerActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.addContentView(R.layout.activity_main);
}
}
Hope this helps!
you could either override setContentView in your BaseActivity and initialised everything after the super call or move all the DrawerLayout related stuff to a protected method and call it from each children of BaseActivity, after you call setContentView. I think the first should be straightforward an, from what you posted, you can avoid to override onCreate in the BaseActivity
Common Navigation DraweFor All Activity
## BaseActivity.java ##
public class BaseActivity extends FragmentActivity
{
final String[] navDrawMenuItems = {"My Project" , "My Project1", "MyProject2", "MyProject3" ,"MyProject4","MyProject5","MyProject6"};
final int[] navDrawMenuIcons = {R.drawable.vendor,
R.drawable.vendor,
R.drawable.vendor,
R.drawable.vendor,
R.drawable.log_icon,
R.drawable.vendor,
};
public RelativeLayout mRelativeLayout;
public FrameLayout actContent;
public ListView navList;
LinearLayout drawer_List;
TextView text_emp_name;
public MenuDrawerAdapter menuDrawerAdapter;
public ArrayList<Vendor_Wrapper> menuDrawerList = new ArrayList<>();
public DrawerArrowDrawable drawerArrowDrawable;
public ImageView drawer_indicator;
public DrawerLayout drawer_layout;
public float offset;
public boolean flipped;
SharedPreferences _SP;
SharedPreferences.Editor _EDITOR;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
for (int i = 0; i < navDrawMenuItems.length; i++)
{
menuDrawerList.add(new Vendor_Wrapper(""+i,navDrawMenuItems[i], navDrawMenuIcons[0]));
}
}
#Override
public void setContentView(int layoutResID)
{
mRelativeLayout = (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_base, null);
actContent = (FrameLayout) mRelativeLayout.findViewById(R.id.main);
// set the drawer dialog_view as main content view of Activity.
setContentView(mRelativeLayout);
// add dialog_view of BaseActivities inside framelayout.i.e. frame_container
getLayoutInflater().inflate(layoutResID, actContent, true);
drawer_layout = (DrawerLayout) findViewById(R.id.drawer_layout);
// =========================================
final Resources resources = getResources();
drawerArrowDrawable = new DrawerArrowDrawable(resources);
drawer_indicator = (ImageView) findViewById(R.id.drawer_indicator);
drawerArrowDrawable.setStrokeColor(resources.getColor(android.R.color.white));
drawer_indicator.setImageDrawable(drawerArrowDrawable);
// =========================================
text_emp_name=(TextView)findViewById(R.id.text_emp_name) ;
_SP = getSharedPreferences(Constants.pref_name, MODE_PRIVATE);
text_emp_name.setText(_SP.getString("empName",""));
drawer_List=(LinearLayout)findViewById(R.id.drawer_List);
navList = (ListView) findViewById(R.id.drawer_List1);
menuDrawerAdapter = new MenuDrawerAdapter(BaseActivity.this, menuDrawerList);
navList.setAdapter(menuDrawerAdapter);
navList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Intent intent;
// Toast.makeText(getApplicationContext(),"position "+position,30).show();
Log.i(Constants.TAG,"drawer_position: "+position);
switch (position)
{
case 0:
intent = new Intent(BaseActivity.this, List_of_projects.class);
startActivityForResult(intent,Constants.EXIT);
//
break;
case 1:
intent = new Intent(BaseActivity.this, List_of_projects.class);
startActivityForResult(intent,Constants.EXIT);
// drawer_indicator.performClick();
break;
case 2:
intent = new Intent(BaseActivity.this, List_of_projects.class);
startActivityForResult(intent,Constants.EXIT);
// drawer_indicator.performClick();
break;
case 3:
intent = new Intent(BaseActivity.this, List_of_projects.class);
startActivityForResult(intent,Constants.EXIT);
// drawer_indicator.performClick();
break;
case 4:
intent = new Intent(BaseActivity.this, List_of_projects.class);
intent.putExtra("Type","Complaints");
startActivityForResult(intent,Constants.EXIT);
// drawer_indicator.performClick();
break;
case 5:
intent = new Intent(BaseActivity.this, List_of_projects.class);
intent.putExtra("Type","Suggestions");
startActivityForResult(intent,Constants.EXIT);
break;
case 6:
intent = new Intent(BaseActivity.this, List_of_projects.class);
startActivityForResult(intent,Constants.EXIT);
break;
case 7:
System.out.println("Logout clickedddddd ");
SharedPreferences.Editor editor = getSharedPreferences("my_pref", MODE_PRIVATE).edit();
editor.clear();
editor.commit();
setResult(Constants.EXIT);
finish();
break;
default:
break;
}
}
});
initViewsandSharedPreferencesandSQLiteAdapter();
clickToViews();
}
public void setMenuDrawer(ArrayList<Vendor_Wrapper> menuDrawerList, String email)
{
navList = (ListView) findViewById(R.id.drawer_List1);
menuDrawerAdapter = new MenuDrawerAdapter(BaseActivity.this, menuDrawerList);
navList.setAdapter(menuDrawerAdapter);
}
public void initViewsandSharedPreferencesandSQLiteAdapter()
{
_SP = getSharedPreferences(Constants.TAG, MODE_PRIVATE);
_EDITOR = _SP.edit();
drawer_indicator_LL = (LinearLayout) findViewById(R.id.drawer_indicator_LL);
}
/**
* Take care of popping the fragment back stack or finishing the activity
* as appropriate.
*/
#Override
public void onBackPressed()
{
super.onBackPressed();
if (drawer_layout.isDrawerVisible(Gravity.RIGHT))
{
drawer_layout.closeDrawer(drawer_List);
}
else
{
finish();
}
}
public void clickToViews()
{
drawer_layout.setDrawerListener(new DrawerLayout.SimpleDrawerListener()
{
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
offset = slideOffset;
// Sometimes slideOffset ends up so close to but not quite 1 or 0.
if (slideOffset >= .995)
{
flipped = true;
drawerArrowDrawable.setFlip(flipped);
} else if (slideOffset <= .005)
{
flipped = false;
drawerArrowDrawable.setFlip(flipped);
}
drawerArrowDrawable.setParameter(offset);
}
});
drawer_indicator.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (drawer_layout.isDrawerVisible(Gravity.RIGHT))
{
drawer_layout.closeDrawer(drawer_List);
}
else
{
drawer_layout.openDrawer(drawer_List);
}
}
});
drawer_indicator_LL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer_layout.isDrawerVisible(Gravity.RIGHT)) {
drawer_layout.closeDrawer(drawer_List);
} else {
drawer_layout.openDrawer(drawer_List);
}
}
});
}
public void NavigationPerformClick()
{
drawer_indicator.performClick();
}
private class MenuDrawerAdapter extends BaseAdapter
{
ArrayList<Vendor_Wrapper> menuDrawerList;
Context context;
public MenuDrawerAdapter(Context context, ArrayList<Vendor_Wrapper> menuDrawerList)
{
super();
this.context = context;
this.menuDrawerList = menuDrawerList;
}
#Override
public int getCount()
{
return menuDrawerList.size();
}
#Override
public Object getItem(int position)
{
return position;
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater layoutInflater = LayoutInflater.from(BaseActivity.this);
ViewHolder viewHolder;
if (convertView == null)
{
viewHolder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.row_menu_drawer, null);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
viewHolder.imgIcon = (ImageView) convertView.findViewById(R.id.img_icon);
viewHolder.main_RL = (RelativeLayout)convertView.findViewById(R.id.main_RL);
viewHolder.imgIcon.setVisibility(View.GONE);
convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
Vendor_Wrapper menuDrawerModel = menuDrawerList.get(position);
//## Setup Data below
String Name = menuDrawerModel.getName();
String id = menuDrawerModel.getId();
viewHolder.tvTitle.setText(menuDrawerModel.getName());
// viewHolder.main_RL.setOnClickListener(new ClickToView(BaseActivity.this,position,id,Name));
viewHolder.imgIcon.setImageResource(menuDrawerModel.getDrawable_icon());
return convertView;
}
public class ViewHolder
{
TextView tvTitle;
ImageView imgIcon;
RelativeLayout main_RL;
}
}
protected class MenuDrawerModel
{
private String title;
private int icon;
public String Icon_url;
public MenuDrawerModel(String title, int icon, String icon_url) {
this.title = title;
this.icon = icon;
Icon_url = icon_url;
}
public MenuDrawerModel(String title, int icon)
{
super();
this.title = title;
this.icon = icon;
}
public MenuDrawerModel() {
super();
}
public String getTitle() {
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public int getIcon() {
return icon;
}
public void setIcon(int icon)
{
this.icon = icon;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println("Logout onActivityResult "+resultCode);
if(resultCode==Constants.EXIT)
{
setResult(Constants.EXIT);
finish();
}
}
}
## MainActivity.java ##
public class MainActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
## activity_base.xml ##
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:custom="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white">
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="#+id/header_view"
layout="#layout/layout_header_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/header_view">
</FrameLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/drawer_List"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:layout_marginTop="50dp"
android:background="#color/white"
android:choiceMode="singleChoice"
android:orientation="vertical"
android:weightSum="10">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3"
android:background="#drawable/bagroundg"
android:orientation="vertical"
android:visibility="gone"
android:weightSum="5">
</LinearLayout>
<ListView
android:id="#+id/drawer_List1"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/white"
android:choiceMode="singleChoice" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
## activity_main.xml ##
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Hello World!"
android:textSize="30dp" />
</LinearLayout>
</RelativeLayout>
public class Vendor_Wrapper
{
private String id;
public Vendor_Wrapper(String id, String name, int drawable_icon)
{
this.id = id;
Name = name;
this.drawable_icon = drawable_icon;
}
private String Name;
private String contact_no;
private String Email_id;
private String Address;
private String img;
private String PAY_MODE;
private String min;
private String max;
private String imgs;
private int drawable_icon;
public int getDrawable_icon() {
return drawable_icon;
}
public void setDrawable_icon(int drawable_icon) {
this.drawable_icon = drawable_icon;
}
public String getEmail_id() {
return Email_id;
}
public void setEmail_id(String email_id) {
Email_id = email_id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getContact_no() {
return contact_no;
}
public void setContact_no(String contact_no) {
this.contact_no = contact_no;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getPAY_MODE() {
return PAY_MODE;
}
public void setPAY_MODE(String PAY_MODE) {
this.PAY_MODE = PAY_MODE;
}
public String getMin() {
return min;
}
public void setMin(String min) {
this.min = min;
}
public String getMax() {
return max;
}
public void setMax(String max) {
this.max = max;
}
public String getImgs() {
return imgs;
}
public void setImgs(String imgs) {
this.imgs = imgs;
}
public Vendor_Wrapper(String id, String name, String contact_no, String email_id, String address, String img, String PAY_MODE, String min, String max, String imgs) {
this.id = id;
Name = name;
this.contact_no = contact_no;
Email_id = email_id;
Address = address;
this.img = img;
this.PAY_MODE = PAY_MODE;
this.min = min;
this.max = max;
this.imgs = imgs;
}
}
Here is my example of implementing to BaseActivity, I found I did it differently and it worked for me.
My Base Activity
public abstract class BaseActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
//swap this to a switch statement
if (id == R.id.nav_newgame) {
// Start new game
Log.e("Base","new Game");
} else if (id == R.id.nav_players) {
} else if (id == R.id.nav_history) {
} else if (id == R.id.nav_tools) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_about) {
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Any activity sharing the same Navigation Drawer
public class MainActivity extends BaseActivity
{
NavigationView navigationView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
Allowing one dynamic Nav Drawer in your base activity saving you the trouble of writing code over and over. Additionally you can override the Base Activity's Nav Drawer and make different results for different situations.
I am using navigation drawer which calls multiple fragments on the click of a list item of navigation drawer.
In my scenario, parent activity handles 2 fragments. There is an expected behavior that I am facing in handling these fragments.
Here is what I am doing:
Go to offline mode -> Go to fragment 2 -> Minimize the app -> Go to online mode ( switch on the internet ) - > Resume the app
On resume of the app, the parent activity is called and in parent activity, by default fragment 1 is opened, rather it should open fragment 2.
Help is appreciated.
Here is my navigation drawer code -
public class NavigationDrawer extends ActionBarActivity implements OnItemClickListener {
private ActionBar actionBar;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
RelativeLayout user_panel;
LinearLayout mylinearlayout;
private ActionBarDrawerToggle mDrawerToggle;
// Initialize SharedPreferences and editor variable's.
SharedPreferences.Editor editor;
SharedPreferences pref;
String username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_drawer);
// Initialize SharedPreferences mode
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = pref.edit();
username = pref.getString("name", null); // getting String
moveDrawerToTop();
initActionBar();
initDrawer();
//Quick cheat: Add Fragment 1 to default view
onItemClick(null, null, 0, 0);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
private void moveDrawerToTop() {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
DrawerLayout drawer = (DrawerLayout) inflater.inflate(R.layout.decor, null); // "null" is important.
// HACK: "steal" the first child of decor view
ViewGroup decor = (ViewGroup) getWindow().getDecorView();
View child = decor.getChildAt(0);
decor.removeView(child);
LinearLayout container = (LinearLayout) drawer.findViewById(R.id.drawer_content); // This is the container we defined just now.
container.addView(child, 0);
drawer.findViewById(R.id.drawer).setPadding(0, getStatusBarHeight(), 0, 0);
ImageView profile = (ImageView) drawer.findViewById(R.id.image_view);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// Make the drawer replace the first child
decor.addView(drawer);
}
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
private int getContentIdResource() {
return getResources().getIdentifier("content", "id", "android");
}
#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.
mDrawerToggle.syncState();
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
int id = item.getItemId();
if (id == R.id.notification) {
Intent display_notify = new Intent(getApplicationContext(), DisplayActivity.class);
startActivity(display_notify);
return true;
}
return super.onOptionsItemSelected(item);
}
private void initActionBar() {
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
private void initDrawer() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mylinearlayout = (LinearLayout) findViewById(R.id.drawer);
mDrawerLayout.setDrawerListener(createDrawerToggle());
mDrawerList = (ListView) findViewById(R.id.MyList);
user_panel = (RelativeLayout) findViewById(R.id.user_profile_panel);
user_panel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
TextView user_name = (TextView) findViewById(R.id.left_panel_user_name);
user_name.setText(username);
ListAdapter adapter = (ListAdapter) (new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.nav_items)));
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(this);
}
private DrawerListener createDrawerToggle() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerStateChanged(int state) {
}
};
return mDrawerToggle;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mDrawerLayout.closeDrawer(mylinearlayout);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ftx = fragmentManager.beginTransaction();
if (position == 0) {
ftx.replace(R.id.main_content, new FragmentOne());
} else if (position == 1) {
ftx.replace(R.id.main_content, new FragmentSecond());
} else if (position == 2) {
} else if (position == 3) {
} else if (position == 4) {
invitation();
} else if (position == 5) {
launchMarket();
} else if (position == 6) {
ftx.replace(R.id.main_content, new Setting_Fragment());
}
ftx.commit();
}
}
I want to implement Left & Right Side Slider Menu so I have set Right Side Slider in NavigationDrawerSlider which already have Left Side Slider by Default.
I am using ActionBarSherLock for this to support Application from Api 8. Slider is working fine but issue is that ActionBar is not showing Title.
Please help me to solve this issue. One more thing, When I Click on ImageView, It also fires ActionBarDrawerToggle. So, how to prevent this also ?
My Code:
public class MainActivity extends SherlockFragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList_Left;
private ListView mDrawerList_Right;
private ActionBarDrawerToggle mDrawerToggle;
private ActionBar actionBar_Right;
private ArrayList<NavDrawerItem> navDrawerItems_Left;
private ArrayList<NavDrawerItem> navDrawerItems_Right;
private CharSequence mDrawerTitle_Left;
private CharSequence mTitle_Left;
private CharSequence mDrawerTitle_Right;
private CharSequence mTitle_Right;
private String[] mFragmentTitles_Left;
private String[] mFragmentTitles_Right;
private TypedArray navMenuIcons_Left;
private TypedArray navMenuIcons_Right;
private NavDrawerListAdapter adapter_Left;
private NavDrawerListAdapter adapter_Right;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle_Left = mDrawerTitle_Left = getTitle();
mFragmentTitles_Left = getResources().getStringArray(
R.array.nav_drawer_items);
mFragmentTitles_Right = getResources().getStringArray(
R.array.nav_drawer_items_right);
navMenuIcons_Left = getResources().obtainTypedArray(
R.array.nav_drawer_icons);
navMenuIcons_Right = getResources().obtainTypedArray(
R.array.nav_drawer_icons_right);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList_Left = (ListView) findViewById(R.id.list_left_slidermenu);
mDrawerList_Right = (ListView) findViewById(R.id.list_right_slidermenu);
actionBar_Right = getSupportActionBar();
actionBar_Right.setCustomView(R.layout.right_menu);
actionBar_Right.setDisplayShowTitleEnabled(true);
actionBar_Right.setDisplayShowCustomEnabled(true);
navDrawerItems_Left = new ArrayList<NavDrawerItem>();
navDrawerItems_Right = new ArrayList<NavDrawerItem>();
// Left Side Menus...
// Home...
navDrawerItems_Left.add(new NavDrawerItem(mFragmentTitles_Left[0],
navMenuIcons_Left.getResourceId(0, -1)));
navMenuIcons_Left.recycle();
// Right Side Menus...
// Edit Profile...
navDrawerItems_Right.add(new NavDrawerItem(mFragmentTitles_Right[0],
navMenuIcons_Right.getResourceId(0, -1)));
// Change Password...
navDrawerItems_Right.add(new NavDrawerItem(mFragmentTitles_Right[1],
navMenuIcons_Right.getResourceId(1, -1)));
navMenuIcons_Right.recycle();
mDrawerList_Left
.setOnItemClickListener(new DrawerItemClickListener_Left());
mDrawerList_Right
.setOnItemClickListener(new DrawerItemClickListener_Right());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
adapter_Left = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems_Left);
mDrawerList_Left.setAdapter(adapter_Left);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name, R.string.app_name);
adapter_Right = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems_Right);
mDrawerList_Right.setAdapter(adapter_Right);
ImageView imgRight = (ImageView) findViewById(R.id.imgRightMenu);
imgRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (mDrawerLayout.isDrawerOpen(mDrawerList_Right)) {
mDrawerLayout.closeDrawer(mDrawerList_Right);
setTitle(mTitle_Right);
} else {
mDrawerLayout.openDrawer(mDrawerList_Right);
mDrawerLayout.closeDrawer(mDrawerList_Left);
setTitle(mDrawerTitle_Right);
}
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem_Left(0);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(mDrawerList_Left)) {
mDrawerLayout.closeDrawer(mDrawerList_Left);
setTitle(mTitle_Left);
} else {
mDrawerLayout.openDrawer(mDrawerList_Left);
mDrawerLayout.closeDrawer(mDrawerList_Right);
setTitle(mDrawerTitle_Left);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class DrawerItemClickListener_Left implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
selectItem_Left(position);
}
}
private void selectItem_Left(int position) {
Fragment newFragment = new Home();
FragmentManager fm = getSupportFragmentManager();
switch (position) {
case 0:
newFragment = new Home();
break;
}
fm.beginTransaction().replace(R.id.frame_container, newFragment)
.commit();
mDrawerList_Left.setItemChecked(position, true);
setTitle(mFragmentTitles_Left[position]);
mDrawerLayout.closeDrawer(mDrawerList_Left);
}
private class DrawerItemClickListener_Right implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
selectItem_Right(position);
}
}
private void selectItem_Right(int position) {
Fragment newFragment = new EditProfile();
FragmentManager fm = getSupportFragmentManager();
switch (position) {
case 0:
newFragment = new EditProfile();
break;
case 1:
newFragment = new ChangePassword();
break;
}
fm.beginTransaction().replace(R.id.frame_container, newFragment)
.commit();
mDrawerList_Right.setItemChecked(position, true);
setTitle(mFragmentTitles_Right[position]);
mDrawerLayout.closeDrawer(mDrawerList_Right);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
I have figured out that It is not showing title because of
actionBar_Right = getSupportActionBar();
actionBar_Right.setCustomView(R.layout.right_menu);
actionBar_Right.setDisplayShowTitleEnabled(true);
actionBar_Right.setDisplayShowCustomEnabled(true);
What to do for this ?
For showing the title in the ActionBar setTitle must be overridden:
#Override
public void setTitle(CharSequence title)
{
this.title = title;
getSupportActionBar().setTitle(title);
}