menu slider with multiple lists - Java for Android App Development

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?

Related

[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:

[Q]Put view over status bar

I want to put a View over the status bar, the code work right, but I get a RunTime Error.
Code:
//Declared in the Activity
WindowManager wm;
LinearLayout ll;
WindowManager.LayoutParams ll_lp;
//Just a sample layout parameters.
ll_lp = new WindowManager.LayoutParams();
ll_lp.format = PixelFormat.TRANSLUCENT;
ll_lp.height = WindowManager.LayoutParams.FILL_PARENT;
ll_lp.width = WindowManager.LayoutParams.FILL_PARENT;
ll_lp.gravity = Gravity.CLIP_HORIZONTAL | Gravity.TOP;
//This one is necessary.
ll_lp.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
//Play around with these two.
ll_lp.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
ll_lp.flags = ll_lp.flags | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
//This is our main layout.
ll = new LinearLayout(LockScreenAppActivity.this);
ll.setBackgroundColor(android.graphics.Color.argb(0, 0, 0, 0));
ll.setHapticFeedbackEnabled(true);
try {
//And finally we add what we created to the screen.
wm.addView(ll, ll_lp);
} catch (Exception e) {
//I GET THE ERROR HERE
Log.e("Error", "Fail");
e.printStackTrace();
e.getMessage();
}
Code:
LOG:
11-29 23:38:38.109: W/System.err(6462): java.lang.NullPointerException
11-29 23:38:38.117: W/System.err(6462): at com.advanced.locker.LockScreenAppActivity.onCreate(LockScreenAppActivity.java:77)
11-29 23:38:38.117: W/System.err(6462): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-29 23:38:38.117: W/System.err(6462): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
11-29 23:38:38.117: W/System.err(6462): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
11-29 23:38:38.117: W/System.err(6462): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
11-29 23:38:38.117: W/System.err(6462): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
11-29 23:38:38.125: W/System.err(6462): at android.os.Handler.dispatchMessage(Handler.java:99)
11-29 23:38:38.125: W/System.err(6462): at android.os.Looper.loop(Looper.java:130)
11-29 23:38:38.125: W/System.err(6462): at android.app.ActivityThread.main(ActivityThread.java:3687)
11-29 23:38:38.125: W/System.err(6462): at java.lang.reflect.Method.invokeNative(Native Method)
11-29 23:38:38.125: W/System.err(6462): at java.lang.reflect.Method.invoke(Method.java:507)
11-29 23:38:38.125: W/System.err(6462): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
11-29 23:38:38.125: W/System.err(6462): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
11-29 23:38:38.125: W/System.err(6462): at dalvik.system.NativeStart.main(Native Method)
11-29 23:45:55.953: E/Error(6884): Fail
11-29 23:55:39.070: W/IInputConnectionWrapper(6884): showStatusIcon on inactive InputConnection
11-29 23:55:53.226: E/Error(7053): Fail
Can anybody help me?
Lot's of thank's!
Don't know whether you idea is possible, but please DO NOT code an empty catch part. Something like e.printStackTrace() and e.getMessage() AT LEAST.
Regards
EmptinessFiller said:
Don't know whether you idea is possible, but please DO NOT code an empty catch part. Something like e.printStackTrace() and e.getMessage() AT LEAST.
Regards
Click to expand...
Click to collapse
Is Correct NOW?
Thank's
It might be correct, but senseless, because you never see e.getMessage(). So u could use Log.e(TAG, e.getMessage()).
But by the way, it'd be great if you'd post your log here and before read it.
Regards
EmptinessFiller said:
It might be correct, but senseless, because you never see e.getMessage(). So u could use Log.e(TAG, e.getMessage()).
But by the way, it'd be great if you'd post your log here and before read it.
Regards
Click to expand...
Click to collapse
Now, i think is fine
Come on please, it's easy, but for me no...
Enviado desde mi GT-S5570I usando Tapatalk 2
You define a variable of type WindowManager but you never assign any object to it.
Add this before the try:
Code:
wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
nikwen said:
You define a variable of type WindowManager but you never assign any object to it.
Add this before the try:
Code:
wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Click to expand...
Click to collapse
Lot's of Thank's friend!
Do you think that I put a view over status bar with it??
Enviado desde mi GT-S5570I usando Tapatalk 2
nikwen said:
You define a variable of type WindowManager but you never assign any object to it.
Add this before the try:
Code:
wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Click to expand...
Click to collapse
Your code works fine, but i can get what i want...
I need something like this:
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
(Red square)
But my view is under the status bar.
Can u help me?
Thank's in advance!
Enviado desde mi GT-S5570I usando Tapatalk 2
DannyGM16 said:
Your code works fine, but i can get what i want...
I need something like this:
(Red square)
But my view is under the status bar.
Can u help me?
Thank's in advance!
Enviado desde mi GT-S5570I usando Tapatalk 2
Click to expand...
Click to collapse
Maybe you can find some hints in the code of the RoundR app which does actually do what you want to achieve: https://github.com/MohammadAdib/Roundr
nikwen said:
Maybe you can find some hints in the code of the RoundR app which does actually do what you want to achieve: https://github.com/MohammadAdib/Roundr
Click to expand...
Click to collapse
I don't find the code that I need, Help me please.
This is the code:
MainActivity.java:
Code:
package mohammad.adib.roundr;
/**
* Copyright 2013 Mohammad Adib
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
import wei.mark.standout.StandOutWindow;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class MainActivity extends Activity {
/**
* Main Activity that launches the 4 floating windows (corners)
*
* @author Mohammad Adib <[email protected]>
*
* Contributors: Mark Wei
*
*/
ProgressDialog progress;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (!BootReceiver.boot_up || Corner.running) {
Intent i = new Intent(this, SettingsActivity.class);
startActivity(i);
}
if (prefs.getBoolean("enable", true)) {
StandOutWindow.show(this, Corner.class, 0);
StandOutWindow.show(this, Corner.class, 1);
StandOutWindow.show(this, Corner.class, 2);
StandOutWindow.show(this, Corner.class, 3);
}
finish();
}
}
Corner.java:
Code:
package mohammad.adib.roundr;
/**
* Copyright 2013 Mohammad Adib
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
import wei.mark.standout.StandOutWindow;
import wei.mark.standout.constants.StandOutFlags;
import wei.mark.standout.ui.Window;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RemoteViews;
public class Corner extends StandOutWindow {
/**
* The individual floating window that sits at one of the corners of the
* screen. Window ID corresponds to which corner this goes to.
*
* @author Mohammad Adib <[email protected]>
*
* Contributors: Mark Wei, Jan Metten
*
*/
public static final String ACTION_SETTINGS = "SETTINGS";
public static final String BCAST_CONFIGCHANGED = "android.intent.action.CONFIGURATION_CHANGED";
public static final int UPDATE_CODE = 2;
public static final int NOTIFICATION_CODE = 3;
public static final int wildcard = 0;
private SharedPreferences prefs;
public static boolean running = false;
@Override
public String getAppName() {
return "RoundR";
}
@Override
public int getAppIcon() {
return R.drawable.notif_icon;
}
@Override
public void createAndAttachView(int corner, FrameLayout frame) {
// Set the image based on window corner
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
ImageView v = (ImageView) inflater.inflate(R.layout.corner, frame, true).findViewById(R.id.iv);
// Top left by default
v.setImageDrawable(getResources().getDrawable(R.drawable.topleft));
switch (corner) {
case 1:
v.setImageDrawable(getResources().getDrawable(R.drawable.topright));
break;
case 2:
v.setImageDrawable(getResources().getDrawable(R.drawable.bottomleft));
break;
case 3:
v.setImageDrawable(getResources().getDrawable(R.drawable.bottomright));
break;
}
}
private int pxFromDp(double dp) {
return (int) (dp * getResources().getDisplayMetrics().density);
}
/**
* Corners: 0 = top left; 1 = top right; 2 = bottom left; 3 = bottom right;
*/
@Override
public StandOutLayoutParams getParams(int corner, Window window) {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
// Check if this corner is enabled
if (prefs.getBoolean("corner" + corner, true)) {
int radius = pxFromDp(prefs.getInt("radius", 20));
// Thanks to Jan Metten for rewriting this based on gravity
switch (corner) {
case 0:
return new StandOutLayoutParams(corner, radius, radius, Gravity.TOP | Gravity.LEFT);
case 1:
return new StandOutLayoutParams(corner, radius, radius, Gravity.TOP | Gravity.RIGHT);
case 2:
return new StandOutLayoutParams(corner, radius, radius, Gravity.BOTTOM | Gravity.LEFT);
case 3:
return new StandOutLayoutParams(corner, radius, radius, Gravity.BOTTOM | Gravity.RIGHT);
}
}
// Outside of screen
return new StandOutLayoutParams(corner, 1, 1, -1, -1, 1, 1);
}
@Override
public int getFlags(int corner) {
return super.getFlags(corner) | StandOutFlags.FLAG_WINDOW_FOCUSABLE_DISABLE | StandOutFlags.FLAG_WINDOW_EDGE_LIMITS_ENABLE;
}
@Override
public String getPersistentNotificationMessage(int corner) {
return "Tap to configure";
}
@Override
public Intent getPersistentNotificationIntent(int corner) {
return new Intent(this, Corner.class).putExtra("id", corner).setAction(ACTION_SETTINGS);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String action = intent.getAction();
int corner = intent.getIntExtra("id", DEFAULT_ID);
if (corner == ONGOING_NOTIFICATION_ID) {
throw new RuntimeException("ID cannot equals StandOutWindow.ONGOING_NOTIFICATION_ID");
}
if (ACTION_SHOW.equals(action) || ACTION_RESTORE.equals(action)) {
show(corner);
} else if (ACTION_SETTINGS.equals(action)) {
try {
Intent intentS = new Intent(this, SettingsActivity.class);
intentS.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intentS);
} catch (Exception e) {
// Addressing this issue: http://i.imgur.com/Op9kfy8.png
}
} else if (ACTION_HIDE.equals(action)) {
hide(corner);
} else if (ACTION_CLOSE.equals(action)) {
close(corner);
} else if (ACTION_CLOSE_ALL.equals(action)) {
closeAll();
} else if (ACTION_SEND_DATA.equals(action)) {
if (isExistingId(corner) || corner == DISREGARD_ID) {
Bundle data = intent.getBundleExtra("wei.mark.standout.data");
int requestCode = intent.getIntExtra("requestCode", 0);
@SuppressWarnings("unchecked")
Class<? extends StandOutWindow> fromCls = (Class<? extends StandOutWindow>) intent.getSerializableExtra("wei.mark.standout.fromCls");
int fromId = intent.getIntExtra("fromId", DEFAULT_ID);
onReceiveData(corner, requestCode, data, fromCls, fromId);
}
}
}
return START_NOT_STICKY;
}
@Override
public boolean onClose(final int corner, final Window window) {
running = false;
return false;
}
@Override
public String getPersistentNotificationTitle(int corner) {
return "Rounded Corners";
}
@SuppressLint({ "InlinedApi", "NewApi" })
@SuppressWarnings("deprecation")
@Override
public Notification getPersistentNotification(int id) {
int icon = getAppIcon();
long when = System.currentTimeMillis();
Context c = getApplicationContext();
String contentTitle = getPersistentNotificationTitle(id);
String contentText = getPersistentNotificationMessage(id);
Intent notificationIntent = getPersistentNotificationIntent(id);
PendingIntent contentIntent = PendingIntent.getService(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// 4.1+ Low priority notification
final int apiLevel = Build.VERSION.SDK_INT;
if (apiLevel >= 16) {
Notification.Builder mBuilder = new Notification.Builder(this).setContent(new RemoteViews(getPackageName(), R.layout.notification)).setSmallIcon(getAppIcon()).setContentTitle(contentTitle).setContentText(contentText).setPriority(Notification.PRIORITY_MIN).setContentIntent(contentIntent);
return mBuilder.build();
}
String tickerText = String.format("%s: %s", contentTitle, contentText);
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(c, contentTitle, contentText, contentIntent);
return notification;
}
@Override
public boolean onShow(final int corner, final Window window) {
running = true;
return false;
}
@Override
public void onReceiveData(int corner, int requestCode, Bundle data, Class<? extends StandOutWindow> fromCls, int fromId) {
Window window = getWindow(corner);
if (requestCode == UPDATE_CODE) {
// Update the corners when device is rotated
updateViewLayout(3, getParams(3, window));
updateViewLayout(2, getParams(2, window));
updateViewLayout(1, getParams(1, window));
updateViewLayout(0, getParams(0, window));
} else if (requestCode == NOTIFICATION_CODE) {
if (!prefs.getBoolean("notification", true)) {
// Hide Notification Icon (for <= Gingerbread devices only)
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = getPersistentNotification(corner);
notification.icon = wei.mark.standout.R.drawable.nothing;
mNotificationManager.notify(getClass().hashCode() + ONGOING_NOTIFICATION_ID, notification);
Log.d("Hello World", "");
} else {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = getPersistentNotification(corner);
mNotificationManager.notify(getClass().hashCode() + ONGOING_NOTIFICATION_ID, notification);
}
}
}
}
SeekBarPreference:
Code:
package mohammad.adib.roundr;
import wei.mark.standout.StandOutWindow;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.preference.Preference;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class SeekBarPreference extends Preference implements OnSeekBarChangeListener {
private final String TAG = getClass().getName();
private static final String ANDROIDNS = "http://schemas.android.com/apk/res/android";
private static final String ROUNDRNS = "roundrprefs";
private static final int DEFAULT_VALUE = 50;
private int mMaxValue = 100;
private int mMinValue = 0;
private int mInterval = 1;
private int mCurrentValue;
private String mUnitsLeft = "";
private String mUnitsRight = "";
private SeekBar mSeekBar;
private Context context;
private TextView mStatusText;
public SeekBarPreference(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
initPreference(context, attrs);
}
public SeekBarPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initPreference(context, attrs);
}
private void initPreference(Context context, AttributeSet attrs) {
setValuesFromXml(attrs);
mSeekBar = new SeekBar(context, attrs);
mSeekBar.setMax(mMaxValue - mMinValue);
mSeekBar.setOnSeekBarChangeListener(this);
}
private void setValuesFromXml(AttributeSet attrs) {
mMaxValue = attrs.getAttributeIntValue(ANDROIDNS, "max", 100);
mMinValue = attrs.getAttributeIntValue(ROUNDRNS, "min", 0);
mUnitsLeft = getAttributeStringValue(attrs, ROUNDRNS, "unitsLeft", "");
String units = getAttributeStringValue(attrs, ROUNDRNS, "units", "");
mUnitsRight = getAttributeStringValue(attrs, ROUNDRNS, "unitsRight", units);
try {
String newInterval = attrs.getAttributeValue(ROUNDRNS, "interval");
if (newInterval != null)
mInterval = Integer.parseInt(newInterval);
} catch (Exception e) {
Log.e(TAG, "Invalid interval value", e);
}
}
private String getAttributeStringValue(AttributeSet attrs, String namespace, String name, String defaultValue) {
String value = attrs.getAttributeValue(namespace, name);
if (value == null)
value = defaultValue;
return value;
}
@Override
protected View onCreateView(ViewGroup parent) {
RelativeLayout layout = null;
try {
LayoutInflater mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = (RelativeLayout) mInflater.inflate(R.layout.seek_bar_preference, parent, false);
} catch (Exception e) {
Log.e(TAG, "Error creating seek bar preference", e);
}
return layout;
}
@Override
public void onBindView(View view) {
super.onBindView(view);
try {
// move our seekbar to the new view we've been given
ViewParent oldContainer = mSeekBar.getParent();
ViewGroup newContainer = (ViewGroup) view.findViewById(R.id.seekBarPrefBarContainer);
if (oldContainer != newContainer) {
// remove the seekbar from the old view
if (oldContainer != null) {
((ViewGroup) oldContainer).removeView(mSeekBar);
}
// remove the existing seekbar (there may not be one) and add
// ours
newContainer.removeAllViews();
newContainer.addView(mSeekBar, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
} catch (Exception ex) {
Log.e(TAG, "Error binding view: " + ex.toString());
}
updateView(view);
}
/**
* Update a SeekBarPreference view with our current state
*
* @param view
*/
protected void updateView(View view) {
try {
RelativeLayout layout = (RelativeLayout) view;
mStatusText = (TextView) layout.findViewById(R.id.seekBarPrefValue);
mStatusText.setText(String.valueOf(pxFromDp(mCurrentValue)));
mStatusText.setMinimumWidth(30);
mSeekBar.setProgress(mCurrentValue - mMinValue);
} catch (Exception e) {
Log.e(TAG, "Error updating seek bar preference", e);
}
}
private int pxFromDp(double dp) {
return (int) (dp * context.getResources().getDisplayMetrics().density);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
int newValue = progress + mMinValue;
if (newValue > mMaxValue)
newValue = mMaxValue;
else if (newValue < mMinValue)
newValue = mMinValue;
else if (mInterval != 1 && newValue % mInterval != 0)
newValue = Math.round(((float) newValue) / mInterval) * mInterval;
// change rejected, revert to the previous value
if (!callChangeListener(newValue)) {
seekBar.setProgress(mCurrentValue - mMinValue);
return;
}
// change accepted, store it
mCurrentValue = newValue;
mStatusText.setText(String.valueOf(pxFromDp(newValue)));
persistInt(newValue);
// Refresh the corners to apply the new radius
StandOutWindow.sendData(context, Corner.class, Corner.wildcard, Corner.UPDATE_CODE, new Bundle(), Corner.class, StandOutWindow.DISREGARD_ID);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
notifyChanged();
}
@Override
protected Object onGetDefaultValue(TypedArray ta, int index) {
int defaultValue = ta.getInt(index, DEFAULT_VALUE);
return defaultValue;
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
if (restoreValue) {
mCurrentValue = getPersistedInt(mCurrentValue);
} else {
int temp = 0;
try {
temp = (Integer) defaultValue;
} catch (Exception ex) {
Log.e(TAG, "Invalid default value: " + defaultValue.toString());
}
persistInt(temp);
mCurrentValue = temp;
}
}
}
SettingsActivity.java:
Code:
package mohammad.adib.roundr;
import wei.mark.standout.StandOutWindow;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.util.Log;
import android.view.WindowManager.LayoutParams;
public class SettingsActivity extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
/**
* Handle Preference Changes
*/
// Enable/Disable
((Preference) findPreference("enable")).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean isChecked = (Boolean) newValue;
if (isChecked) {
StandOutWindow.show(SettingsActivity.this, Corner.class, 0);
StandOutWindow.show(SettingsActivity.this, Corner.class, 1);
StandOutWindow.show(SettingsActivity.this, Corner.class, 2);
StandOutWindow.show(SettingsActivity.this, Corner.class, 3);
} else {
StandOutWindow.closeAll(SettingsActivity.this, Corner.class);
}
return true;
}
});
// Notification
final int apiLevel = Build.VERSION.SDK_INT;
if (apiLevel >= 16) {
((Preference) findPreference("notification")).setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
new AlertDialog.Builder(SettingsActivity.this).setTitle("Notification").setMessage("The notification prevents Android from killing RoundR in low memory situations.\n\nOn Android 4.1+ devices, it can be disabled via the App Info.").setPositiveButton("Continue", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
showInstalledAppDetails("mohammad.adib.roundr");
}
}).show();
return true;
}
});
}else{
((Preference) findPreference("notification")).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
StandOutWindow.sendData(SettingsActivity.this, Corner.class, Corner.wildcard, Corner.NOTIFICATION_CODE, new Bundle(), Corner.class, StandOutWindow.DISREGARD_ID);
return true;
}
});
}
// Enable specific corners
for (int i = 0; i < 4; i++) {
((Preference) findPreference("corner" + i)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
refresh();
return true;
}
});
}
/**
* Overlap Settings TODO: These are messy
*/
((Preference) findPreference("overlap1")).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean isChecked = (Boolean) newValue;
if (isChecked) {
prefs.edit().putInt("type", LayoutParams.TYPE_SYSTEM_OVERLAY).commit();
if (prefs.getBoolean("overlap2", false))
prefs.edit().putInt("flags", LayoutParams.FLAG_SHOW_WHEN_LOCKED | LayoutParams.FLAG_LAYOUT_IN_SCREEN).commit();
else
prefs.edit().putInt("flags", LayoutParams.FLAG_SHOW_WHEN_LOCKED).commit();
} else {
prefs.edit().putInt("type", LayoutParams.TYPE_SYSTEM_ALERT).commit();
if (prefs.getBoolean("overlap2", false))
prefs.edit().putInt("flags", LayoutParams.FLAG_NOT_TOUCH_MODAL | LayoutParams.FLAG_LAYOUT_IN_SCREEN).commit();
else
prefs.edit().putInt("flags", LayoutParams.FLAG_NOT_TOUCH_MODAL).commit();
}
new Thread(new Runnable() {
@Override
public void run() {
// Disable and Re-enable the corners
StandOutWindow.closeAll(SettingsActivity.this, Corner.class);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
StandOutWindow.show(SettingsActivity.this, Corner.class, 0);
StandOutWindow.show(SettingsActivity.this, Corner.class, 1);
StandOutWindow.show(SettingsActivity.this, Corner.class, 2);
StandOutWindow.show(SettingsActivity.this, Corner.class, 3);
}
}).start();
return true;
}
});
((Preference) findPreference("overlap2")).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean isChecked = (Boolean) newValue;
if (isChecked) {
if (prefs.getBoolean("overlap", true))
prefs.edit().putInt("flags", LayoutParams.FLAG_SHOW_WHEN_LOCKED | LayoutParams.FLAG_LAYOUT_IN_SCREEN).commit();
else
prefs.edit().putInt("flags", LayoutParams.FLAG_NOT_TOUCH_MODAL | LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | LayoutParams.FLAG_LAYOUT_IN_SCREEN).commit();
} else {
if (prefs.getBoolean("overlap", true))
prefs.edit().putInt("flags", LayoutParams.FLAG_SHOW_WHEN_LOCKED).commit();
else
prefs.edit().putInt("flags", LayoutParams.FLAG_NOT_TOUCH_MODAL | LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH).commit();
}
new Thread(new Runnable() {
@Override
public void run() {
// Disable and Reenable the corners
StandOutWindow.closeAll(SettingsActivity.this, Corner.class);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
StandOutWindow.show(SettingsActivity.this, Corner.class, 0);
StandOutWindow.show(SettingsActivity.this, Corner.class, 1);
StandOutWindow.show(SettingsActivity.this, Corner.class, 2);
StandOutWindow.show(SettingsActivity.this, Corner.class, 3);
}
}).start();
return true;
}
});
/**
* TODO: Figure out if Developer Options is enabled. If so, show a
* GitHub Source Code Link preference:
* "Seems like you are a developer? Check out the RoundR source code on GitHub!"
*/
}
/*
* Sends a signal to all the corners to refresh their layout parameters,
* which in turn refreshes their size.
*/
public void refresh() {
StandOutWindow.sendData(this, Corner.class, Corner.wildcard, Corner.UPDATE_CODE, new Bundle(), Corner.class, StandOutWindow.DISREGARD_ID);
}
@SuppressLint("InlinedApi")
public void showInstalledAppDetails(String packageName) {
Intent intent = new Intent();
intent.setAction(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", packageName, null);
intent.setData(uri);
startActivity(intent);
}
}
preferences.xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:roundr="roundrprefs" >
<PreferenceCategory android:title="General Settings" >
<CheckBoxPreference
android:defaultValue="true"
android:key="enable"
android:summary="Enable rounded screen corners"
android:title="Enable RoundR" />
<CheckBoxPreference
android:defaultValue="true"
android:key="start_on_boot"
android:summary="Start RoundR automatically on boot"
android:title="Start on boot" />
<CheckBoxPreference
android:defaultValue="true"
android:key="notification"
android:summary="The notification is required to keep RoundR running in low memory situations"
android:title="Visible Notification" />
</PreferenceCategory>
<PreferenceCategory android:title="RoundR Settings" >
<PreferenceScreen
android:dependency="enable"
android:persistent="false"
android:summary="Enable rounding on specific corners"
android:title="Enabled Corners" >
<CheckBoxPreference
android:defaultValue="true"
android:key="corner0"
android:title="Top Left" />
<CheckBoxPreference
android:defaultValue="true"
android:key="corner1"
android:title="Top Right" />
<CheckBoxPreference
android:defaultValue="true"
android:key="corner2"
android:title="Bottom Left" />
<CheckBoxPreference
android:defaultValue="true"
android:key="corner3"
android:title="Bottom Right" />
</PreferenceScreen>
<mohammad.adib.roundr.SeekBarPreference
android:defaultValue="10"
android:key="radius"
android:max="40"
android:title="Corner Radius"
roundr:min="2"
roundr:unitsLeft=""
roundr:unitsRight="" />
<CheckBoxPreference
android:defaultValue="true"
android:key="overlap1"
android:summary="This also constitutes overlaping of the corners on the notification pull-down"
android:title="Enable on lockscreen" />
<CheckBoxPreference
android:defaultValue="false"
android:key="overlap2"
android:summary="Allows for the corners to overlap the status bar"
android:title="Overlap Status Bar" />
</PreferenceCategory>
</PreferenceScreen>
Can u help me? where is the specific code that i need, i was trying to find it for hours...
Enviado desde mi GT-S5570I usando Tapatalk 2
DannyGM16 said:
I don't find the code that I need, Help me please.
This is the code:
MainActivity.java:
Code:
package mohammad.adib.roundr;
/**
* Copyright 2013 Mohammad Adib
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
import wei.mark.standout.StandOutWindow;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class MainActivity extends Activity {
/**
* Main Activity that launches the 4 floating windows (corners)
*
* @author Mohammad Adib <[email protected]>
*
* Contributors: Mark Wei
*
*/
ProgressDialog progress;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (!BootReceiver.boot_up || Corner.running) {
Intent i = new Intent(this, SettingsActivity.class);
startActivity(i);
}
if (prefs.getBoolean("enable", true)) {
StandOutWindow.show(this, Corner.class, 0);
StandOutWindow.show(this, Corner.class, 1);
StandOutWindow.show(this, Corner.class, 2);
StandOutWindow.show(this, Corner.class, 3);
}
finish();
}
}
Corner.java:
Code:
package mohammad.adib.roundr;
/**
* Copyright 2013 Mohammad Adib
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
import wei.mark.standout.StandOutWindow;
import wei.mark.standout.constants.StandOutFlags;
import wei.mark.standout.ui.Window;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RemoteViews;
public class Corner extends StandOutWindow {
/**
* The individual floating window that sits at one of the corners of the
* screen. Window ID corresponds to which corner this goes to.
*
* @author Mohammad Adib <[email protected]>
*
* Contributors: Mark Wei, Jan Metten
*
*/
public static final String ACTION_SETTINGS = "SETTINGS";
public static final String BCAST_CONFIGCHANGED = "android.intent.action.CONFIGURATION_CHANGED";
public static final int UPDATE_CODE = 2;
public static final int NOTIFICATION_CODE = 3;
public static final int wildcard = 0;
private SharedPreferences prefs;
public static boolean running = false;
@Override
public String getAppName() {
return "RoundR";
}
@Override
public int getAppIcon() {
return R.drawable.notif_icon;
}
@Override
public void createAndAttachView(int corner, FrameLayout frame) {
// Set the image based on window corner
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
ImageView v = (ImageView) inflater.inflate(R.layout.corner, frame, true).findViewById(R.id.iv);
// Top left by default
v.setImageDrawable(getResources().getDrawable(R.drawable.topleft));
switch (corner) {
case 1:
v.setImageDrawable(getResources().getDrawable(R.drawable.topright));
break;
case 2:
v.setImageDrawable(getResources().getDrawable(R.drawable.bottomleft));
break;
case 3:
v.setImageDrawable(getResources().getDrawable(R.drawable.bottomright));
break;
}
}
private int pxFromDp(double dp) {
return (int) (dp * getResources().getDisplayMetrics().density);
}
/**
* Corners: 0 = top left; 1 = top right; 2 = bottom left; 3 = bottom right;
*/
@Override
public StandOutLayoutParams getParams(int corner, Window window) {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
// Check if this corner is enabled
if (prefs.getBoolean("corner" + corner, true)) {
int radius = pxFromDp(prefs.getInt("radius", 20));
// Thanks to Jan Metten for rewriting this based on gravity
switch (corner) {
case 0:
return new StandOutLayoutParams(corner, radius, radius, Gravity.TOP | Gravity.LEFT);
case 1:
return new StandOutLayoutParams(corner, radius, radius, Gravity.TOP | Gravity.RIGHT);
case 2:
return new StandOutLayoutParams(corner, radius, radius, Gravity.BOTTOM | Gravity.LEFT);
case 3:
return new StandOutLayoutParams(corner, radius, radius, Gravity.BOTTOM | Gravity.RIGHT);
}
}
// Outside of screen
return new StandOutLayoutParams(corner, 1, 1, -1, -1, 1, 1);
}
@Override
public int getFlags(int corner) {
return super.getFlags(corner) | StandOutFlags.FLAG_WINDOW_FOCUSABLE_DISABLE | StandOutFlags.FLAG_WINDOW_EDGE_LIMITS_ENABLE;
}
@Override
public String getPersistentNotificationMessage(int corner) {
return "Tap to configure";
}
@Override
public Intent getPersistentNotificationIntent(int corner) {
return new Intent(this, Corner.class).putExtra("id", corner).setAction(ACTION_SETTINGS);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String action = intent.getAction();
int corner = intent.getIntExtra("id", DEFAULT_ID);
if (corner == ONGOING_NOTIFICATION_ID) {
throw new RuntimeException("ID cannot equals StandOutWindow.ONGOING_NOTIFICATION_ID");
}
if (ACTION_SHOW.equals(action) || ACTION_RESTORE.equals(action)) {
show(corner);
} else if (ACTION_SETTINGS.equals(action)) {
try {
Intent intentS = new Intent(this, SettingsActivity.class);
intentS.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intentS);
} catch (Exception e) {
// Addressing this issue: http://i.imgur.com/Op9kfy8.png
}
} else if (ACTION_HIDE.equals(action)) {
hide(corner);
} else if (ACTION_CLOSE.equals(action)) {
close(corner);
} else if (ACTION_CLOSE_ALL.equals(action)) {
closeAll();
} else if (ACTION_SEND_DATA.equals(action)) {
if (isExistingId(corner) || corner == DISREGARD_ID) {
Bundle data = intent.getBundleExtra("wei.mark.standout.data");
int requestCode = intent.getIntExtra("requestCode", 0);
@SuppressWarnings("unchecked")
Class<? extends StandOutWindow> fromCls = (Class<? extends StandOutWindow>) intent.getSerializableExtra("wei.mark.standout.fromCls");
int fromId = intent.getIntExtra("fromId", DEFAULT_ID);
onReceiveData(corner, requestCode, data, fromCls, fromId);
}
}
}
return START_NOT_STICKY;
}
@Override
public boolean onClose(final int corner, final Window window) {
running = false;
return false;
}
@Override
public String getPersistentNotificationTitle(int corner) {
return "Rounded Corners";
}
@SuppressLint({ "InlinedApi", "NewApi" })
@SuppressWarnings("deprecation")
@Override
public Notification getPersistentNotification(int id) {
int icon = getAppIcon();
long when = System.currentTimeMillis();
Context c = getApplicationContext();
String contentTitle = getPersistentNotificationTitle(id);
String contentText = getPersistentNotificationMessage(id);
Intent notificationIntent = getPersistentNotificationIntent(id);
PendingIntent contentIntent = PendingIntent.getService(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// 4.1+ Low priority notification
final int apiLevel = Build.VERSION.SDK_INT;
if (apiLevel >= 16) {
Notification.Builder mBuilder = new Notification.Builder(this).setContent(new RemoteViews(getPackageName(), R.layout.notification)).setSmallIcon(getAppIcon()).setContentTitle(contentTitle).setContentText(contentText).setPriority(Notification.PRIORITY_MIN).setContentIntent(contentIntent);
return mBuilder.build();
}
String tickerText = String.format("%s: %s", contentTitle, contentText);
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(c, contentTitle, contentText, contentIntent);
return notification;
}
@Override
public boolean onShow(final int corner, final Window window) {
running = true;
return false;
}
@Override
public void onReceiveData(int corner, int requestCode, Bundle data, Class<? extends StandOutWindow> fromCls, int fromId) {
Window window = getWindow(corner);
if (requestCode == UPDATE_CODE) {
// Update the corners when device is rotated
updateViewLayout(3, getParams(3, window));
updateViewLayout(2, getParams(2, window));
updateViewLayout(1, getParams(1, window));
updateViewLayout(0, getParams(0, window));
} else if (requestCode == NOTIFICATION_CODE) {
if (!prefs.getBoolean("notification", true)) {
// Hide Notification Icon (for <= Gingerbread devices only)
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = getPersistentNotification(corner);
notification.icon = wei.mark.standout.R.drawable.nothing;
mNotificationManager.notify(getClass().hashCode() + ONGOING_NOTIFICATION_ID, notification);
Log.d("Hello World", "");
} else {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = getPersistentNotification(corner);
mNotificationManager.notify(getClass().hashCode() + ONGOING_NOTIFICATION_ID, notification);
}
}
}
}
SeekBarPreference:
Code:
package mohammad.adib.roundr;
import wei.mark.standout.StandOutWindow;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.preference.Preference;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class SeekBarPreference extends Preference implements OnSeekBarChangeListener {
private final String TAG = getClass().getName();
private static final String ANDROIDNS = "http://schemas.android.com/apk/res/android";
private static final String ROUNDRNS = "roundrprefs";
private static final int DEFAULT_VALUE = 50;
private int mMaxValue = 100;
private int mMinValue = 0;
private int mInterval = 1;
private int mCurrentValue;
private String mUnitsLeft = "";
private String mUnitsRight = "";
private SeekBar mSeekBar;
private Context context;
private TextView mStatusText;
public SeekBarPreference(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
initPreference(context, attrs);
}
public SeekBarPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initPreference(context, attrs);
}
private void initPreference(Context context, AttributeSet attrs) {
setValuesFromXml(attrs);
mSeekBar = new SeekBar(context, attrs);
mSeekBar.setMax(mMaxValue - mMinValue);
mSeekBar.setOnSeekBarChangeListener(this);
}
private void setValuesFromXml(AttributeSet attrs) {
mMaxValue = attrs.getAttributeIntValue(ANDROIDNS, "max", 100);
mMinValue = attrs.getAttributeIntValue(ROUNDRNS, "min", 0);
mUnitsLeft = getAttributeStringValue(attrs, ROUNDRNS, "unitsLeft", "");
String units = getAttributeStringValue(attrs, ROUNDRNS, "units", "");
mUnitsRight = getAttributeStringValue(attrs, ROUNDRNS, "unitsRight", units);
try {
String newInterval = attrs.getAttributeValue(ROUNDRNS, "interval");
if (newInterval != null)
mInterval = Integer.parseInt(newInterval);
} catch (Exception e) {
Log.e(TAG, "Invalid interval value", e);
}
}
private String getAttributeStringValue(AttributeSet attrs, String namespace, String name, String defaultValue) {
String value = attrs.getAttributeValue(namespace, name);
if (value == null)
value = defaultValue;
return value;
}
@Override
protected View onCreateView(ViewGroup parent) {
RelativeLayout layout = null;
try {
LayoutInflater mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = (RelativeLayout) mInflater.inflate(R.layout.seek_bar_preference, parent, false);
} catch (Exception e) {
Log.e(TAG, "Error creating seek bar preference", e);
}
return layout;
}
@Override
public void onBindView(View view) {
super.onBindView(view);
try {
// move our seekbar to the new view we've been given
ViewParent oldContainer = mSeekBar.getParent();
ViewGroup newContainer = (ViewGroup) view.findViewById(R.id.seekBarPrefBarContainer);
if (oldContainer != newContainer) {
// remove the seekbar from the old view
if (oldContainer != null) {
((ViewGroup) oldContainer).removeView(mSeekBar);
}
// remove the existing seekbar (there may not be one) and add
// ours
newContainer.removeAllViews();
newContainer.addView(mSeekBar, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
} catch (Exception ex) {
Log.e(TAG, "Error binding view: " + ex.toString());
}
updateView(view);
}
/**
* Update a SeekBarPreference view with our current state
*
* @param view
*/
protected void updateView(View view) {
try {
RelativeLayout layout = (RelativeLayout) view;
mStatusText = (TextView) layout.findViewById(R.id.seekBarPrefValue);
mStatusText.setText(String.valueOf(pxFromDp(mCurrentValue)));
mStatusText.setMinimumWidth(30);
mSeekBar.setProgress(mCurrentValue - mMinValue);
} catch (Exception e) {
Log.e(TAG, "Error updating seek bar preference", e);
}
}
private int pxFromDp(double dp) {
return (int) (dp * context.getResources().getDisplayMetrics().density);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
int newValue = progress + mMinValue;
if (newValue > mMaxValue)
newValue = mMaxValue;
else if (newValue < mMinValue)
newValue = mMinValue;
else if (mInterval != 1 && newValue % mInterval != 0)
newValue = Math.round(((float) newValue) / mInterval) * mInterval;
// change rejected, revert to the previous value
if (!callChangeListener(newValue)) {
seekBar.setProgress(mCurrentValue - mMinValue);
return;
}
// change accepted, store it
mCurrentValue = newValue;
mStatusText.setText(String.valueOf(pxFromDp(newValue)));
persistInt(newValue);
// Refresh the corners to apply the new radius
StandOutWindow.sendData(context, Corner.class, Corner.wildcard, Corner.UPDATE_CODE, new Bundle(), Corner.class, StandOutWindow.DISREGARD_ID);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
notifyChanged();
}
@Override
protected Object onGetDefaultValue(TypedArray ta, int index) {
int defaultValue = ta.getInt(index, DEFAULT_VALUE);
return defaultValue;
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
if (restoreValue) {
mCurrentValue = getPersistedInt(mCurrentValue);
} else {
int temp = 0;
try {
temp = (Integer) defaultValue;
} catch (Exception ex) {
Log.e(TAG, "Invalid default value: " + defaultValue.toString());
}
persistInt(temp);
mCurrentValue = temp;
}
}
}
SettingsActivity.java:
Code:
package mohammad.adib.roundr;
import wei.mark.standout.StandOutWindow;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.util.Log;
import android.view.WindowManager.LayoutParams;
public class SettingsActivity extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
/**
* Handle Preference Changes
*/
// Enable/Disable
((Preference) findPreference("enable")).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean isChecked = (Boolean) newValue;
if (isChecked) {
StandOutWindow.show(SettingsActivity.this, Corner.class, 0);
StandOutWindow.show(SettingsActivity.this, Corner.class, 1);
StandOutWindow.show(SettingsActivity.this, Corner.class, 2);
StandOutWindow.show(SettingsActivity.this, Corner.class, 3);
} else {
StandOutWindow.closeAll(SettingsActivity.this, Corner.class);
}
return true;
}
});
// Notification
final int apiLevel = Build.VERSION.SDK_INT;
if (apiLevel >= 16) {
((Preference) findPreference("notification")).setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
new AlertDialog.Builder(SettingsActivity.this).setTitle("Notification").setMessage("The notification prevents Android from killing RoundR in low memory situations.\n\nOn Android 4.1+ devices, it can be disabled via the App Info.").setPositiveButton("Continue", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
showInstalledAppDetails("mohammad.adib.roundr");
}
}).show();
return true;
}
});
}else{
((Preference) findPreference("notification")).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
StandOutWindow.sendData(SettingsActivity.this, Corner.class, Corner.wildcard, Corner.NOTIFICATION_CODE, new Bundle(), Corner.class, StandOutWindow.DISREGARD_ID);
return true;
}
});
}
// Enable specific corners
for (int i = 0; i < 4; i++) {
((Preference) findPreference("corner" + i)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
refresh();
return true;
}
});
}
/**
* Overlap Settings TODO: These are messy
*/
((Preference) findPreference("overlap1")).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean isChecked = (Boolean) newValue;
if (isChecked) {
prefs.edit().putInt("type", LayoutParams.TYPE_SYSTEM_OVERLAY).commit();
if (prefs.getBoolean("overlap2", false))
prefs.edit().putInt("flags", LayoutParams.FLAG_SHOW_WHEN_LOCKED | LayoutParams.FLAG_LAYOUT_IN_SCREEN).commit();
else
prefs.edit().putInt("flags", LayoutParams.FLAG_SHOW_WHEN_LOCKED).commit();
} else {
prefs.edit().putInt("type", LayoutParams.TYPE_SYSTEM_ALERT).commit();
if (prefs.getBoolean("overlap2", false))
prefs.edit().putInt("flags", LayoutParams.FLAG_NOT_TOUCH_MODAL | LayoutParams.FLAG_LAYOUT_IN_SCREEN).commit();
else
prefs.edit().putInt("flags", LayoutParams.FLAG_NOT_TOUCH_MODAL).commit();
}
new Thread(new Runnable() {
@Override
public void run() {
// Disable and Re-enable the corners
StandOutWindow.closeAll(SettingsActivity.this, Corner.class);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
StandOutWindow.show(SettingsActivity.this, Corner.class, 0);
StandOutWindow.show(SettingsActivity.this, Corner.class, 1);
StandOutWindow.show(SettingsActivity.this, Corner.class, 2);
StandOutWindow.show(SettingsActivity.this, Corner.class, 3);
}
}).start();
return true;
}
});
((Preference) findPreference("overlap2")).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean isChecked = (Boolean) newValue;
if (isChecked) {
if (prefs.getBoolean("overlap", true))
prefs.edit().putInt("flags", LayoutParams.FLAG_SHOW_WHEN_LOCKED | LayoutParams.FLAG_LAYOUT_IN_SCREEN).commit();
else
prefs.edit().putInt("flags", LayoutParams.FLAG_NOT_TOUCH_MODAL | LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | LayoutParams.FLAG_LAYOUT_IN_SCREEN).commit();
} else {
if (prefs.getBoolean("overlap", true))
prefs.edit().putInt("flags", LayoutParams.FLAG_SHOW_WHEN_LOCKED).commit();
else
prefs.edit().putInt("flags", LayoutParams.FLAG_NOT_TOUCH_MODAL | LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH).commit();
}
new Thread(new Runnable() {
@Override
public void run() {
// Disable and Reenable the corners
StandOutWindow.closeAll(SettingsActivity.this, Corner.class);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
StandOutWindow.show(SettingsActivity.this, Corner.class, 0);
StandOutWindow.show(SettingsActivity.this, Corner.class, 1);
StandOutWindow.show(SettingsActivity.this, Corner.class, 2);
StandOutWindow.show(SettingsActivity.this, Corner.class, 3);
}
}).start();
return true;
}
});
/**
* TODO: Figure out if Developer Options is enabled. If so, show a
* GitHub Source Code Link preference:
* "Seems like you are a developer? Check out the RoundR source code on GitHub!"
*/
}
/*
* Sends a signal to all the corners to refresh their layout parameters,
* which in turn refreshes their size.
*/
public void refresh() {
StandOutWindow.sendData(this, Corner.class, Corner.wildcard, Corner.UPDATE_CODE, new Bundle(), Corner.class, StandOutWindow.DISREGARD_ID);
}
@SuppressLint("InlinedApi")
public void showInstalledAppDetails(String packageName) {
Intent intent = new Intent();
intent.setAction(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", packageName, null);
intent.setData(uri);
startActivity(intent);
}
}
preferences.xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:roundr="roundrprefs" >
<PreferenceCategory android:title="General Settings" >
<CheckBoxPreference
android:defaultValue="true"
android:key="enable"
android:summary="Enable rounded screen corners"
android:title="Enable RoundR" />
<CheckBoxPreference
android:defaultValue="true"
android:key="start_on_boot"
android:summary="Start RoundR automatically on boot"
android:title="Start on boot" />
<CheckBoxPreference
android:defaultValue="true"
android:key="notification"
android:summary="The notification is required to keep RoundR running in low memory situations"
android:title="Visible Notification" />
</PreferenceCategory>
<PreferenceCategory android:title="RoundR Settings" >
<PreferenceScreen
android:dependency="enable"
android:persistent="false"
android:summary="Enable rounding on specific corners"
android:title="Enabled Corners" >
<CheckBoxPreference
android:defaultValue="true"
android:key="corner0"
android:title="Top Left" />
<CheckBoxPreference
android:defaultValue="true"
android:key="corner1"
android:title="Top Right" />
<CheckBoxPreference
android:defaultValue="true"
android:key="corner2"
android:title="Bottom Left" />
<CheckBoxPreference
android:defaultValue="true"
android:key="corner3"
android:title="Bottom Right" />
</PreferenceScreen>
<mohammad.adib.roundr.SeekBarPreference
android:defaultValue="10"
android:key="radius"
android:max="40"
android:title="Corner Radius"
roundr:min="2"
roundr:unitsLeft=""
roundr:unitsRight="" />
<CheckBoxPreference
android:defaultValue="true"
android:key="overlap1"
android:summary="This also constitutes overlaping of the corners on the notification pull-down"
android:title="Enable on lockscreen" />
<CheckBoxPreference
android:defaultValue="false"
android:key="overlap2"
android:summary="Allows for the corners to overlap the status bar"
android:title="Overlap Status Bar" />
</PreferenceCategory>
</PreferenceScreen>
Can u help me? where is the specific code that i need, i was trying to find it for hours...
Enviado desde mi GT-S5570I usando Tapatalk 2
Click to expand...
Click to collapse
It's this particular code change: https://github.com/MohammadAdib/Roundr/commit/b47ca72867093dbe9b29a99469f48e95a1d369fa
nikwen said:
It's this particular code change: https://github.com/MohammadAdib/Roundr/commit/b47ca72867093dbe9b29a99469f48e95a1d369fa
Click to expand...
Click to collapse
IT WORK'S! IT WORK'S! THANK'S!
But the problem now i how to get clicks from it. Do you know how to do it?
Enviado desde mi GT-S5570I usando Tapatalk 2
DannyGM16 said:
IT WORK'S! IT WORK'S! THANK'S!
But the problem now i how to get clicks from it. Do you know how to do it?
Enviado desde mi GT-S5570I usando Tapatalk 2
Click to expand...
Click to collapse
Great. :good:
What's about adding an onClick listener?
nikwen said:
Great. :good:
What's about adding an onClick listener?
Click to expand...
Click to collapse
I tryed it, but the onClick affects to all the screen...
Enviado desde mi GT-S5570I usando Tapatalk 2

