[Q] Can someone help me out with an app i'm making - Java for Android App Development

This is a very simple webview app, its used to load a remote website and allow users to browse the site from the app.
What i want it to do, is support swipe gestures, for example
Swipe left to right go back a page
Swipe right to left go forward a page
Eventually i'm going to try to add in page turn animations but for not i just need to get the swipe gesture support to work for the initial release
The code needs a lot of cleanup as well, the vertical swipe detection needs to come out, but its only there for testing purposes
Code:
package com.bno.bnoonline;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.MotionEvent;
import android.view.View;
public class MainActivity extends Activity {
WebView mWebView;
/** Called when the activity is first created. */
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebViewClient yourWebClient = new WebViewClient() {
// Override page so it's load on my view only
[user=439709]@override[/user]
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// This line we let me load only pages inside Firstdroid Webpage
if (url.contains("myurl") == true)
// Load new URL Don't override URL Link
return false;
// Return true to override url loading (In this case do
// nothing).
return true;
}
};
// Get Web view
mWebView = (WebView) findViewById(R.id.webView1); // This is the id you
// gave
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setSupportZoom(true); // Zoom Control on web (You
// don't need this
// if ROM supports Multi-Touch
mWebView.getSettings().setBuiltInZoomControls(true); // Enable
// Multitouch if
// supported by
// ROM
mWebView.setWebViewClient(yourWebClient);
// Load URL
mWebView.loadUrl("myurl.com");
}
public static enum Action {
LR, // Left to right
RL, // Right to left
TB, // Top to bottom
BT, // Bottom to top
None // Action not found
}
private static final int HORIZONTAL_MIN_DISTANCE = 30; // The minimum
// distance for
// horizontal swipe
private static final int VERTICAL_MIN_DISTANCE = 80; // The minimum distance
// for vertical
// swipe
private float downX, downY, upX, upY; // Coordinates
private Action mSwipeDetected = Action.None; // Last action
public boolean swipeDetected() {
return mSwipeDetected != Action.None;
}
public Action getAction() {
return mSwipeDetected;
}
/**
* Swipe detection
* [user=2056652]@return[/user]
*/public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
{
downX = event.getX();
downY = event.getY();
mSwipeDetected = Action.None;
return false; // allow other events like Click to be processed
}
case MotionEvent.ACTION_MOVE:
{
upX = event.getX();
upY = event.getY();
float deltaX = downX - upX;
float deltaY = downY - upY;
// horizontal swipe detection
if (Math.abs(deltaX) > HORIZONTAL_MIN_DISTANCE) {
// left or right
if (deltaX < 0) {
mSwipeDetected = Action.LR;
if(mWebView.canGoForward() == true){
mWebView.goForward();
return true;
}
if (deltaX > 0) {
mSwipeDetected = Action.RL;
if(mWebView.canGoBack() == true){
mWebView.goBack();
return true;
}
} else
// vertical swipe detection
if (Math.abs(deltaY) > VERTICAL_MIN_DISTANCE) {
// top or down
if (deltaY < 0) {
mSwipeDetected = Action.TB;
return false;
}
if (deltaY > 0) {
mSwipeDetected = Action.BT;
return false;
}
}
return true;
}
}
return false;
}
}
return false;
}
}
Here is a logcat, though its not very revealing
09-30 01:01:18.331: E/Trace(10259): error opening trace file: No such file or directory (2)
09-30 01:01:19.151: D/dalvikvm(10259): GC_FOR_ALLOC freed 45K, 6% free 2662K/2828K, paused 246ms, total 254ms
09-30 01:01:19.161: I/dalvikvm-heap(10259): Grow heap (frag case) to 3.787MB for 1127536-byte allocation
09-30 01:01:19.351: D/dalvikvm(10259): GC_FOR_ALLOC freed 2K, 5% free 3760K/3932K, paused 188ms, total 188ms
09-30 01:01:19.461: D/dalvikvm(10259): GC_CONCURRENT freed <1K, 5% free 3766K/3932K, paused 5ms+14ms, total 112ms
09-30 01:01:19.991: D/libEGL(10259): loaded /system/lib/egl/libEGL_emulation.so
09-30 01:01:20.021: D/(10259): HostConnection::get() New Host Connection established 0x2a17cbe0, tid 10259
09-30 01:01:20.061: D/libEGL(10259): loaded /system/lib/egl/libGLESv1_CM_emulation.so
09-30 01:01:20.091: D/libEGL(10259): loaded /system/lib/egl/libGLESv2_emulation.so
09-30 01:01:20.231: W/EGL_emulation(10259): eglSurfaceAttrib not implemented
09-30 01:01:20.291: D/OpenGLRenderer(10259): Enabling debug mode 0
09-30 01:01:20.301: I/Choreographer(10259): Skipped 37 frames! The application may be doing too much work on its main thread.
09-30 01:01:29.534: D/TilesManager(10259): Starting TG #0, 0x2a561340
09-30 01:01:29.541: D/TilesManager(10259): new EGLContext from framework: 2a1b9bc0
09-30 01:01:29.541: D/GLWebViewState(10259): Reinit shader
09-30 01:01:29.912: D/GLWebViewState(10259): Reinit transferQueue
09-30 01:01:31.451: D/(10259): HostConnection::get() New Host Connection established 0x2a4d6ae8, tid 10286
09-30 01:02:44.795: D/dalvikvm(10259): GC_CONCURRENT freed 196K, 8% free 3956K/4272K, paused 20ms+17ms, total 104ms
09-30 01:02:54.462: D/dalvikvm(10259): GC_FOR_ALLOC freed 37K, 8% free 4239K/4592K, paused 36ms, total 41ms

