Using Navigation Drawer in different Activities by extending BaseActivity - android

I'm trying to let my HomeActivity extend BaseActivity (as suggested here) so I can have the same Navigation Drawer in every Activity I want. But I get a NullPointerException in the onCreate method of my HomeActivity. This is the code of BaseActivity:
import android.os.Bundle;
import android.app.Activity;
import android.content.res.Configuration;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class BaseActivity extends Activity
{
public DrawerLayout drawerLayout;
public ListView drawerList;
private String[] drawerListEntries;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState)
{
drawerListEntries = new String[] {"Bla bla", "Profile", "Home"};
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle((Activity) this, drawerLayout, R.drawable.ic_navigation_drawer, 0, 0)
{
public void onDrawerClosed(View view)
{
getActionBar().setTitle(R.string.app_name);
}
public void onDrawerOpened(View drawerView)
{
getActionBar().setTitle(R.string.hello_world);
}
};
drawerLayout.setDrawerListener(drawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
//layers = getResources().getStringArray(R.array.layers_array);
drawerList = (ListView) findViewById(R.id.drawer_list);
// View header = getLayoutInflater().inflate(R.layout.drawer_list_header, null);
// drawerList.addHeaderView(header, null, false);
drawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, drawerListEntries));
// View footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
// R.layout.drawer_list_footer, null, false);
// drawerList.addFooterView(footerView);
drawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
//map.drawerClickEvent(pos);
String selectedValue = (String) drawerList.getAdapter().getItem(pos);
Toast.makeText(getBaseContext(), selectedValue, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
}
And this is the code of HomeActivity which extends BaseActivity:
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.facebook.Session;
public class HomeActivity extends BaseActivity {
TextView greeting;
Button orderButton, deliverButton, logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
//return super.onCreateOptionsMenu(menu);
return true;
}
}
I get a NullPointerException in:
super.onCreate(savedInstanceState); // HomeActivity
and when I click on that, it goes to:
drawerLayout.setDrawerListener(drawerToggle); // BaseActivity
Does anyone know how I can fix this?
Update:
drawer_list.xml:
<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" >
<ListView
android:id="#+id/drawer_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="10dp"
android:layout_marginTop="5dp"
android:background="#android:color/transparent"
android:cacheColorHint="#android:color/transparent"
android:divider="#CCCCCC"
android:dividerHeight="1dp"
android:paddingLeft="2dp" />
</android.support.v4.widget.DrawerLayout>
and drawer_list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/drawer_list_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="12dp"
android:textSize="24sp"
android:layout_gravity="left"
android:textColor="#color/belize_hole"
android:fontFamily="sans-serif-light">
</TextView>
</LinearLayout>

Same issue in a few posts. I am new to android but solved it this way. Would love to hear if there is a better "right" way to do it. (yes, without fragments but I know I need to learn them eventually).
The problem appears that the base class is not aware of the layout. Not sure how or why it worked for others without having to do something like this.. but I am new to Android.
I was getting the same error and solved by passing my layout to the base via onCreate.
So in the base, I modified onCreate to be like this:
protected void onCreate(Bundle savedInstanceState, int resLayoutID)
{
super.onCreate(savedInstanceState);
setContentView(resLayoutID);
Then, from my new activity, I have this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState, R.layout.my_activity);
This code in my base now works instead of staying null:
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerList = (ListView) findViewById(R.id.left_drawer);
btw, this result was suggested to me by a friend and it worked for me.

Related

ImageView may return Null?

