How to make click on ActionBar Logo in android - android

I tried to do something on Click on icon in ActionBar but do nothing.I also like to do open drawer_layout on click on a icon in action bar. How to make it clickable and handle the event of it`s pressing?
public class MainActivity extends AppCompatActivity {
ViewPager viewPager,viewPager01;
CustomSwipAdapter swip_adapter;
CustomSwipAdapter01 swip_adapter01;
String[] menu;
DrawerLayout dLayout;
ListView dList;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
getSupportActionBar().setLogo(R.drawable.sample_01);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("");
}
catch (Exception e) {
}
viewPager = (ViewPager)findViewById(R.id.viewpager);
swip_adapter =new CustomSwipAdapter(this);
viewPager.setAdapter(swip_adapter);
/* viewPager01 = (ViewPager)findViewById(R.id.viewpager01);
swip_adapter01 =new CustomSwipAdapter01(this);
viewPager01.setAdapter(swip_adapter01);*/
menu = new String[]{"Home","E-Gift Voucher"};
dLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
dList = (ListView)findViewById(R.id.left_drawer);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,menu);
dList.setAdapter(adapter);
dList.setSelector(android.R.color.holo_blue_dark);
dList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
dLayout.closeDrawers();
Bundle args = new Bundle();
args.putString("Menu", menu[position]);
Fragment detail = new DetailFragment();
detail.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, detail).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_main, menu);
MenuInflater inf = getMenuInflater();
inf.inflate(R.menu.main_activity_action,menu);
return super.onCreateOptionsMenu(menu);*/
MenuInflater inf = getMenuInflater();
inf.inflate(R.menu.main_activity_action,menu);
return true;//super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
// int id = item.getItemId();
switch (item.getItemId()){
case android.R.id.home:
Toast.makeText(MainActivity.this,"Click on Logo",Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

layout xml
<RelativeLayout
android:id="#+id/rl_main_search_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/transparent_semi"
tools:context="com.worldofmoms.views.fragments.search_and_explore.SearchFragment">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:theme="#style/ActionBar_Light"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar_search"
android:background="#android:color/white"
android:visibility="gone"
/>
</RelativeLayout>
Add in your activity onCreate()
mToolbar = (Toolbar) view.findViewById(R.id.toolbar_search);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
and Add
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id==android.R.id.home){
// home button from toolbar clicked
}
}

Add in your activity onCreate(): i am quite sure it may help you...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Custom code for image icon which redirects to homepage
ActionBar actionBar=getSupportActionBar();
actionBar.setDisplayOptions(actionBar.getDisplayOptions()
| ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView imageView = new ImageView(actionBar.getThemedContext());
imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setImageResource(R.mipmap.ic_launcher);
imageView.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v) {
webViewPlaceholder.loadUrl("http://www.salebhai.com");
} });
ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.WRAP_CONTENT, Gravity.LEFT
| Gravity.CENTER_VERTICAL);
layoutParams.leftMargin = 20;
imageView.setLayoutParams(layoutParams);
actionBar.setCustomView(imageView);
actionBar.setDisplayHomeAsUpEnabled(true);
Thank you ,
happy Coding.....

Related

Floating context menu on button click inside Fragment

In my app I have created few buttons in one fragment which will redirect to several activity based on the click. Now if user click button1, they will get a floating context menu conataing the list of the comapny, such as company1, compan2...etc. I have followed this post Opening a floating menu (context menu) in Android? to develop this feature in my app. But the problem is that this code is implemented in Activity, where in my case I want ti implement it in Fragment. I wrote the code but nothig happen with the button click. Now how can I generate this menu on button click
My contextmenu is
<?xml version="1.0" encoding="utf-8"?>
<item android:id="#+id/company_1"
android:title="#string/company_1"></item>
<item android:id="#+id/company_2"
android:title="#string/company_2"></item>
<item android:id="#+id/company_3"
android:title="#string/company_3"></item>
<item android:id="#+id/company_4"
android:title="#string/company_4">
</item>
<item android:id="#+id/company_5"
android:title="#string/company_5"></item>
<item android:id="#+id/company_6"
android:title="#string/company_6">
</item>
My Fragment Class is
public class MainFragment extends Fragment implements View.OnClickListener{
public MainFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
Button button1=(Button) view.findViewById(R.id.button1);
button1.setOnClickListener(this);
registerForContextMenu(button);
Button button2=(Button) view.findViewById(R.id.button2);
button2.setOnClickListener(this);
Button button3=(Button) view.findViewById(R.id.button3);
button3.setOnClickListener(this);
// Inflate the layout for this fragment
return view;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
if(v.getId()==R.id.button1){
this.getActivity().getMenuInflater().inflate(R.menu.contextmenu_company,menu);
}
super.onCreateContextMenu(menu, v, menuInfo);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
setHasOptionsMenu(true);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.company_1:
Toast.makeText(getActivity().getApplicationContext(),"caompany1code",Toast.LENGTH_LONG).show();
return true;
case R.id.company_2:
......
case R.id.company_3:
.....
case R.id.company_4:
....
return true;
case R.id.company_5:
.....
return true;
case R.id.company_6:
.....
return true;
}
return super.onContextItemSelected(item);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
Toast.makeText(getActivity(),"My colleagues clicked", Toast.LENGTH_SHORT).show();
break;
case R.id.button2:
Toast.makeText(getActivity(), "News clicked", Toast.LENGTH_SHORT).show();
break;
case R.id.button3:
Toast.makeText(getActivity(), "Navigator clicked", Toast.LENGTH_SHORT).show();
break;
}
}
In MainActivity Class
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
NavigationView navigationView = null;
Toolbar toolbar = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set the fragment initially
MainFragment fragment = new MainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
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) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#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.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
.....
}
Well i found something here :
Try this in your fragment :
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
if(v.getId()==R.id.button1{getActivity().getMenuInflater().inflate(R.menu.contextmenu_company,menu);
}
}
You are also calling this wrong:
//Instead of button use button1.
registerForContextMenu(button1);
Maybe this will help.
You did use
onCreateOptionsMenu(Menu menu)
in your Activity but you are trying to use
onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo)
in your fragment.
Use onCreateOptionsMenu(Menu menu) in your fragment as well and set setHasOptionsMenu(true) in your onCreateView method.

Selecting item of sliding tabs menu from navigation drawer with some fragment

I have a project navigation drawer using library (https://github.com/mikepenz/MaterialDrawer) with sliding tab which contained 3 fragment (HomeFragment, LiveFragment, MovieFragment).
I was created navigation drawer in MainActivity.class there are some items (Home, Live TV, Movie). I want when i click item Home from navigation drawer and then go to HomeFragment. I have tried with code below but nothing happen when i click item Home from navigation drawer.
Please help me to resolve this problem. Thank you :)
this is my MainAactivity.class
public class MainActivity extends AppCompatActivity{
public final static int NAV_ID_FRAG_ONE = 1;
public final static int NAV_ID_FRAG_TWO = 2;
public final static int NAV_ID_FRAG_THREE = 3;
public final static int NAV_ID_ABOUT_ACTIVITY = 6;
Toolbar toolbar;
private SlidingTabLayout mSlidingTabLayout;
private ViewPager mViewPager;
private Drawer result;
private AccountHeader headerResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
toolbar.setTitle("JMN Anywhere");
setSupportActionBar(toolbar);
mViewPager = (ViewPager) findViewById(R.id.vp_tabs);
mViewPager.setAdapter(new TabAdapter(getSupportFragmentManager(), this));
mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.st1_tabs);
mSlidingTabLayout.setDistributeEvenly(true);//meratakan posisi icon
mSlidingTabLayout.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
mSlidingTabLayout.setSelectedIndicatorColors(getResources().getColor(R.color.slidingcolor));
mSlidingTabLayout.setCustomTabView(R.layout.tab_view, R.id.tv_tab);
mSlidingTabLayout.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
mSlidingTabLayout.setViewPager(mViewPager);
//Navigation Drawer
//Header
AccountHeader headerResult = new AccountHeaderBuilder()
.withActivity(this)
.withCompactStyle(false)
.withSavedInstance(savedInstanceState)
.withThreeSmallProfileImages(false)
.withHeaderBackground(R.drawable.header)
.build();
//List Drawer
Drawer result = new DrawerBuilder()
.withActivity(this)
.withToolbar(toolbar)
.withDisplayBelowStatusBar(true)
.withActionBarDrawerToggleAnimated(true)
.withDrawerGravity(Gravity.LEFT)
.withSavedInstance(savedInstanceState)
.withAccountHeader(headerResult)
.withHasStableIds(true)
.withAccountHeader(headerResult) //set the AccountHeader we created earlier for the header
.addDrawerItems(//set item drawer
new PrimaryDrawerItem().withName("Home").withDescription("Beranda").withIcon(R.drawable.ic_home_black_48dp).withIdentifier(NAV_ID_FRAG_ONE).withSelectable(false),
new PrimaryDrawerItem().withName("Live TV").withDescription("Siaran Televisi").withIcon(R.drawable.ic_live_tv_black_48dp).withIdentifier(NAV_ID_FRAG_TWO).withSelectable(false),
new PrimaryDrawerItem().withName("Movies").withDescription("Film-film").withIcon(R.drawable.ic_local_movies_black_48dp).withIdentifier(NAV_ID_FRAG_THREE).withSelectable(false),
new ExpandableDrawerItem().withName("Categories").withLevel(2).withIdentifier(4).withSelectable(false).withSubItems(
new SecondaryDrawerItem().withName("Action").withLevel(3).withIdentifier(2000),
new SecondaryDrawerItem().withName("Comedy").withLevel(3).withIdentifier(2001)
),
new SectionDrawerItem().withName("Others"),
new SecondaryDrawerItem().withName("Account").withIcon(R.drawable.ic_account_box_black_48dp).withIdentifier(5).withSelectable(false),
new SecondaryDrawerItem().withName("About").withIcon(R.drawable.ic_info_black_48dp).withIdentifier(NAV_ID_ABOUT_ACTIVITY).withSelectable(false),
new SecondaryDrawerItem().withName("Logout").withIcon(R.drawable.ic_exit_to_app_black_48dp).withIdentifier(7).withSelectable(false)
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int i, IDrawerItem drawerItem) {
Fragment fragment = null;
switch ((int) drawerItem.getIdentifier()) {
case NAV_ID_FRAG_ONE:
fragment = new HomeFragment();
break;
case NAV_ID_FRAG_TWO:
fragment = new LiveFragment();
break;
case NAV_ID_FRAG_THREE:
fragment = new MovieFragment();
break;
case NAV_ID_ABOUT_ACTIVITY:
Intent intent = new Intent(MainActivity.this, AboutActivity.class);
startActivity(intent);
break;
}
return false;
}
})
.withSelectedItem(1)
.withFireOnInitialOnClick(true)
// add the items we want to use with our Drawer
.build();
new RecyclerViewCacheUtil<IDrawerItem>().withCacheSize(2).apply(result.getRecyclerView(), result.getDrawerItems());
}
#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) {
switch (item.getItemId()) {
case R.id.action_settings:
// User chose the "Settings" item, show the app settings UI...
Intent in = new Intent("com.ajjunaedi.jmnanywhere.AboutActivity");
startActivity(in);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
You need to add FragmentManager to add/remove/replace a fragment.
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment,fragment).commit();
getSupportFragmentManager() = Return the FragmentManager for interacting with fragments associated with this activity.
.beginTransaction() = Start a series of edit operations on the Fragments associated with this FragmentManager.
R.id.fragment is the id of the container where you be putting your fragment.
for more info refer to this post - What does FragmentManager and FragmentTransaction exactly do?
EDIT: you will add this after your switch statement. I hope this is the answer that you are looking for.
Add this to your xml file. inside the baselayout
<RelativeLayout
android:id="#+id/fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Resize it to your desire. or you can simply add the line android:id="#+id/fragment" to your baselayout.

Android: Navigation menu not working with button but with touch

Hiho!
I build a navigation drawer into my android app. I used the howto from http://blog.teamtreehouse.com/add-navigation-drawer-android and modified it at one place of the layout. I can activate the menu when i touch and swing my finger from left to right. But if I touch the hamburger menu nothing hapend. What ist wrong?
If i swipped in the menu the icon changed to an arrow, so there is a connection.
Hope some one can help me.
My Java Class (Main Activity):
public class AmericanFootball extends AppCompatActivity {
private MenuItem mi;
public static Context context;
private ListView mDrawerList;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private String mActivityTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = (Context) this;
setContentView(R.layout.activity_american_football);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(getText(R.string.app_name));
setSupportActionBar(toolbar);
mDrawerList = (ListView)findViewById(R.id.navList);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawerLayout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
checkInternet ci = new checkInternet();
boolean internet=ci.isNetzwerkVerfuegbar((Context) this);
TextView tv = (TextView) findViewById(R.id.tv_hello);
tv.setTypeface(FontManager.getTypeface((Context) this, FontManager.FONTAWESOME));
tv.setText(R.string.fa_icon_areachart);
tv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimaryLight));
}
#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_american_football, menu);
MenuItem mi = menu.findItem(R.id.action_refresh);
TextDrawable td = new TextDrawable((Context) this);
td.setText(getString(R.string.fa_refresh));
td.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimaryLight));
td.setTextSize(30);
mi.setIcon(td);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageView iv = (ImageView)inflater.inflate(R.layout.iv_refresh, null);
iv.setImageDrawable(td);
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_refresh) {
doRefreshGames(item);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
private void addDrawerItems() {
String[] osArray = { "Android", "iOS", "Windows", "OS X", "Linux" };
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(AmericanFootball.this, "Time for an upgrade!", Toast.LENGTH_SHORT).show();
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Navigation!");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
}
My layoutfile:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="k0f.de.americanfootball.AmericanFootball">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_american_football" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<ListView
android:id="#+id/navList"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="left|start"
android:background="#ffeeeeee"/>
</android.support.v4.widget.DrawerLayout>
</android.support.design.widget.CoordinatorLayout>
I found my mistake. Forgot a little thing:
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
}

Add icon in navigation Drawer

I have a navigation drawer and i want to add icon. But i dont know how to implement it. Is there any way i can customize my list inside navigation drawer? and use menu instead of array for items inside the navigation drawer. Thanks in advance :)
Heres my code :
public class MainActivity extends ActionBarActivity {
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerList = (ListView)findViewById(R.id.navList);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, new One()).commit();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void addDrawerItems() {
String[] osArray = { "Android", "iOS", "Windows", "OS X", "Linux" };
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
Fragment fragment = null;
Class fragmentClass;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 1:
fragmentClass = One.class;
break;
case 2:
fragmentClass = Two.class;
break;
default:
break;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager=getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
// Highlight the selected item, update the title, and close the drawer
mDrawerLayout.closeDrawers();
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Navigation!");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu();
// creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.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) {
// 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;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Inside your navigation Drawer xml file add menu file app:menu="#menu/activity_main_drawer"
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:menu="#menu/activity_main_drawer">
</android.support.design.widget.NavigationView>
in activity_main_drawer menu file define your icons wrt their names
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item android:id="#+id/nav_camara" android:icon="#android:drawable/ic_menu_camera"
android:title="Camera" />
<item android:id="#+id/nav_gallery" android:icon="#android:drawable/ic_menu_gallery"
android:title="Gallery" />
<item android:id="#+id/nav_manage" android:icon="#android:drawable/ic_menu_manage"
android:title="Manage" />
</group>
In your MainActivity.java call the action of each item click of drawer menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Handle navigation view item clicks here.
int id = menuItem.getItemId();
if (id == R.id.nav_camara) {
// Call your Action
} else if (id == R.id.nav_gallery) {
// Call your Action
} else if (id == R.id.nav_manage) {
// Call your Action
}
}
Yes, just create your custom layout for drawer list item.
Check answer f.e. here How to add icons to items in a navigation drawer
In your case you have to create your own adapter instead of ArrayAdapter and your custom item list view, that will contain ImageView for icon.

How to hide the whole RecyclerView?

I am trying to hide the RecyclerView until the user passes some valid information. But it is not happening. Some weird things happen when I try this but it doesn't show any error.
Here's my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private LinearLayout recyclerRow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Paper.init(getApplicationContext());
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), (Toolbar) findViewById(R.id.app_bar));
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.goalList);
RVAdapter adapter = new RVAdapter(getApplicationContext(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerRow = (LinearLayout) findViewById(R.id.goal_row);
if(Paper.get("goalTitle") == null){
recyclerView.setVisibility(View.GONE);
recyclerRow.setVisibility(View.GONE);
}
}
public List<RVData> getData() {
Log.d("Check6", Paper.get("goalTitle") + "");
List<RVData> data = new ArrayList<>();
String[] titles = {(String) Paper.get("goalTitle")};
for (int i = 0; i < titles.length; i++) {
RVData current = new RVData();
current.goalTitle = titles[i];
data.add(current);
}
return data;
}
public void newGoal(View view) {
Intent intent = new Intent(MainActivity.this, NewGoal.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I am using Paper for my database.
Instead of setVisibility, You can use setAlpha(0) to hide and setAlpha(1) to show. This is what I ended up doing. It is quite working well. It will be the same effect as if you use visibility Invisible.

Categories

Resources