swipable menu on left - Java for Android App Development

hI THERE,
How can I in adroid have swipable menu on left..similar to gmail.. ( WHICH when you swipe gives you inbox below it social, promotions, primary then all labels below it starred important chats sent outbox) ..

http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/

one question.. android.support.v4 does this support honeycomb?
3.0 and above?

krikor1 said:
one question.. android.support.v4 does this support honeycomb?
3.0 and above?
Click to expand...
Click to collapse
http://developer.android.com/reference/android/support/v4/app/package-summary.html
Support android.app classes to assist with development of applications for android API level 4 or later. The main features here are backwards-compatible versions of FragmentManager and LoaderManager.
Click to expand...
Click to collapse
is that what you where asking for?

Implemented it, but what if i want it similar to right one... that is favorites... below it list of buttons..same for others..
http://www.androidhive.info/wp-content/uploads/2013/11/sliding-menu-example-applications.jpg

The implementation purely depends on you. You can inflate multiple list views.
Sent from my Micromax A116

coolbud012 said:
The implementation purely depends on you. You can inflate multiple list views.
Sent from my Micromax A116
Click to expand...
Click to collapse
how do u inflate multiple list views?
Code:
package com.netvariant.alkhaliji;
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class TabMenu extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList[B], mDrawerList2;[/B]
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems, [B]navDrawerItems2;[/B]
private NavDrawerListAdapter adapter,[B] adapter2;[/B]
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
[B]mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
mDrawerList2 = (ListView) findViewById(R.id.list_menuslider);[/B]
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
[B]navDrawerItems2.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems2.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems2.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// Pages
navDrawerItems2.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems2.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));[/B]
// Recycle the typed array
navMenuIcons.recycle();
[B]mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
mDrawerList2.setOnItemClickListener(new SlideMenuClickListener());[/B]
// setting the nav drawer list adapter
[B]adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems2);
mDrawerList.setAdapter(adapter);
mDrawerList2.setAdapter(adapter2);[/B]
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
[B] // if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
boolean drawerOpen2 = mDrawerLayout.isDrawerOpen(mDrawerList2);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen2);
return super.onPrepareOptionsMenu(menu);[/B]
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new FindPeopleFragment();
break;
case 2:
fragment = new PhotosFragment();
break;
case 3:
fragment = new CommunityFragment();
break;
case 4:
fragment = new PagesFragment();
break;
case 5:
fragment = new WhatsHotFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
[B]// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
mDrawerList2.setItemChecked(position, true);
mDrawerList2.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
mDrawerLayout.closeDrawer(mDrawerList2);[/B]
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
@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);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
modified bolded parts, and i get error
also in xml i added this
Code:
<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">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Listview to display slider menu -->
<ListView
android:id="@+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@color/list_divider"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_selector"
android:background="@color/list_background"/>
[B] <ListView
android:id="@+id/list_menuslider"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@color/list_divider"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_selector"
android:background="@color/list_background"/>[/B]
</android.support.v4.widget.DrawerLayout>
two listviews...instead of one..as i want it subsections...

Related

Text input with DialogFragment