I have a fragment that is half image and then half text.
Trying to assign the ImageView and the TextView but it says:
Might give null
and when I run the app it does not run.
I included the Java and XML files for fragment and included the mainActivity java.
Fragment code:
import android.media.Image;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.View;
import android.widget.TextView;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import android.view.View;
public class headercode extends Fragment implements Runnable{
ImageView image;
TextView text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(getView().findViewById(R.id.imageView ) != null)
{
image = (ImageView)getView().findViewById(R.id.imageView);
}
return inflater.inflate(R.layout.frag, container, false);
}
public void run(){
text.setText("Test");
}
}
Layout XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#692f2f">
<ImageView
android:layout_width="match_parent"
android:layout_height="300dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="269dp"
android:id="#+id/text"/>
</LinearLayout>
MainActivity code:
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
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.TextView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentManager;
import android.widget.FrameLayout;
import android.widget.Button;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.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);
if (findViewById(R.id.fragment) != null){
headercode header = new headercode();
getSupportFragmentManager().beginTransaction().add(R.id.fragment,header).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 onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);//This is the setting top right
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.Technology) {
} else if (id == R.id.Opinion) {
} else if (id == R.id.travel) {
} else if (id == R.id.politics) {
}else if(id == R.id.Home){
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
For fragment you should inflate first your xml in the onCreateView method, you get your view and you can find your corresponding ImageView:
View myView = inflater.inflate(R.layout.frag, container, false);
ImageView myImage = (ImageView) myView.findViewById(R.layout.my_image);
return myView;
In the xml you should add an id to the iamgeView in order to get it:
<ImageView
android:id="#+id/my_image"
android:layout_width="match_parent"
android:layout_height="300dp" />
Trying to assign the ImageView and the textView but it says Might give
null error and when i run the app it does not run.
That's a lint warning informing you that findViewById could return null. If your xml contains the id you are looking for, you don't have anything to worry about.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(getView().findViewById(R.id.imageView ) != null)
getView() returns the View the onCreateView returns, therefore you can't use getView() inside onCreateView. Override onViewCreate instead, and its parameter View to perform your findViewById calls
In the fragment you first need to infalte the view and then assing values to its content
Example:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag, container, false);
ImageView image = (ImageView) rootView.findViewById(R.id.imageView);
TextView tv = (TextView) rootView.findViewById(R.id.yourTextViewId);
tv.setText("Test");
// Here you will perform all the actions that you want to perform and then in the end return the view like below
return rootView;
}

extending another class and inflating its xml in my current activity hides the content of my current activity

I have created a navigationactivity where i am having navigation drawer and now when i extend this class in another activities its working but the content of other actvities are not getting displayed
here is my code:
package com.astro.famouspandit.Activities.Abstract;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
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.view.View;
import android.view.ViewStub;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import com.astro.famouspandit.Activities.Activity.ChartStyle;
import com.astro.famouspandit.Activities.Activity.Contact;
import com.astro.famouspandit.Activities.Activity.Settings;
import com.astro.famouspandit.R;
public class NavigationActivity extends AppCompatActivity implements View.OnClickListener{
protected DrawerLayout mDrawerLayout;
protected FrameLayout mFrameLayout_ContentFrame;
protected ActionBarDrawerToggle mActionBarDrawerToggle;
protected Toolbar mToolbar;
private LinearLayout mDrawerList2;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
mFrameLayout_ContentFrame = (FrameLayout) findViewById(R.id.main_activity_content_frame);
mDrawerList2 = (LinearLayout) findViewById(R.id.left_drawer2);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.main_activity_DrawerLayout);
mDrawerLayout.closeDrawers();
mDrawerLayout.setStatusBarBackground(R.color.colorPrimary);
mActionBarDrawerToggle = new ActionBarDrawerToggle
(
this,
mDrawerLayout,
mToolbar,
R.string.drawer_open,
R.string.drawer_close
) {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
// Disables the burger/arrow animation by default
super.onDrawerSlide(drawerView, 0);
}
};
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
mActionBarDrawerToggle.syncState();
}
#Override
public void onClick(View v) {
}
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList2);
menu.findItem(R.id.action_Aboutus).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
int items = item.getItemId();
switch(items){
case R.id.action_Settings:{
Intent intent = new Intent(this,Settings.class);
startActivity(intent);
}break;
case R.id.action_Contact_us:{
Intent intent = new Intent(this,Contact.class);
startActivity(intent);
}break;
case R.id.action_Aboutus:{
Intent intent = new Intent(this,ChartStyle.class);
startActivity(intent);
}break;
case R.id.action_Profile:{
Intent intent = new Intent(this,ChartStyle.class);
startActivity(intent);
}break;
}
return super.onOptionsItemSelected(item);
}
}
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_activity_DrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<LinearLayout android:id="#+id/left_drawer2"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:orientation="vertical"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#0F6177"/>
<!-- The main content view -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/main_activity_content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!-- The navigation drawer -->
</android.support.v4.widget.DrawerLayout>
class where i am extending it: i cannot see the content of this class
public class Contact extends NavigationActivity implements View.OnClickListener {
private EditText mName,mNumber,mEmail,mMessage;
private FancyButton mSbmt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.activity_contact,mFrameLayout_ContentFrame);
I think you are searching for the hierarchy used in the concept of BaseActivity you can make many child and use the behavior of parent. The formal concept is pass the layout from child Activity to the BaseActivity and BaseActivity will set the content.
First create an abstract class and name it BaseActivity, It should be something like
public abstract class BaseActivity extends AppCompatActivity{
#Override
public void onCreate(bundle) {
super.onCreate(bundle);
setContentView(getLayoutResourceId());
}
protected abstract int getLayoutResourceId();
}
Then in your case extend BaseActivity in NavigationActivity like here
public class NavigationActivity extends BaseActivity {
#Override
public void onCreate(bundle) {
super.onCreate(bundle);
// do extra stuff on your resources, using findViewById on your activity_navigation
}
#Override
protected int getLayoutResourceId() {
return R.layout.activity_navigation;
}
}