So is it force closing or what? At first I thought maybe you were wanting help on gestures but I'm confused as to why you posted the logcat.
Take a look here if it is help on gestures
http://stackoverflow.com/questions/16392559/webview-with-swipe-gesture

zalez said:
So is it force closing or what? At first I thought maybe you were wanting help on gestures but I'm confused as to why you posted the logcat.
Take a look here if it is help on gestures
Click to expand...
Click to collapse
Thanks, looking over that, it seems to be more simplified than my implementation.
Also, i posted the logcat because the rules say that i should *shrug*
To clarify for anyone else that reads this, the problem with the above code is that its not working, the gesture implementation that i am using in the original code simply does not work meaning, nothing happens when i swipe left or right.

Related

WM6 - how to Query WLAN "connection" status

I am desperately trying to work around some unknown problem caused by our NDIS IM driver on WM6 and HTC TyTn ( TyTn at least, but most likely other devices as well ). I started some other threads regarding different facets of this problem, and no help is coming. Now I am just trying to work around it.
in short the problem is when power events happen the WLAN will never connect.
The work around is programmatically open the control panel with STControlPanel class and press the down button 1 time then the f1 key ( right dash ). This "presses connect" on the last configured access point. This works around my problem, however, I need to detect when the access point has connected. There is a "connecting" and "connected" message for the access point in this control panel dialog ( control panel # 17 ).
My Question: Is there some way to get this text "connecting" or "connected" from the control panel #17?
I have tried wzc, ndisuio, winsock, and other "non control panel" ways to detect connected state, but the IM problem fools all these methods. The only thing I have ever seen that successfully shows when the problem has occurred is the "connecting"/"connected" status in the control panel 17.
Please Help Someone.
p.s. If I can get this worked around, we sell a commercial grade ndis intermediate driver toolkit letting you easily write plugins without any of the hard driver details. We have redirectors, transparent proxy, tunnelers, virtual adapters, lots of good stuff. Also the same plugin will work on all windows desktop platforms vista - 98, WM5/6 and CE and also linux and solaris...
Hello skk
What about notification API?
Here is the solution (simple concept) for Your problem. Interesting parts are in bold.
SNapiTest.cpp
Code:
#include "stdafx.h"
#include "SNapiTest.h"
#include <windows.h>
#include <commctrl.h>
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE g_hInst; // current instance
HWND g_hWndMenuBar; // menu bar handle
[b]
const DWORD WM_WIFISTATUS = WM_USER + 1;
bool g_connecting;
bool g_connected;
HREGNOTIFY g_hNotify;
HREGNOTIFY g_hNotify2;
[/b]
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE, LPTSTR);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
MSG msg;
// Perform application initialization:
if (!InitInstance(hInstance, nCmdShow))
{
return FALSE;
}
HACCEL hAccelTable;
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_SNAPITEST));
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
// COMMENTS:
//
ATOM MyRegisterClass(HINSTANCE hInstance, LPTSTR szWindowClass)
{
WNDCLASS wc;
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_SNAPITEST));
wc.hCursor = 0;
wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
wc.lpszMenuName = 0;
wc.lpszClassName = szWindowClass;
return RegisterClass(&wc);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
TCHAR szTitle[MAX_LOADSTRING]; // title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // main window class name
g_hInst = hInstance; // Store instance handle in our global variable
// SHInitExtraControls should be called once during your application's initialization to initialize any
// of the device specific controls such as CAPEDIT and SIPPREF.
SHInitExtraControls();
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_SNAPITEST, szWindowClass, MAX_LOADSTRING);
//If it is already running, then focus on the window, and exit
hWnd = FindWindow(szWindowClass, szTitle);
if (hWnd)
{
// set focus to foremost child window
// The "| 0x00000001" is used to bring any owned windows to the foreground and
// activate them.
SetForegroundWindow((HWND)((ULONG) hWnd | 0x00000001));
return 0;
}
if (!MyRegisterClass(hInstance, szWindowClass))
{
return FALSE;
}
hWnd = CreateWindow(szWindowClass, szTitle, WS_VISIBLE,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
// When the main window is created using CW_USEDEFAULT the height of the menubar (if one
// is created is not taken into account). So we resize the window after creating it
// if a menubar is present
if (g_hWndMenuBar)
{
RECT rc;
RECT rcMenuBar;
GetWindowRect(hWnd, &rc);
GetWindowRect(g_hWndMenuBar, &rcMenuBar);
rc.bottom -= (rcMenuBar.bottom - rcMenuBar.top);
MoveWindow(hWnd, rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top, FALSE);
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
static SHACTIVATEINFO s_sai;
switch (message)
{
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_HELP_ABOUT:
DialogBox(g_hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, About);
break;
case IDM_OK:
SendMessage (hWnd, WM_CLOSE, 0, 0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_CREATE:
SHMENUBARINFO mbi;
memset(&mbi, 0, sizeof(SHMENUBARINFO));
mbi.cbSize = sizeof(SHMENUBARINFO);
mbi.hwndParent = hWnd;
mbi.nToolBarId = IDR_MENU;
mbi.hInstRes = g_hInst;
if (!SHCreateMenuBar(&mbi))
{
g_hWndMenuBar = NULL;
}
else
{
g_hWndMenuBar = mbi.hwndMB;
}
// Initialize the shell activate info structure
memset(&s_sai, 0, sizeof (s_sai));
s_sai.cbSize = sizeof (s_sai);
[b]
g_connecting = false;
g_connected = false;
{HRESULT hr = RegistryNotifyWindow(SN_WIFISTATECONNECTING_ROOT,
SN_WIFISTATECONNECTING_PATH, SN_WIFISTATECONNECTING_VALUE,
hWnd, WM_WIFISTATUS, 0, NULL, &g_hNotify);}
{HRESULT hr2 = RegistryNotifyWindow(SN_WIFISTATECONNECTING_ROOT,
SN_WIFISTATECONNECTED_PATH, SN_WIFISTATECONNECTED_VALUE,
hWnd, WM_WIFISTATUS, 0, NULL, &g_hNotify2);}
[/b]
break;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code here...
EndPaint(hWnd, &ps);
break;
[b]
case WM_WIFISTATUS:
{
DWORD newValue = (DWORD) wParam;
WCHAR caption[] = L"Wifi Status";
if ((newValue & SN_WIFISTATECONNECTED_BITMASK) == SN_WIFISTATECONNECTED_BITMASK)
{
if (!g_connected)
{
g_connected = true;
g_connecting = false;
MessageBox(hWnd, L"Connected!!", caption, MB_OK);
}
break;
}
if ((newValue & SN_WIFISTATECONNECTING_BITMASK) == SN_WIFISTATECONNECTING_BITMASK)
{
if (!g_connecting)
{
g_connecting = true;
g_connected =false;
MessageBox(hWnd, L"Connecting...", caption, MB_OK);
}
}
break;
}
[/b]
case WM_DESTROY:
CommandBar_Destroy(g_hWndMenuBar);
[B]
RegistryCloseNotification(g_hNotify);
RegistryCloseNotification(g_hNotify2);
[/B]
PostQuitMessage(0);
break;
case WM_ACTIVATE:
// Notify shell of our activate message
SHHandleWMActivate(hWnd, wParam, lParam, &s_sai, FALSE);
break;
case WM_SETTINGCHANGE:
SHHandleWMSettingChange(hWnd, wParam, lParam, &s_sai);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_INITDIALOG:
{
// Create a Done button and size it.
SHINITDLGINFO shidi;
shidi.dwMask = SHIDIM_FLAGS;
shidi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIPDOWN | SHIDIF_SIZEDLGFULLSCREEN | SHIDIF_EMPTYMENU;
shidi.hDlg = hDlg;
SHInitDialog(&shidi);
}
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK)
{
EndDialog(hDlg, LOWORD(wParam));
return TRUE;
}
break;
case WM_CLOSE:
EndDialog(hDlg, message);
return TRUE;
}
return (INT_PTR)FALSE;
}
Needed includes:
// TODO: reference additional headers your program requires here
#include <snapi.h>
#include <regext.h>
snapi.h
Thank you so much for your post. I just found snapi.h, I assume this is snapitest.h?
IT WORKS!
It works! You are my hero RStein. You are a god among men.
Great. ) Thanks for sharing the results.