I am trying to get a value that user enters into a Dialog, using the recommended DialogFragment class for it, the Dialog constructs and runs fine, but I cannot return the value of the EditText parameter to the parent class, without get a Null pointer exception.
My DialogHost class, this constructs, returns and links the parent to its buttons.
Code:
package jo.app.co;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
public class DialogHost extends DialogFragment {
public interface NoticeDialogListener {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
NoticeDialogListener mListener;
[user=439709]@override[/user]
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (NoticeDialogListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString());
}
}
[user=439709]@override[/user]
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.dialog_add, null))
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
[user=439709]@override[/user]
public void onClick(DialogInterface dialog, int id) {
mListener.onDialogPositiveClick(DialogHost.this);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
DialogHost.this.getDialog().cancel();
}
});
return builder.create();
}
}
My MainActivity
Code:
package jo.app.co;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.EditText;
public class MainActivity extends FragmentActivity implements DialogHost.NoticeDialogListener {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showNoticeDialog();
}
public void showNoticeDialog() {
DialogFragment dialog = new DialogHost();
dialog.show(getFragmentManager(), "DialogHost");
}
[user=439709]@override[/user]
public void onDialogPositiveClick(DialogFragment dialog) {
EditText myText = (EditText) findViewById(R.id.item_added);
try {
Log.d ("IN TRY", myText.getText().toString());
}
catch (Exception e) {
Log.e ("IN CATCH", e.toString());
}
}
[user=439709]@override[/user]
public void onDialogNegativeClick(DialogFragment dialog) {
Log.d ("INMAIN", "REACHED NEG");
}
}
This is my layout for the add item dialog.
Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:id="@+id/item_added"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:hint="@string/hint_add_item" />
</LinearLayout>
It's because in your main activity you are trying to call findViewById:
swapnilraj said:
Code:
[user=439709]@override[/user]
public void onDialogPositiveClick(DialogFragment dialog) {
EditText myText = (EditText) findViewById(R.id.item_added);
try {
Log.d ("IN TRY", myText.getText().toString());
}
catch (Exception e) {
Log.e ("IN CATCH", e.toString());
}
}
Click to expand...
Click to collapse
This is not possible since the layout of the activity is not the one the dialog is using. There are multiple ways of doing this, for instance call findViewById in the dialog's onPositiveButtonListener and pass that value through your interface. It might be that you need to use the LayoutInflator in the onCreateDialog, set
LinearLayout linearl = (LinearLayout) inflater.inflate(...) and get the EditText from there. You then call setView(linearL) instead.
SimplicityApks said:
It's because in your main activity you are trying to call findViewById:
This is not possible since the layout of the activity is not the one the dialog is using. There are multiple ways of doing this, for instance call findViewById in the dialog's onPositiveButtonListener and pass that value through your interface. It might be that you need to use the LayoutInflator in the onCreateDialog, set
LinearLayout linearl = (LinearLayout) inflater.inflate(...) and get the EditText from there. You then call setView(linearL) instead.
Click to expand...
Click to collapse
I tried calling findViewById method in the onClick method in the Dialog class, but the function is not defined for a DialogInterface.onClickListner, I modified it to linearl method you told but I cannot get it to work either.
Could you make the changes in the 2 snippets above, it would be very helpful!
You'll have to setup listeners fo this and pass the string or whetever you want to pass to back to the activity which in its turn can handle it (do it by itself or pass this to another fragement).
Although not so much votes (0) the last answer here on stackoverflow has exeactly what you need.

[Q] How to add function to toggle switches?