fragment text appearing in toolbar

I'm trying to get a sliding drawer set up. I want the text to appear in the main body of the activity, but instead it's appearing inside of the toolbar, and it only says This is fragment 2, regardless of whether I pulled up the fragment that's supposed to say This is fragment 1 or This is fragment 2.
How can I make it pull up the proper fragment, instead of always fragment 2, and how can I make the toolbar opaque, with text appearing under it instead of in it.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout"
tools:context="me.paxana.alerta.MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="8dp"
android:minHeight="?attr/actionBarSize"
android:layout_alignParentTop="true"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_content"
android:layout_alignParentTop="true">
</RelativeLayout>
<ListView
android:layout_width="200dp"
android:layout_height="match_parent"
android:id="#+id/lv_sliding_menu"
android:background="#FFFFFF"
android:choiceMode="singleChoice"
android:layout_gravity="start" />
</android.support.v4.widget.DrawerLayout>
MainActivity.java
package me.paxana.alerta;
import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.app.Fragment;
import android.content.Intent;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import com.parse.ParseUser;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import me.paxana.alerta.adapter.SlidingMenuAdapter;
import me.paxana.alerta.fragment.Fragment1;
import me.paxana.alerta.fragment.Fragment2;
import me.paxana.alerta.fragment.Fragment3;
import me.paxana.alerta.model.ItemSlideMenu;
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
private List<ItemSlideMenu> listSliding;
private SlidingMenuAdapter adapter;
private ListView listViewSliding;
private DrawerLayout drawerLayout;
private android.support.v7.app.ActionBarDrawerToggle actionBarDrawerToggle;
private Toolbar mToolbar;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser == null) {
navigateToLogin();
}
else {
Log.i(TAG, currentUser.getUsername());
}
listViewSliding = (ListView)findViewById(R.id.lv_sliding_menu);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
listSliding = new ArrayList<>();
//add item for sliding list
listSliding. add(new ItemSlideMenu(R.drawable.ic_action_settings, "Settings"));
listSliding.add(new ItemSlideMenu(R.drawable.ic_action_about, "About"));
listSliding.add(new ItemSlideMenu(R.drawable.ic_logout_black_48dp, "Log Out"));
adapter = new SlidingMenuAdapter(this, listSliding);
listViewSliding.setAdapter(adapter);
//display icon to open/close slider
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//item selected
listViewSliding.setItemChecked(0, true);
//close menu
drawerLayout.closeDrawer(listViewSliding);
//handle on item click
listViewSliding.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 2) {
ParseUser.logOut();
navigateToLogin();
} else {
//replace fragment
replaceFragment(position);
//item selected
listViewSliding.setItemChecked(position, true);
//close menu
drawerLayout.closeDrawer(listViewSliding);
}
}
});
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_opened, R.string.drawer_closed) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
}
private void navigateToLogin() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
int itemId = item.getItemId();
if (itemId == R.id.action_logout) {
ParseUser.logOut();
navigateToLogin();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
//create method replace fragment
private void replaceFragment(int pos) {
android.support.v4.app.Fragment fragment = null;
switch (pos) {
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
default:
fragment = new Fragment1();
break;
}
if(null != fragment) {
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_content, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
}
I solved one part of this issue, though I'm not certain I used best practices. I added padding to the top of main_content in a size of "?attr/actionBarSize"
But it's still only displaying This is Fragment 2, regardless of which fragment I'm trying to select.
If you want the content below the toolbar, you can wrap toolbar and content in one layout as:
<LinearLayout
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="?attr/actionBarSize"
android:minHeight="?attr/actionBarSize"
android:layout_alignParentTop="true"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_content"
android:background="#8000ff00"
>
</RelativeLayout>
</LinearLayout>
Besides, if you are using Android Studio, creating Navigation Drawer Activity through the wizard is the best way to ensure that everything works properly.

onitemclicklistener does not work after fragment is executed

my problem is that as soon as i call a fragment in my main layout, the fragment is called in the frame, but after that, the onitemclick listener stops working. what is that i missed ?
the main.java
import java.util.Locale;
import android.annotation.TargetApi;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
public class Main extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mDrawerMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTitle = mDrawerTitle = getTitle();
mDrawerMenu = getResources().getStringArray(R.array.menu);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_view);
// set a custom shadow that overlays the main content when the drawer opens
//mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.custom_menu_list, mDrawerMenu));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
//Action bar on item click events
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action buttons
switch(item.getItemId()) {
case R.id.menu_icon:
// create intent to perform web search for this planet
Log.d("Hello","Menu clicked");
mDrawerLayout.openDrawer(mDrawerList);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listener for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
Log.d("Hello", String.valueOf(position));
//Get the option name and compare
TextView text = (TextView) arg1.findViewById(android.R.id.text1);
String MenuName = text.getText().toString();
Log.d("Click", MenuName);
if(position == 0){
Log.d("Click","Home Clicked");
// update the main content by replacing fragments
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MenuFragment fragment = new MenuFragment();
fragmentTransaction.replace(R.id.drawer_layout, fragment, String.valueOf(position));
fragmentTransaction.commit();
}
else if(position == 1){
Log.d("Click","News Clicked 2");
}
mDrawerLayout.closeDrawer(mDrawerList);
}
}
}
This is the main.xml
<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"
android:background="#FFFFFF">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"/>
<!-- The navigation drawer -->
<ListView android:id="#+id/list_view"
android:layout_width="320dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#000000"/>
</android.support.v4.widget.DrawerLayout>
This is the menugragment which calls the layout.
public class MenuFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.sports, container, false);
}
}
Now, as it is replaced in the frame in main (when the position is 0, the fragment is called),after that if 1 is called, the onitemclicklistener does not work. why is that ?
Thank you
replace
fragmentTransaction.replace(R.id.drawer_layout, fragment, String.valueOf(position));
to
fragmentTransaction.replace(R.id.content_frame, fragment, String.valueOf(position));
You should replace the content_frame not the drawer_layout