Cursor help!

I'm new to using cursors to obtain data from the device. I'm working on a music player (see market link in signature) and I need to be able to list (and eventually play) the music found on the sdcard. I have some code, but I can't seem to get it to work
Here's the code I found on a website, but it leads to a force-close:
public class TestingData extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView view = (TextView) findViewById(R.id.hello);
String[] projection = new String[] {
MediaStore.MediaColumns.DISPLAY_NAME
, MediaStore.MediaColumns.DATE_ADDED
, MediaStore.MediaColumns.MIME_TYPE
};
Cursor mCur = managedQuery(Media.EXTERNAL_CONTENT_URI,
projection, null, null, null
);
mCur.moveToFirst();
while (mCur.isAfterLast() == false) {
for (int i=0; i<mCur.getColumnCount(); i++) {
view.append("n" + mCur.getString(i));
}
mCur.moveToNext();
}
}
}
Here's my attempt at fixing it, which still leads to a force-close:
public class test3 extends Activity {
TextView view = (TextView) findViewById(R.id.text1);
ListView list;
private ArrayAdapter<String> adapter;
String[] projection = new String[] {
MediaStore.MediaColumns.DISPLAY_NAME
, MediaStore.MediaColumns.DATE_ADDED
, MediaStore.MediaColumns.MIME_TYPE
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list = (ListView)findViewById(R.id.list);
ArrayList<String> _list = new ArrayList<String>(Arrays.asList(projection));
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,_list);
list.setAdapter(adapter);
Cursor mCur = managedQuery(Media.EXTERNAL_CONTENT_URI,
projection, null, null,
MediaStore.MediaColumns.DISPLAY_NAME + "ASC"
);
mCur.moveToFirst();
while (mCur.isAfterLast() == false) {
for (int i=0; i<mCur.getColumnCount(); i++) {
view.append("n" + mCur.getString(i));
}
mCur.moveToNext();
}
}
}
What am I doing wrong? Both codes lead to a force-close and I can't think of anything else to do. Thanks in advance.
did you set the correct permissions in the android manifest?
*slaps hand to forehead* I always forget about the manifest. Lol. Ummmm....what all am I supposed to put in there for these codes? Do both codes look like they would accomplish the same thing?
Well, I've written hundreds of Cursors in Android and I don't run my loop like you do, so, as a suggestion:
Code:
Cursror c = yada, yada;
if(c.moveToFirst()) {
do {
// TO DO HERE...
} while(c.moveToNext());
}
c.close();
Never had a problem.
Awesome! Thanks. Ill try it when I get a chance