swipable menu on left

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...

Android App - Java: Adding to an arrayList then updating a ListView

I have coded this android app which produces a listView containing songs which are streamed from the internet, and the user can play them by clicking them using the mediaPlayer.
What i am having trouble with is allowing the user to add a song to the arrayList that populates the ListView within MainActivity.java. I have used the settings page to add textboxes so the user can add their songs by inputting, Song Name, Artist and the Direct Link to the song. Though the code i have used for this doesn't work, it should add the Song Name, Artist and Direct Link into the array_list_music ArrayList, then update the ListView, or at least i think that is how it should be done, although after entering details and clicking the 'Add Song' button, and returning to the main page, the ListView does not that the newly added song.
I have shown my code below.
So if someone could help with this problem, that would be great, thanks.
MainActivity.java
Code:
package com.groupassignment.musicplayer;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.Toast;
public class MainActivity extends ListActivity implements OnPreparedListener, MediaController.MediaPlayerControl {
private static final String TAG = "AudioPlayer";
private ListView list;
public MainArrayAdapter adapter;
private MediaPlayer mediaPlayer;
private MediaController mediaController;
private String audioFile;
private Handler handler = new Handler();
ArrayList<String> array_list_music = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = getListView();
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaController = new MediaController(this);
//ArrayList<String> array_list_music = new ArrayList<String>();
//Used to add a song to the array list
array_list_music
.add("Jar of Hearts"
+ " ### "
+ "Christina Perri"
+ " ### "
+ "LINK");
array_list_music
.add("Save The World"
+ " ### "
+ "Swedish House Mafia feat. John Martin"
+ " ### "
+ "LINK");
array_list_music
.add("Bromance"
+ " ### "
+ "Avicii"
+ " ### "
+ "LINK");
adapter = new MainArrayAdapter(MainActivity.this, array_list_music);
setListAdapter(adapter);
//used to display toast and to play song using the URL, when clicking on a song
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Object item = getListView().getItemAtPosition(arg2);
String the_list_item = item.toString();
Toast.makeText(MainActivity.this, "You are now listening to: " + the_list_item, Toast.LENGTH_LONG).show();
String[] aux = the_list_item.split(" ### ");
String url_to_play = aux[2];
playAudio(url_to_play);//sends url from arraylist item to the playAudio method
}
});
}
//used to play audio using the android mediaPlayer
private void playAudio(String url_to_play) {
//stop & reset player
try {
mediaPlayer.stop();
mediaPlayer.reset();
} catch (Exception e) {
}
//set the url, prepare it, and then play it
try {
mediaPlayer.setDataSource(url_to_play);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
Log.e(TAG, "Could not open file " + url_to_play + ".", e);
}
}
@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 boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent i_settings = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(i_settings);
break;
}
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mediaController.show();
return false;
}
//used to hide media controller, stop the media player and to release the url.
@Override
protected void onStop() {
super.onStop();
mediaController.hide();
mediaPlayer.stop();
mediaPlayer.release();
}
@Override
public boolean canPause() {
return true;
}
@Override
public boolean canSeekBackward() {
return true;
}
@Override
public boolean canSeekForward() {
return true;
}
@Override
public int getBufferPercentage() {
return 0;
}
@Override
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
@Override
public int getDuration() {
return mediaPlayer.getDuration();
}
@Override
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
@Override
public void pause() {
mediaPlayer.pause();
}
@Override
public void seekTo(int arg0) {
mediaPlayer.seekTo(arg0);
}
@Override
public void start() {
mediaPlayer.start();
}
public void onPrepared(MediaPlayer mediaPlayer) {
Log.d(TAG, "onPrepared");
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(list);
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
//------- what can you do from here -------
// implement your own media player with buttons since this one is not behaving "smart"..
// make next,previous buttons
// highlight the list item on click
// add your own server for playing music
// anything you want :)
}
MainArrayAdapter.java
Code:
package com.groupassignment.musicplayer;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import android.content.Context;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.groupassignment.musicplayer.R;
public class MainArrayAdapter extends ArrayAdapter<String> implements ListAdapter {
private final Context context;
private ArrayList<String> data_array;
private List<DataSetObserver> observers = new LinkedList<DataSetObserver>();
public MainArrayAdapter(Context context, ArrayList<String> list_of_ids) {
super(context, R.layout.main_list_rowlayout, list_of_ids);
this.context = context;
this.data_array = list_of_ids;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.main_list_rowlayout, parent,
false);
TextView textView_main_row_song_name = (TextView) rowView
.findViewById(R.id.textView_main_row_song_name);
TextView textView_main_row_singer_name = (TextView) rowView
.findViewById(R.id.textView_main_row_singer_name);
try {
String[] aux = data_array.get(position).split(" ### ");
String song_name = aux[0];
String artist = aux[1];
String url = aux[2];
textView_main_row_song_name.setText(song_name);
textView_main_row_singer_name.setText(artist);
} catch (Exception e) {
// TODO: handle exception
}
return rowView;
}
public void setArray(ArrayList<String> data_array){
this.data_array = data_array;
for (DataSetObserver observer : observers){
observer.onChanged();
}
}
@Override
public void registerDataSetObserver(DataSetObserver dataSetObserver) {
((LinkedList) observers).addFirst(dataSetObserver);
}
@Override
public void unregisterDataSetObserver(DataSetObserver dataSetObserver) {
observers.remove(dataSetObserver);
}
}
SettingsActivity.java
Code:
package com.groupassignment.musicplayer;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import com.groupassignment.musicplayer.R;
public class SettingsActivity extends Activity {
public String str ="";
String songName;
String artist;
String directLink;
protected void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
songName = ((EditText)findViewById(R.id.editTextSongName)).toString();
artist = ((EditText)findViewById(R.id.editTextArtist)).toString();
directLink = ((EditText)findViewById(R.id.editTextDirectLink)).toString();
};
public void buttonAddSongClicked(View v)
{
addSong(songName, artist, directLink);
}
private void addSong(String artist, String songName, String directLink)
{
MainActivity main = new MainActivity();
main.array_list_music
.add( songName
+ " ### "
+ artist
+ " ### "
+ directLink);
main.adapter.notifyDataSetChanged();
main.adapter = new MainArrayAdapter(main, main.array_list_music);
}
}
The problem is that you create new instances of adapter each time, instead of updating the existing one. Easy way to solve your problem is to change attributes of array_list_music and adapter to public static in your MainActivity and modify addSong inside SettingsActivity to:
Code:
private void addSong(String artist, String songName, String directLink)
{
MainActivity.array_list_music
.add( songName
+ " ### "
+ artist
+ " ### "
+ directLink);
MainActivity.adapter.notifyDataSetChanged();
}

Categories

Resources