I am pretty new to coding and app development. After searching around this is an easy thing to do. But I'm so stupid I can figure it out.
So what I need is to add a hardware function to a toggle switch. If you know how to add function to it. What I need is to send all audio through the earpiece when the toggle switch is on. Can you please put the whole code I need to do this? Please help me out!
Makbrar3215 said:
I am pretty new to coding and app development. After searching around this is an easy thing to do. But I'm so stupid I can figure it out.
So what I need is to add a hardware function to a toggle switch. If you know how to add function to it. What I need is to send all audio through the earpiece when the toggle switch is on. Can you please put the whole code I need to do this? Please help me out!
Click to expand...
Click to collapse
After you define your toggle switch in your xml, you can add a id and then you can
Code:
android:onClick="onSwitchClicked"
anywhere between the toggle block. This will say what to do when the toggle is clicked. Now put the below method in your class to control the toggle status:
Code:
public void onSwitchClicked(View view) {
switch(view.getId()){
case R.id.switch1:
if(switch1.isChecked()) {
// To do when 1st switch is on
}
else {
//To do when 1st switch is off
}
break;
case R.id.switch2:
if(switch2.isChecked()) {
//To do when 2nd switch is on
}
else {
//To do when 2nd switch is off
}
break;
}
}
You can extended to as many switches you want by providing different id's for the switch in xml and controlling that with case statements in the java.
And for controlling the audio, You can use audiomanager class
Code:
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.setSpeakerphoneOn(true); //sets audio via speaker
am.setWiredHeadsetOn(true); //sets audio via headset
Problem!
vijai2011 said:
After you define your toggle switch in your xml, you can add a id and then you can
Code:
android:onClick="onSwitchClicked"
anywhere between the toggle block. This will say what to do when the toggle is clicked. Now put the below method in your class to control the toggle status:
Code:
public void onSwitchClicked(View view) {
switch(view.getId()){
case R.id.switch1:
if(switch1.isChecked()) {
// To do when 1st switch is on
}
else {
//To do when 1st switch is off
}
break;
case R.id.switch2:
if(switch2.isChecked()) {
//To do when 2nd switch is on
}
else {
//To do when 2nd switch is off
}
break;
}
}
You can extended to as many switches you want by providing different id's for the switch in xml and controlling that with case statements in the java.
And for controlling the audio, You can use audiomanager class
Code:
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.setSpeakerphoneOn(true); //sets audio via speaker
am.setWiredHeadsetOn(true); //sets audio via headset
Click to expand...
Click to collapse
I did what you said. Yet I encountered a problem. Please see the attached screenshot.
When I hover over the X it says "Attribute name "public" associated with an element type "RadioButton" must be followed by the ' = '
character."
Where do I put the "="
Thanks by the way. You helped me out a lot!
you are mixing java with XML. Honestly, I suggest you start on a few beginner tutorials.
Just tell me what to do. I can't go through the guide. I need this app done by August 14.
Sent from my SGH-I337M using xda app-developers app
Bad Attitude to have. This isn't a "do my work for me" forum.
And like zalez was kind enough to point out, your putting java in xml. If you expect to make an app you need to read some beginner guides first.
you have almost a month to do it.
Thanks, I didn't mean to be rude. Where can I find the guide? :thumbup:
Sent from my SGH-I337M using xda app-developers app
Makbrar3215 said:
Thanks, I didn't mean to be rude. Where can I find the guide? :thumbup:
Sent from my SGH-I337M using xda app-developers app
Click to expand...
Click to collapse
http://developer.android.com/training/index.html
But you should probably start with generic Java 101 stuff
Set Switch status from incoming JSON data
Sorry to bump this thread after such a long time but I am facing a problem with switches myself and would appreciate some help. I have a JSON parser class which is retrieving data from a database. The retrieved info contains 'ID', 'name' and 'status' fields related to a device. I can display ID and name of each of the devices (there are several rows) using a listview but I don't know how to use the 'status' field value (it is either 1 or 0) to set an associated Switch component. I have to set the Switch associated with each listview item to ON if incoming 'status' value is 1 and set it OFF if 'status' is 0. I am lost on where to put the 'setChecked' method for every listview item. Here's the code of activity that shows these list items:
Code:
package com.iotautomationtech.androidapp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.widget.ToggleButton;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.TextView;
public class AllDevicesActivity extends ListActivity {
Switch mySwitch = (Switch) findViewById(R.id.switchButton);
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "external_link_removed";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "devices";
private static final String TAG_PID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_STATUS = "status";
// products JSONArray
JSONArray products = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_devices);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditDeviceActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllDevicesActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String status = c.getString(TAG_STATUS);
int toggleValue = Integer.parseInt(c.getString(TAG_STATUS));
boolean sBool = false;
if (toggleValue == 1) {
sBool = true;
}
if (status.equals("1")) {
status = "Status: ON";
}
else {
status = "Status: OFF";
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_STATUS, status);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewDeviceActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllDevicesActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME, TAG_STATUS},
new int[] { R.id.pid, R.id.name, R.id.status });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
The XML file:
Code:
<RelativeLayout xmlns:android="schemas.android"
android:layout_width="fill_parent"
android:layout_height="65dip"
android:orientation="vertical"
android:layout_centerVertical="true"
>
<!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
<TextView
android:id="@+id/pid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17dip"
android:textStyle="bold" />
<TextView
android:id="@+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="6dip"
android:textSize="17dip"
android:layout_below="@+id/name"
/>
<Switch
android:id="@+id/switchButton"
android:layout_alignParentRight="true"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:layout_marginRight="6dip"
android:layout_centerVertical="true"
android:textOff="OFF"
android:textOn="ON"
android:onClick="onSwitchClicked"
/>
</RelativeLayout>
I have reached thus far with the code: [attached-image]
Now I only have to set those Switches according to status values from database. I have tried putting the setChecked in doInBackground method and onPostExecute method but it doesn't work. Do I have to save all status values in an array and start a loop to set all Switches? Where would that code go?
ANY kind of help/guidance here is appreciated!

