I want to change the Action Bar title in the .java file depending on which cell is tapped. When the new activity is called here, I am only able to change the action bar title through the xml file, but I want to use a string from my previous activity (in order to change the action bar title to whatever the cell title was in the previous activity).
In this case the String would be sText
public class ListViewAndroidExample extends Activity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.list_view_android_example, menu);
return super.onCreateOptionsMenu(menu);
}
ListView listView ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_android_example);
try {
setContentView(R.layout.activity_list_view_android_example);
ListView mlistView = (ListView) findViewById(R.id.list);
mlistView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
new String[] {"#unlv", "#unr", "#ucla", "#usc"}));
mlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text Game, Help, Home
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
String sText = ((TextView) view).getText().toString();
Intent intent;
intent = new Intent(ListViewAndroidExample.this, ChatRoom.class);
startActivity(intent);
//else if(sText.equals("Help")) ..........
}
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Created by Jason on 6/30/2014.
*/
public static class ChatRoom extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatlayout);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
}
}
Did you try
getActionBar().setTitle(sText);
or
getSupportActionBar().setTitle(sText);
Related
I am New to Android. I Have Created Tab using android.support.v4.view.ViewPager. When i trying to get data from server using Json Request it give me the Error
AccountActivity is not an enclosing class.
please Any Help will be Appreciated
TAb1.java
public class Tab1 extends Fragment {
private ProgressDialog pDialog;
private UserAddress userAddress;
private TextView txtResponsec;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new LoadUserAddress().execute();
}
class LoadUserAddress extends AsyncTask<String,String,String> {
private ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
JSONHttpClient jsonHttpClient = new JSONHttpClient();
userAddress = jsonHttpClient.Get(ServiceUrl.UserAddress, nameValuePairs, UserAddress.class);
String id = userAddress.GetId();
}
catch (Exception ex){
String message = ex.getMessage();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute(); //To change body of overridden methods use File | Settings | File Templates.
progressDialog = new ProgressDialog(AccountActivity.this);
progressDialog.setMessage("Loading products. Please wait...");
progressDialog.show();
}
#Override
protected void onPostExecute(String s) {
progressDialog.dismiss();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
txtResponsec.setText(userAddress.GetCountry());
}
});
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1,container,false);
return v;
}
}
AccountActivity.java
public class AccountActivity extends AppCompatActivity {
Toolbar toolbar;
ActionBar actionBar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Info.","Address","Contact","Email"};
int Numboftabs =4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (toolbar != null) {
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}
#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_account, 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);
}
}
You should change
progressDialog = new ProgressDialog(AccountActivity.this);
to
progressDialog = new ProgressDialog(getActivity());
in Tab1 Fragment also i see txtResponsec=null you forget to initialized it.
Edit:
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1,container,false);
txtResponsec=(TextView)v.findViewById(R.id.txtResponsecId);
return v;
}
i am a newbie for Android Programming.
Here i have some problem when i want to make an activity (call Category_Setting) that showing list view, but when i switch from main activity to Category_Setting the error report in Android Studio gimme some error like this
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ever_ncn.cashflow/com.example.ever_ncn.cashflow.CategorySetting}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
I have googling for it, asking some friend, but still i even don't know what is my error for.
Please somebody answer my question with simple understanding words.
Thank You..
NB. here is my code for MainActivity.java
public class MainActivity extends Activity implements OnItemSelectedListener {
private static Button BtnINewTrans;
private static Button BtnIViewCash;
private static Button BtnIAddCateg;
Spinner my_Spinner;
DatabaseHelper dbHelper = new DatabaseHelper(this);
//ArrayAdapter<String> adapterCategory;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
my_Spinner = (Spinner)findViewById(R.id.spnCategSelect);
my_Spinner.setOnItemSelectedListener(this);
select_spinner_Category();
onButtonClickButtonListener();
}
/*ArrayList<String> my_array = new ArrayList<String>();
my_array = getTableValues();*/
/*ArrayAdapter my_Adapter = new ArrayAdapter(this, R.layout.spinner_row, my_array);
My_spinner.setAdapter(my_Adapter);*/
public void select_spinner_Category () {
my_Spinner = (Spinner)findViewById(R.id.spnCategSelect);
DatabaseHelper dbH = new DatabaseHelper(getApplicationContext());
List<String> listCategory = dbH.getAllCategory();
ArrayAdapter<String> adapterCategory = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, listCategory);
adapterCategory
.setDropDownViewResource(android.R.layout.simple_spinner_item);
my_Spinner.setAdapter(adapterCategory);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id){
String label = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "You selected "+label,
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
/*ArrayList<String> arrayCategory;
arrayCategory = dbHelper.getAllCategory();
selectCategory = (Spinner) findViewById(R.id.spnCategSelect);
ArrayAdapter adapterCategory = new ArrayAdapter(this, android.R.layout.simple_spinner_item, arrayCategory);
// adapterCategory = new ArrayList<String>(this, android.R.layout.simple_spinner_item, R.id.spnCategSelect, AllCategoryList);
adapterCategory.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selectCategory.setAdapter(adapterCategory);
selectCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), parent.getItemAtPosition(position) + " selected", Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}*/
#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;
}
public void onButtonClickButtonListener(){
BtnINewTrans = (Button)findViewById(R.id.btnNewTrans);
BtnINewTrans.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentNewTrans = new Intent ("com.example.ever_ncn.cashflow.NewTransaction");
startActivity(intentNewTrans);
}
}
);
BtnIViewCash = (Button)findViewById(R.id.btnViewCashflow);
BtnIViewCash.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentViewCash = new Intent ("com.example.ever_ncn.cashflow.ViewCashflow");
startActivity(intentViewCash);
}
}
);
BtnIAddCateg = (Button)findViewById(R.id.btnAddCateg);
BtnIAddCateg.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentAddCateg = new Intent ("com.example.ever_ncn.cashflow.CategorySetting");
startActivity(intentAddCateg);
}
}
);
}
#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);
}
}
And this is Category_Setting.java (where i get this error)
public class CategorySetting extends Activity {
private SQLiteDatabase db;
private CursorAdapter currAdapter;
private static Button BtnIAddCateg;
private static Button BtnICancelCateg;
private static final String TAG = CategorySetting.class.getSimpleName();
DatabaseHelper dBHelper = new DatabaseHelper (this);
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onButtonClickButtonListener();
//reload();
}
public void reload(){
listView = (ListView) findViewById(R.id.listViewCateg);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "clicked on item: " + position);
}
}
);
}
#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_category_setting, menu);
return true;
}
public void onButtonClickButtonListener(){
BtnIAddCateg = (Button)findViewById(R.id.btnAddNewCateg);
BtnIAddCateg.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentAddCateg = new Intent ("com.example.ever_ncn.cashflow.AddCategory");
startActivity(intentAddCateg);
}
}
);
BtnICancelCateg = (Button)findViewById(R.id.btnCancelCateg);
BtnICancelCateg.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
}
);
}
#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);
}
}
In this method in Category_Setting.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onButtonClickButtonListener();
//reload();
}
you forgot to load the layout. You should add some code like you used in the MainActivity:
setContentView(R.layout.activity_main);
Right now, the layout is not loaded at all, so
BtnINewTrans = (Button)findViewById(R.id.btnNewTrans);
will return null.
I have a problem with my app when I try to return a string array from an activity that was launched for a result. For some strange reason, my app also doesn't display the action bar, no matter what I do. I have put the code below.
MainActivity is launched first then DropDownList is called for Result.
DropDownList.Java
public class DropDownList extends Activity implements View.OnClickListener {
private ListView lView;
String[] lv_items;
ArrayAdapter<String> adapter;
Button button;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_drop_down_list);
lv_items = getResources().getStringArray(R.array.subjects_List);
findViewsById();
lView = (ListView) findViewById(R.id.ListView01);
// Set option as Multiple Choice. So that user can able to select more the one option from list
lView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, lv_items));
lView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
button.setOnClickListener(this);
}
private void findViewsById() {
lView = (ListView) findViewById(R.id.ListView01);
button = (Button) findViewById(R.id.submitButton);
}
//I BELIEVE THIS IS WHERE THE PROBLEMATIC CODE IS
public void onClick(View v) {
SparseBooleanArray checked = lView.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
if (checked.valueAt(i))
selectedItems.add(adapter.getItem(position));
}
String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = selectedItems.get(i);
}
Intent returnIntent = new Intent(getApplicationContext(),
MainActivity.class);
// Create a bundle object
Bundle b = new Bundle();
b.putStringArray("selectedItems", outputStrArr);
// Add the bundle to the intent.
returnIntent.putExtras(b);
// start the ResultActivity
setResult(RESULT_OK, returnIntent);
/**returnIntent.putExtra("SelectedBook",book);*/
finish();
}
#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
switch(id) {
case R.id.action_ok:
break;
case R.id.about_menu:
Toast.makeText(this, "developed by Seyi Oluwasanmi",
Toast.LENGTH_SHORT).show();
break;
case R.id.action_settings:
Toast.makeText(getApplicationContext(),"Settings Clicked",Toast.LENGTH_SHORT).show();
break;
}
return true;
}
}
MainActivity.Java
public class MainActivity extends Activity {
public static final int ReqCode = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageButton addButton = (ImageButton) findViewById(R.id.add_button);
ViewOutlineProvider viewOutlineProvider = new ViewOutlineProvider() {
#Override
public void getOutline(View view, Outline outline) {
// Or read size directly from the view's width/height
int size = getResources().getDimensionPixelSize(R.dimen.fab_size);
outline.setOval(0, 0, size, size);
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this, DropDownList.class);
startActivityForResult(myIntent, ReqCode);
}
});
}
};
addButton.setOutlineProvider(viewOutlineProvider);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ReqCode:
if (resultCode == RESULT_OK) {
ArraySubs();
break;
}
}
}
public void ArraySubs() {
Bundle b = getIntent().getExtras();
String[] subChoices = b.getStringArray("selectedItems");
ListView lv = (ListView) findViewById(R.id.outputList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, subChoices);
lv.setAdapter(adapter);
};
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
MenuInflater blowUp=getMenuInflater();
blowUp.inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id) {
case R.id.action_ok:
break;
case R.id.action_settings:
Toast.makeText(getApplicationContext(),"Settings Clicked", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
}
MENU.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
<item android:id="#+id/action_ok"
android:icon="#drawable/ic_menu_done"
android:title="#string/action_ok"
android:showAsAction="ifRoom"
/>
<item android:id="#+id/about_menu"
android:title="#string/about_menu"
android:showAsAction="ifRoom"
/>
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:showAsAction="ifRoom"
/>
</menu>
String Array of Subjects
<string-array name="subjects_List">
<item>Maths</item>
<item>English</item>
<item>Physics</item>
<item>Biology</item>
<item>Computing</item>
<item>Chemistry</item>
<item>French</item>
<item>Music</item>
<item>Philosophy</item>
<item>Art</item>
</string-array>
For the action bar issue, have your activities extend "ActionBarActivity" rather than just "Activity" and that will be fixed.
For the other issue, your problem is here:
selectedItems.add(adapter.getItem(position));
because adapter is not being initialized.
Change the following:
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_drop_down_list);
lv_items = getResources().getStringArray(R.array.subjects_List);
findViewsById();
lView = (ListView) findViewById(R.id.ListView01);
// Set option as Multiple Choice. So that user can able to select more the one option from list
lView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, lv_items));
lView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
button.setOnClickListener(this);
}
To:
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, lv_items);
lView.setAdapter(adapter);
That should fix the issue.
One other thing I noticed that will cause a crash is here:
public void ArraySubs() {
Bundle b = getIntent().getExtras();
String[] subChoices = b.getStringArray("selectedItems");
ListView lv = (ListView) findViewById(R.id.outputList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, subChoices);
lv.setAdapter(adapter);
};
You are trying to get the intent of the MainActivity, which won't contain the array. You will need to pass in the intent from the onActivityResult. It also would be a good idea to put it in a try/catch in case the extra doesn't exist.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ReqCode:
if (resultCode == RESULT_OK) {
ArraySubs(data);
break;
}
}
}
public void ArraySubs(Intent data) {
try{
Bundle b = data.getExtras();
String[] subChoices = b.getStringArray("selectedItems");
ListView lv = (ListView) findViewById(R.id.lv_list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, subChoices);
lv.setAdapter(adapter);
}
catch(Exception e){
Log.e("MainActivity", e.getMessage());
}
}
Im not too sure about your first problem but for the action bar try extending ActionBarActivity http://developer.android.com/reference/android/support/v7/app/ActionBarActivity.html
I get error with Intent. It says: intent is undefined. I've been searching a lot of other posts and it still doesn't work. Any ideas?
for your knowledge, i develop my own app with the basic of android developpes. Because my own intent didn't work, i used and created the exact same class as in the example, class DisplayMessageActivity but the problem remains the same, Here some of my code.
public class Main extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
catch(Exception e){
System.out.println("fout zit hier");
}
}
#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.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
}
Try replacing the first parameter on the Intent constructor.
Intent intent = new Intent(this, DisplayMessageActivity.class); // wrong
Intent intent = new Intent(getActivity(), DisplayMessageActivity.class); // right
The first parameter is a Context object, and remember that a Fragment does not inherit from Context, so the solution is getting the one from the parent Activity.
I have a Navigation Drawer in my App.I have the items in the drawer but I don't know how I can open new Activity from each of items .
I have Tried some Methods & Commented It ...
Thanks for your Help ...
MainActivity
public class MainActivity extends ActionBarActivity
{
private ListView mDrawerList;
protected DrawerLayout mDrawer;
private CustomActionBarDrawerToggle mDrawerToggle;
private String[] menuItems;
String LOG_TAG = "Remote It";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
supportRequestWindowFeature(WindowCompat.FEATURE_ACTION_BAR);
// getSupportActionBar().hide();
setContentView(R.layout.activity_main_drawer);
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
_initMenu();
mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawer);
mDrawer.setDrawerListener(mDrawerToggle);
// if (savedInstanceState == null)
// {
// selectItem(0);
// }
}
private void _initMenu()
{
NsMenuAdapter mAdapter = new NsMenuAdapter(this);
// Add Header
mAdapter.addHeader(R.string.ns_menu_main_header);
// Add first block
menuItems = getResources().getStringArray(R.array.ns_menu_items);
String[] menuItemsIcon = getResources().getStringArray(R.array.ns_menu_items_icon);
int res = 0;
for (String item : menuItems)
{
int id_title = getResources().getIdentifier(item, "string", this.getPackageName());
int id_icon = getResources().getIdentifier(menuItemsIcon[res], "drawable", this.getPackageName());
NsMenuItemModel mItem = new NsMenuItemModel(id_title, id_icon);
// if (res==1) mItem.counter=12; //it is just an example...
// if (res==3) mItem.counter=3; //it is just an example...
mAdapter.addItem(mItem);
res++;
}
mAdapter.addHeader(R.string.ns_menu_main_header2);
mDrawerList = (ListView) findViewById(R.id.drawer);
if (mDrawerList != null)
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
#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)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.control_menu, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
// If the nav drawer is open, hide action items related to the content
// view
boolean drawerOpen = mDrawer.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_keyboard).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
/*
* The action bar home/up should open or close the drawer.
* ActionBarDrawerToggle will take care of this.
*/
if (mDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
private class CustomActionBarDrawerToggle extends ActionBarDrawerToggle
{
public CustomActionBarDrawerToggle(Activity mActivity, DrawerLayout mDrawerLayout)
{
super(mActivity, mDrawerLayout, R.drawable.ic_drawer, R.string.ns_menu_open, R.string.ns_menu_close);
}
#Override
public void onDrawerClosed(View view)
{
getSupportActionBar().setTitle(getString(R.string.ns_menu_close));
supportInvalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView)
{
getSupportActionBar().setTitle(getString(R.string.ns_menu_open));
supportInvalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
}
//private void selectItem(int position)
//{
// switch (position)
// {
// case 1:
// Intent a = new Intent(MainActivity.this, ControlActivity.class);
// startActivity(a);
// break;
// case 2:
// Intent b = new Intent(MainActivity.this, Tutorial.class);
// startActivity(b);
// break;
// default:
// }
//}
private class DrawerItemClickListener implements ListView.OnItemClickListener
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
// Highlight the selected item, update the title, and close the
// drawer
// update selected item and title, then close the drawer
//mDrawerList.setItemChecked(position, true);
// String text = "menu click... should be implemented";
// Toast.makeText(MainActivity.this, text,
// Toast.LENGTH_LONG).show();
// // You should reset item counter
//mDrawer.closeDrawer(mDrawerList);
Intent intent = new Intent(MainActivity.this, Tutorial.class);
startActivity(intent);
}
}
}
NOTE
I need it to work with activities & not with Fragments .
If you want your NavigationDrawer in all your activities you can launch from the NavigationDrawer, the best way to handle that is not to launch new Activity, but to replace Fragment.
Because if you launch a new Activity each time you'll need to implement your NavigationDrawer in all your subactivities. (easily doable with heritage though).
There is a nice tutorial here to play with "replace" Fragments with the NavigationDrawer :
http://manishkpr.webheavens.com/android-navigation-drawer-example-using-fragments/