Finish Appwidget Config Activity

i have an Appwidget that i have been working on in conjuntion with an Appwidget Config Activity that runs before the Appwidget gets placed. i have two buttons in the config activity. one for canceling out of creating the widget and one for making the widget. i am fine on the cancel button, but no matter what i do for my create button i cant seem to get it to make the appwidget.
how can i have a button create my appwidget inside my appwidget config activity?
----
ANSWER IN #3
Bump.
It would be logical to have finish() make the widget appear but it does not. Really need some help / direction with this
From something awesome
hope this helps others who are looking to make this happen.
Code:
private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setResult(RESULT_CANCELED);
setContentView(R.layout.gitc_config);
findViewById(R.id.create_button).setOnClickListener(mOnClickListener);
// Find the widget id from the intent.
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
mAppWidgetId = extras.getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
}
// If they gave us an intent without the widget id, just bail.
if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
finish();
}
}
View.OnClickListener mOnClickListener = new View.OnClickListener() {
public void onClick(View v) {
// Make sure we pass back the original appWidgetId
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, resultValue);
finish();
}
};

[Q] No idea how to load onChildClick in my ExpandableListView.

I have an expandable list view with 2 parents and 3 children. I want to open a dialog based on each click. I can't find any examples showing you how to call something based on positions. At least not with the ExpandableListView tutorial I followed.
Code:
public class MainActivity extends Activity implements OnClickListener {
private LinkedHashMap<String, HeaderInfo> myDepartments = new LinkedHashMap<String, HeaderInfo>();
private ArrayList<HeaderInfo> deptList = new ArrayList<HeaderInfo>();
private MyListAdapter listAdapter;
private ExpandableListView myList;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Just add some data to start with
loadData();
// get reference to the ExpandableListView
myList = (ExpandableListView) findViewById(R.id.myList);
// create the adapter by passing your ArrayList data
listAdapter = new MyListAdapter(MainActivity.this, deptList);
// attach the adapter to the list
myList.setAdapter(listAdapter);
// listener for child row click
myList.setOnChildClickListener(myListItemClicked);
// listener for group heading click
myList.setOnGroupClickListener(myListGroupClicked);
}
// load some initial data into out list
private void loadData() {
addProduct("Parent One", "Child One");
addProduct("Parent One", "Child Two");
addProduct("Parent One", "Child Three");
addProduct("Parent Two", "Child One");
addProduct("Parent Two", "Child Two");
addProduct("Parent Two", "Child Three");
}
// our child listener
private OnChildClickListener myListItemClicked = new OnChildClickListener() {
[user=439709]@override[/user]
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// Create a switch that switches on the specific child position.
// get the group header
HeaderInfo headerInfo = deptList.get(groupPosition);
// get the child info
DetailInfo detailInfo = headerInfo.getProductList().get(
childPosition);
// display it or do something with it
// custom dialog
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.cdialog);
// dialog.setTitle(R.id.titlebar);
dialog.setTitle(R.string.titlebar);
dialog.show();
return false;
}
};
// our group listener
private OnGroupClickListener myListGroupClicked = new OnGroupClickListener() {
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// get the group header HeaderInfo headerInfo =
deptList.get(groupPosition);
// display it or do something with it
return false;
}
};
I can get a custom dialog open if I click a child, but it's not set to any specific parent and child.
Any ideas?
EDIT ADD: Got it. Tried a switch/case like this and it worked. Finally! After two days of trying to understand it.:fingers-crossed:
Code:
switch(groupPosition) {
case 1:
switch (childPosition) {
case 0:
Intent protheanIntent = new Intent(Codex.this, CodexProthean.class);
Codex.this.startActivity(protheanIntent);
break;
case 1:
Intent rachniIntent = new Intent(Codex.this, CodexRachni.class);
Codex.this.startActivity(rachniIntent);
break;
}
case 2:
switch (childPosition) {
case 2:
Intent asariIntent = new Intent(Codex.this, CodexAsari.class);
Codex.this.startActivity(asariIntent);
break;
}
}