[Q] Code not bringing desired results

good day,
i'm trying to create an app that will create options in a listview on an an activity based on the option a user selects in the previous activity
below is the code i came up with but it doesn't work.
please what am i doing wrong?
thanks in advance
package com.inveniotech.moneyventure;
/**
* Created by BolorunduroWB on 9/3/13.
*/
import android.os.Bundle;
import android.app.Activity;
import android.view.*;
import android.widget.*;
import java.util.*;
import android.content.Intent;
public class menu_options extends Activity {
SimpleAdapter simpleAdpt;
Intent intent = getIntent();
public String message = intent.getStringExtra(football.EXTRA_MESSAGE);
String[] menuList;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menuoptionsview);
initList();
// We get the ListView component from the layout
ListView lv = (ListView) findViewById(R.id.listView);
// This is a simple adapter that accepts as parameter
// Context
// Data list
// The row layout that is used during the row creation
// The keys used to retrieve the data
// The View id used to show the data. The key number and the view id must match
simpleAdpt = new SimpleAdapter(this, optionList, android.R.layout.simple_list_item_1, new String[] {"options"}, new int[] {android.R.id.text1});
lv.setAdapter(simpleAdpt);
// React to user clicks on item
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position, long id) {
// We know the View is a TextView so we can cast it
TextView clickedView = (TextView) view;
Toast.makeText(menu_options.this, "Item with id ["+id+"] - Position ["+position+"] - Planet ["+clickedView.getText()+"]", Toast.LENGTH_SHORT).show();
}
});
}
@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;
}
// The data to show
List<Map<String, String>> optionList = new ArrayList<Map<String,String>>();
private void initList() {
// We populate the planets
if (message.equals("5")){
menuList = new String[]{"News", "Fixtures","Results","Standings"," "};
}
else if (message.equals("6")){
menuList = new String[]{"News", "Tables"," "," "," "};
}
else if (message.equals("7")){
menuList = new String[]{"Done Deals", "Rumours","Latest News","Live","Transfer Centre"};
}
else {
menuList = new String[] {"News","Teams","Fixtures","Results","Table"};
}
optionList.add(createOptions("options", menuList[0]));
optionList.add(createOptions("options", menuList[1]));
optionList.add(createOptions("options", menuList[2]));
optionList.add(createOptions("options", menuList[3]));
optionList.add(createOptions("options", menuList[4]));
}
private HashMap<String, String> createOptions(String key, String name) {
HashMap<String, String> options = new HashMap<String, String>();
options.put(key, name);
return options;
}
}
Read This guide first, then it's easier to help you.
What I'm seeing is that you should set your message=getIntent ().... ; in the onCreate since the Intent data is probably not available before.
SimplicityApks said:
Read This guide first, then it's easier to help you.
What I'm seeing is that you should set your message=getIntent ().... ; in the onCreate since the Intent data is probably not available before.
Click to expand...
Click to collapse
Thank you. Wanted to post the link, too. :laugh:

How to use Navigation Drawer inside Tabs menu.