Android Navigation Drawer not being closed by dragging it

I'm trying to implement a Navigation Drawer and I managed successfully to integrate it with the Action Bar: it opens and closes when the application button is pressed and it closes when I press on a blank part of the screen, but it does not allow to be dragged back to its original position. Once opened, I can't close it with a swipe (as in every application I have seen so far).
Here is my Java code:
package com.example.notificationswhisperer;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class MainActivity
extends Activity {
private DrawerLayout drawerLayout;
private ListView drawerList;
private ActionBarDrawerToggle drawerToggle;
private List<AppDrawerItem> drawerItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notifications_whisperer);
drawerItems = new ArrayList<AppDrawerItem>();
drawerItems.add(
new AppDrawerItem("Settings",
getResources().getDrawable(R.drawable.ic_action_settings)));
drawerItems.add(
new AppDrawerItem("Test",
getResources().getDrawable(R.drawable.ic_action_settings)));
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
drawerLayout = (DrawerLayout) findViewById(R.id.layout_app_drawer);
drawerToggle = new ActionBarDrawerToggle(
this, // Context
drawerLayout, // DrawerLayout object
R.drawable.ic_drawer, // Drawer icon
0, // Open Drawer description
0) { // Closed Drawer description
public void onDrawerOpened(View view) {
super.onDrawerOpened(view);
invalidateOptionsMenu();
}
public void onDrawerSlide(View view, float offset) {
if (offset > .5) {
onDrawerOpened(view);
} else {
onDrawerClosed(view);
}
}
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(drawerToggle);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.START);
drawerList = (ListView) findViewById(R.id.list_app_drawer);
drawerList.setAdapter(new AppDrawerAdapter(this, drawerItems));
drawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
drawerList.setItemChecked(position, true);
drawerLayout.closeDrawer(drawerList);
}
});
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration config) {
super.onConfigurationChanged(config);
drawerToggle.onConfigurationChanged(config);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.notifications_whisperer, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my layout for the activity:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layout_app_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.notificationswhisperer.NotificationsWhisperer" >
<ListView
android:id="#+id/list_app_drawer"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/black"
android:dividerHeight="0.5dp"
android:background="#android:color/white" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</android.support.v4.widget.DrawerLayout>
And this is for the List entries:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="vertical" >
<ImageView
android:id="#+id/list_item_app_drawer_image"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_marginLeft="8dp"
android:layout_centerVertical="true" />
<TextView
android:id="#+id/list_item_app_drawer_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/list_item_app_drawer_image"
android:textSize="18sp" />
</RelativeLayout>
Am I missing something? Thank you in advance.
ADDENDUM: Additionally, the back button won't close the Drawer.
I had the very same issue : the drawer could be opened by a swipe, but could only be closed by a click on the actionbar button.
After some research, it appeared that the underlying activity had several critical bugs : some fragments were added which were adding an un-initialized pager (with a null adapter)
Anyway, when I fixed these bugs (which had nothing to do with the drawer implementation), then behavior went correct.

Categories

Resources