[Q] How to stop the ball at touch release

hi, its killing me i can't fix it i made this thing because i was learning Canvas and drawing on android !
i included moving animations (smooth) but i removed it
Code:
package com.example.graphics;
import android.content.Context;
import android.view.KeyEvent;
import android.view.MotionEvent;
import java.util.Formatter;
import android.graphics.Typeface;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.View;
public class BouncingBallView extends View {
private int xMin = 0; // This view's bounds
private int xMax;
private int yMin = 0;
private int yMax;
private float ballRadius = 80; // Ball's radius
private float ballX = ballRadius + 20; // Ball's center (x,y)
private float ballY = ballRadius + 40;
private float ballSpeedX = 11; // Ball's speed (x,y)
private float ballSpeedY = 7;
//private RectF ballBounds; // Needed for Canvas.drawOval
private Paint paint; // The paint (e.g. style, color) used for drawing
// Status message to show Ball's (x,y) position and speed.
private StringBuilder statusMsg = new StringBuilder();
private Formatter formatter = new Formatter(statusMsg); // Formatting the statusMsg
private float previousX;
private float previousY;
private float currentX;
private float currentY;
private float scale;
private int ifdrawcount = 0;
// Constructor
public BouncingBallView(Context context) {
super(context);
//ballBounds = new RectF();
paint = new Paint();
paint.setTypeface(Typeface.MONOSPACE);
paint.setTextSize(25);
setFocusableInTouchMode(true);
//setFocusable(true);
requestFocus();
}
/*public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_RIGHT: // Increase rightward speed
ballSpeedX++;
break;
case KeyEvent.KEYCODE_DPAD_LEFT: // Increase leftward speed
ballSpeedX--;
break;
case KeyEvent.KEYCODE_DPAD_UP: // Increase upward speed
ballSpeedY--;
break;
case KeyEvent.KEYCODE_DPAD_DOWN: // Increase downward speed
ballSpeedY++;
break;
case KeyEvent.KEYCODE_DPAD_CENTER: // Stop
ballSpeedX = 0;
ballSpeedY = 0;
break;
case KeyEvent.KEYCODE_A: // Zoom in
// Max radius is about 90% of half of the smaller dimension
float maxRadius = (xMax > yMax) ? yMax / 2 * 0.9f : xMax / 2 * 0.9f;
if (ballRadius < maxRadius) {
ballRadius *= 1.05; // Increase radius by 5%
}
break;
case KeyEvent.KEYCODE_Z: // Zoom out
if (ballRadius > 20) { // Minimum radius
ballRadius *= 0.95; // Decrease radius by 5%
}
break;
}
return true; // Event handled
}*/
// Called back to draw the view. Also called by invalidate().
@Override
protected void onDraw(Canvas canvas) {
// Draw the ball
//ballBounds.set(ballX-ballRadius, ballY-ballRadius, ballX+ballRadius, ballY+ballRadius);
//paint.setColor(Color.GRAY);
//canvas.drawOval(ballBounds, paint);
//canvas.drawCircle(70, yMax -70, 60, paint);
//canvas.drawCircle(xMax -70, yMax -60, 60, paint);
paint.setColor(Color.GREEN);
canvas.drawCircle(ballX, ballY, ballRadius, paint);
// Draw the status message
paint.setColor(Color.WHITE);
paint.setStrokeWidth(2);
canvas.drawText(statusMsg.toString(), 10, 30, paint);
if(ifdrawcount > 0){
canvas.drawLine(previousX, previousY, currentX, currentY, paint);
paint.setStrokeWidth(10);
paint.setColor(Color.BLACK);
canvas.drawPoint(previousX,previousY,paint);
ifdrawcount--;
}
// Update the position of the ball, including collision detection and reaction.
update();
// Delay
try {
Thread.sleep(16);
} catch (InterruptedException e) { }
invalidate(); // Force a re-draw
}
// Touch-input handler
@Override
public boolean onTouchEvent(MotionEvent event) {
currentX = event.getX();
currentY = event.getY();
ifdrawcount = 10;
//float deltaX, deltaY;
scale = 20.0f / ((xMax > yMax) ? yMax : xMax);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
previousX = currentX;
previousY = currentY;
case MotionEvent.ACTION_MOVE:
ballSpeedY = (currentY - previousY) * scale;
ballSpeedX = (currentX - previousX) * scale;
case MotionEvent.ACTION_UP:
ballSpeedX = 0;
ballSpeedY = 0;
}
return true; // Event handled
}
// Detect collision and update the position of the ball.
private void update() {
// Get new (x,y) position
ballX += ballSpeedX;
ballY += ballSpeedY;
/*if(ifdrawcount == 0)
ballSpeedX = 0; ballSpeedY = 0;*/
// Detect collision and react
if (ballX + ballRadius > xMax) {
ballSpeedX = -ballSpeedX;
ballX = xMax-ballRadius;
} else if (ballX - ballRadius < xMin) {
ballSpeedX = -ballSpeedX;
ballX = xMin+ballRadius;
}
if (ballY + ballRadius > yMax) {
ballSpeedY = -ballSpeedY;
ballY = yMax - ballRadius;
} else if (ballY - ballRadius < yMin) {
ballSpeedY = -ballSpeedY;
ballY = yMin + ballRadius;
}
// Build status message
statusMsg.delete(0, statusMsg.length()); // Empty buffer
formatter.format("%3.0f %3.0f || %3.0f %3.0f", ballSpeedX, ballSpeedY,ballX,ballY);
}
// Called back when the view is first created or its size changes.
@Override
public void onSizeChanged(int w, int h, int oldW, int oldH) {
// Set the movement bounds for the ball
xMax = w-1;
yMax = h-1;
}
}
the problem is my ball doesn't move at all, but i see the line, once i remove the line:
Code:
case MotionEvent.ACTION_UP:
ballSpeedX = 0;
ballSpeedY = 0;
it works, but you know, after release it continues with same speed :! its like the ACTION_UP is always the case, !!! any idea why it doesn't work, how to stop the ball once the user releases the screen?
also sorry if this is not the right place. i searched the forums, i got confused i didn't find anyplace to ask this question so i tough this is the best place!

Categories

Resources