Hi guys.
I've been developing an app which has Swipeable menu in bottom and one of the pages , should have a Navigation Drawer to change its own Fragments.
MainActivity.java
Code:
package com.example.elizehprotowithshlkandvpis;
import com.example.elizehprotowithshlkandvpis.adapter.MainMenuAdapter;
import com.viewpagerindicator.TabPageIndicator;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
private static final String[] CONTENT = { "Home", "AboutUs", "Maps", "Resturants", "Tours", "CustomerClub", "Neccesseries", "UrgentCall" };
private ViewPager mViewPager;
private FragmentPagerAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new MainMenuAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator) findViewById(R.id.indicator);
indicator.setViewPager(mViewPager);
}
@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;
}
public static String[] getCONTENT() {
return CONTENT;
}
}
MainMenuAdapter.java
Code:
package com.example.elizehprotowithshlkandvpis.adapter;
import com.example.elizehprotowithshlkandvpis.MainActivity;
import com.example.menuclasses.AboutUs;
import com.example.menuclasses.CustomerClub;
import com.example.menuclasses.Maps;
import com.example.menuclasses.Neccesseries;
import com.example.menuclasses.Tours;
import com.example.menuclasses.UrgentCall;
import com.example.menuclasses.Resturants;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MainMenuAdapter extends FragmentPagerAdapter {
private static final String[] CONTENT = { "Home", "AboutUs", "Maps", "Resturants", "Tours", "CustomerClub", "Neccesseries", "UrgentCall" };
private final int HOME_INDEX = 0;
private final int ABOUTUS_INDEX = 1;
private final int MAPS_INDEX = 2;
private final int RESTURANTS_INDEX = 3;
private final int TOURS_INDEX = 4;
private final int CUSTOMERCLUB_INDEX = 5;
private final int NECCESSERIES_INDEX = 6;
private final int URGENTCALL_INDEX = 7;
private final int NUMBEROFMENUS = CONTENT.length;
public MainMenuAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
@Override
public CharSequence getPageTitle(int position) {
String[] CONTENT = MainActivity.getCONTENT();
return CONTENT[position % CONTENT.length].toUpperCase();
}
@Override
public Fragment getItem(int index) {
switch(index) {
case HOME_INDEX:
return new AboutUs();
case ABOUTUS_INDEX:
return new AboutUs();
case MAPS_INDEX:
return new Maps();
case RESTURANTS_INDEX:
return new Resturants();
case TOURS_INDEX:
return new Tours();
case CUSTOMERCLUB_INDEX:
return new CustomerClub();
case NECCESSERIES_INDEX:
return new Neccesseries();
case URGENTCALL_INDEX:
return new UrgentCall();
}
return null;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return NUMBEROFMENUS;
}
}
The Fragment that should contain a Navigation Drawer is Resturants , also drawer's mainactivity is implemented with Sherlock Library(SherlockFragmentActivity).
I'm puzzled how to call the SherlockFragmentActivity from the SherlockActivity
Thanks
Pouya_am said:
Hi guys.
I've been developing an app which has Swipeable menu in bottom and one of the pages , should have a Navigation Drawer to change its own Fragments.
MainActivity.java
Code:
package com.example.elizehprotowithshlkandvpis;
import com.example.elizehprotowithshlkandvpis.adapter.MainMenuAdapter;
import com.viewpagerindicator.TabPageIndicator;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
private static final String[] CONTENT = { "Home", "AboutUs", "Maps", "Resturants", "Tours", "CustomerClub", "Neccesseries", "UrgentCall" };
private ViewPager mViewPager;
private FragmentPagerAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new MainMenuAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator) findViewById(R.id.indicator);
indicator.setViewPager(mViewPager);
}
@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;
}
public static String[] getCONTENT() {
return CONTENT;
}
}
MainMenuAdapter.java
Code:
package com.example.elizehprotowithshlkandvpis.adapter;
import com.example.elizehprotowithshlkandvpis.MainActivity;
import com.example.menuclasses.AboutUs;
import com.example.menuclasses.CustomerClub;
import com.example.menuclasses.Maps;
import com.example.menuclasses.Neccesseries;
import com.example.menuclasses.Tours;
import com.example.menuclasses.UrgentCall;
import com.example.menuclasses.Resturants;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MainMenuAdapter extends FragmentPagerAdapter {
private static final String[] CONTENT = { "Home", "AboutUs", "Maps", "Resturants", "Tours", "CustomerClub", "Neccesseries", "UrgentCall" };
private final int HOME_INDEX = 0;
private final int ABOUTUS_INDEX = 1;
private final int MAPS_INDEX = 2;
private final int RESTURANTS_INDEX = 3;
private final int TOURS_INDEX = 4;
private final int CUSTOMERCLUB_INDEX = 5;
private final int NECCESSERIES_INDEX = 6;
private final int URGENTCALL_INDEX = 7;
private final int NUMBEROFMENUS = CONTENT.length;
public MainMenuAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
@Override
public CharSequence getPageTitle(int position) {
String[] CONTENT = MainActivity.getCONTENT();
return CONTENT[position % CONTENT.length].toUpperCase();
}
@Override
public Fragment getItem(int index) {
switch(index) {
case HOME_INDEX:
return new AboutUs();
case ABOUTUS_INDEX:
return new AboutUs();
case MAPS_INDEX:
return new Maps();
case RESTURANTS_INDEX:
return new Resturants();
case TOURS_INDEX:
return new Tours();
case CUSTOMERCLUB_INDEX:
return new CustomerClub();
case NECCESSERIES_INDEX:
return new Neccesseries();
case URGENTCALL_INDEX:
return new UrgentCall();
}
return null;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return NUMBEROFMENUS;
}
}
The Fragment that should contain a Navigation Drawer is Resturants , also drawer's mainactivity is implemented with Sherlock Library(SherlockFragmentActivity).
I'm puzzled how to call the SherlockFragmentActivity from the SherlockActivity
Thanks
Click to expand...
Click to collapse
That last sentence does not make sense I assume you mean from the Fragment?! Well to access the holding activity you need to add an interface to the Fragment which the activity will implement.
Am I understanding you correctly that have a horizontal ViewPager and one of the Fragments should have a Navigation drawer? To accomplish that you would still need the whole activity to hold the drawer and figure out a way to disable it when the user is on some other Fragment. But my question is why you want to use a navigation drawer in that case, because the drawer is meant for navigating on the same hierarchical level, but the different items are more independent than with the ViewPager. It doesn't really make sense to have both a drawer and horizontal swiping, even the YouTube app really bothers me with its swiping between suggestions and feed. I think what you need to use here is a spinner in the ActionBar, replacing the title of the Fragment.
SimplicityApks said:
That last sentence does not make sense I assume you mean from the Fragment?! Well to access the holding activity you need to add an interface to the Fragment which the activity will implement.
Am I understanding you correctly that have a horizontal ViewPager and one of the Fragments should have a Navigation drawer? To accomplish that you would still need the whole activity to hold the drawer and figure out a way to disable it when the user is on some other Fragment. But my question is why you want to use a navigation drawer in that case, because the drawer is meant for navigating on the same hierarchical level, but the different items are more independent than with the ViewPager. It doesn't really make sense to have both a drawer and horizontal swiping, even the YouTube app really bothers me with its swiping between suggestions and feed. I think what you need to use here is a spinner in the ActionBar, replacing the title of the Fragment.
Click to expand...
Click to collapse
Yeah you're right , I just want to use the drawer in order to change contents.
So as you suggest , I just have to use a simple tricks to make the drawer enable in desire Fragment.
I don't want to , I am asked to make it possible....

menu slider with multiple lists

Code:
package com.netvariant.alkhaliji;
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class TabMenu extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList, mDrawerList2;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems,navDrawerItems2;
private NavDrawerListAdapter adapter, adapter2;
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
mDrawerList2 = (ListView) findViewById(R.id.list_menuslider);
navDrawerItems = new ArrayList<NavDrawerItem>();
navDrawerItems2 = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems2.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems2.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// Pages
navDrawerItems2.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems2.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
mDrawerList2.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
adapter2 = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems2);
mDrawerList.setAdapter(adapter);
mDrawerList2.setAdapter(adapter2);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
boolean drawerOpen2 = mDrawerLayout.isDrawerOpen(mDrawerList2);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen2);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new FindPeopleFragment();
break;
case 2:
fragment = new PhotosFragment();
break;
case 3:
fragment = new CommunityFragment();
break;
case 4:
fragment = new PagesFragment();
break;
case 5:
fragment = new WhatsHotFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
// mDrawerList2.setItemChecked(position, true);
// mDrawerList2.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
// mDrawerLayout.closeDrawer(mDrawerList2);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
@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);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
Code:
<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">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Listview to display slider menu -->
<ListView
android:id="@+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@color/list_divider"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_selector"
android:background="@color/list_background"/>
<ListView
android:id="@+id/list_menuslider"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@color/list_divider"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_selector"
android:background="@color/list_background"/>
</android.support.v4.widget.DrawerLayout>
my 2nd list is not showing...any help?

Categories

Resources