enter image description here
enter image description here
I created an App and when I run it on a Motorola Xoom it executes the main activity as I expected but when I run it on a Huawei phone it displays Hello World and never executes the main activity. (Android 4.1.2 and 8 respectively. I have created projects using the Basic Activity and the Empty Activity and get the same result with both). How do I stop the Hello World?
package com.example.xoom;
import android.hardware.usb.UsbConstants;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.app.PendingIntent;
import android.content.Intent;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Button;
import android.content.Context;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.graphics.Color;
import android.graphics.Typeface;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity
{
final Button[] pitchButton = new Button[50];
int startLength;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String ACTION_USB_PERMISSION = "com.example.xoom";
byte[] sendChar = {0x5A}; // ASCII "Z"
byte[] getChar = new byte[200];
boolean addListener;
TextView tv = new TextView(this);
int buttonCount = 0;
for (int i = 0; i < 50; i++)
{
pitchButton[i] = new Button(this);
pitchButton[i].setTypeface(Typeface.MONOSPACE);
}
tv.setTextSize(20);
getWindow().getDecorView().setBackgroundColor(Color.CYAN);
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
if (manager.getDeviceList().isEmpty()) // The device list is empty
{
tv.setTextColor(Color.RED);
tv.append("No USB Devices Found");
}
else
{
tv.setTextColor(Color.BLUE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
UsbDevice device = deviceIterator.next(); // Get first device in list
PendingIntent pi = PendingIntent.getBroadcast(this, 0,
new Intent(ACTION_USB_PERMISSION), 0);
manager.requestPermission(device, pi);
UsbDeviceConnection connection = manager.openDevice(device);
getDeviceProperties(device, manager, tv); // Show USB device properties
getInterfaceProperties(device, connection, tv); // Show USB Interface properties
tv.setText(""); // Clear information from above because you don't want to see
// it normally but sometimes you do. Make this statement
// a comment if you do.
setConnectionProperties(connection); // Set speed etc of connection
UsbEndpoint endpointOut = device.getInterface(1).getEndpoint(1);
UsbEndpoint endpointIn = device.getInterface(1).getEndpoint(0);
connection.bulkTransfer(endpointOut, sendChar, 1, 500); // Send request for data
//
// It takes more than one read to get the data out of the FIFO
// Build up message by polling the FIFO until there is nothing left
// This has taken a lot of fiddling about to make it work. The baud
// and the timeouts have to be just so.
// (9600 and 200 work here but why who knows (or cares))
//
int k = 0;
char[] labelStr = new char[20];
int flag = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE;
int bytesReceived = connection.bulkTransfer(endpointIn, getChar, 200, 200);
while (bytesReceived > 0)
{
for (int j = 0; j < bytesReceived; j++)
{
labelStr[k++] = (char) getChar[j];
if (getChar[j] == 13) // Carriage return
{
String label = String.valueOf(labelStr, 1, k - 1);
SpannableString spanLabel = new SpannableString(label);
spanLabel.setSpan(new RelativeSizeSpan(1.0f), 0, spanLabel.length(), flag);
addListener = true;
if (label.contains("Cross Slide"))
{ // Start adding pitches
spanLabel = new SpannableString("Pitch");
spanLabel.setSpan(new ForegroundColorSpan(Color.RED), 0, spanLabel.length(), flag);
addListener = false;
}
if (label.contains("End"))
{ // Start adding lengths
spanLabel = new SpannableString("Length");
spanLabel.setSpan(new ForegroundColorSpan(Color.RED), 0, spanLabel.length(), flag);
addListener = false;
if (startLength == 0) // Avoid the second "End" messages from MCU
startLength = buttonCount;
}
pitchButton[buttonCount].setText(spanLabel);
pitchButton[buttonCount].setId(buttonCount);
if (addListener)
{
pitchButton[buttonCount].setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int buttonIndex;
Button buttonText = (Button) v;
String bt = buttonText.getText().toString();
String message;
if (bt.contains(".")) // On Button press display selected value
{
message = "Pitch ";
buttonIndex = 0;
}
else
{
message = "Length ";
buttonIndex = startLength;
}
message = message + bt;
pitchButton[buttonIndex].setText(message);
pitchButton[buttonIndex].setBackgroundColor(Color.GREEN);
}
});
}
buttonCount++;
k = 0;
}
}
bytesReceived = connection.bulkTransfer(endpointIn, getChar, 200, 200);
}
connection.close();
RelativeLayout.LayoutParams[] params = new RelativeLayout.LayoutParams[100];
RelativeLayout rel = new RelativeLayout(this);
rel.addView(tv);
int leftMargin = 0;
int topMargin = 0;
int lineCount = 0;
for (int i = 0; i < buttonCount - 1; i++)
{
params[i] = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params[i].width = 150;
params[i].height = 50;
if (Math.IEEEremainder(lineCount, 5) == 0) // Put 5 buttons per line
{
topMargin = topMargin + params[i].height;
leftMargin = 0;
}
lineCount++;
if (pitchButton[i].getText().toString().contains("Pitch"))
{
topMargin = topMargin + params[i].height;
leftMargin = 0;
lineCount = 0;
}
if (pitchButton[i].getText().toString().contains("Length"))
{
topMargin = topMargin + params[i].height;
leftMargin = 0;
lineCount = 0;
}
params[i].leftMargin = leftMargin;
leftMargin = leftMargin + params[i].width;
params[i].topMargin = topMargin;
pitchButton[i].setLayoutParams(params[i]);
rel.addView(pitchButton[i]);
}
//
//Add control for setting taper
//
ArrayList<String> taperArray = new ArrayList<String>();
taperArray.add("1");
taperArray.add("2");
taperArray.add("3");
Spinner spinner = new Spinner(this,Spinner.MODE_DIALOG);
spinner.setBackgroundColor(Color.BLUE);
String taperPrompt = "Set Taper Angle";
RelativeLayout.LayoutParams spinnerParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
spinnerParams.width = 50;
spinnerParams.height = 40;
spinnerParams.topMargin = 600;
spinnerParams.leftMargin = 200;
spinner.setPrompt("Select Taper Angle");
spinner.setLayoutParams(spinnerParams);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, taperArray);
spinner.setAdapter(spinnerArrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l)
{
}
public void onNothingSelected(AdapterView<?> adapterView)
{
}
});
RelativeLayout.LayoutParams taperParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
taperParams.width = 200;
taperParams.height = 50;
taperParams.topMargin = 600;
taperParams.leftMargin = 10;
TextView taperView = new TextView(this);
taperView.setLayoutParams(taperParams);
taperView.setText(taperPrompt);
taperView.setTextColor(Color.RED);
taperView.setTextSize(20);
rel.addView(taperView);
rel.addView(spinner);
setContentView(rel);
}
}
public void setConnectionProperties(UsbDeviceConnection connection)
{
connection.controlTransfer(0x40, 0, 0, 0, null, 0, 0);// reset
// mConnection.controlTransfer(0×40,
// 0, 1, 0, null, 0,
// 0);//clear Rx
connection.controlTransfer(0x40, 0, 2, 0, null, 0, 0);// clear Tx
connection.controlTransfer(0x40, 0x02, 0x0000, 0, null, 0, 0);// flow
// control
// none
connection.controlTransfer(0x40, 0x03, 0x4138, 0, null, 0, 0);// baudrate
// 9600 (4138 is 9600, 1A is 115200 0271 is 4800)
connection.controlTransfer(0x40, 0x04, 0x0008, 0, null, 0, 0);// data bit
// 8, parity
// none,
// stop bit
// 1, tx off
}
public void getInterfaceProperties(UsbDevice device, UsbDeviceConnection connection, TextView tv)
{
int interfaceCount = device.getInterfaceCount();
int endPointCount;
for (int i=0; i < interfaceCount-1; i++)
{
if (connection.claimInterface(device.getInterface(i), true)) {
tv.append("\nConnection Interface " + i + " Claim succeeded \n");
UsbInterface interfce = device.getInterface(i);
endPointCount = interfce.getEndpointCount();
tv.append("Endpoint count for Interface " + i + " is " + endPointCount + "\n");
for (int j = 0; j < endPointCount; j++) {
if (interfce.getEndpoint(j).getType() == UsbConstants.USB_ENDPOINT_XFER_INT)
tv.append("Endpoint " + j + " Type is Xfer Int \n");
if (interfce.getEndpoint(j).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)
tv.append("Endpoint " + j + " Type is Bulk Xfer \n");
if (interfce.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_IN)
tv.append("Endpoint " + j + " Direction is IN \n");
if (interfce.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_OUT)
tv.append("Endpoint " + j + " Direction is OUT \n");
tv.append("Max packet size = " + interfce.getEndpoint(j).getMaxPacketSize() + "\n");
}
tv.append("Interface Protocol is " + interfce.getInterfaceProtocol() + "\n");
}
}
}
public void getDeviceProperties(UsbDevice device, UsbManager manager, TextView tv)
{
tv.setTextSize(20);
tv.setTextColor(Color.BLUE);
tv.append("USB Device name = " + device.getDeviceName() + "\n");
tv.append("USB Product Id = " + device.getProductId() + "\n");
tv.append("USB Vendor Id = " + device.getVendorId() + "\n");
tv.append("USB Device Id = " + device.getDeviceId() + "\n");
if (manager.hasPermission(device)) // Can the App access the device ?
{
tv.append("Device Permission = Yes \n");
}
else
{
tv.append("Device Permission = No \n");
}
}
}
I have found the answer – when no USB devices are attached to the phone the message No USB Devices Found could ever be displayed on the screen. By adding the line setContentView(tv) after the line tv.append(“No USB Devices Found”) leaves this message on the screen rather than falling back to the Hello World message. Thank you for looking at it. I would still like to know if it is possible to get rid of the Hello World fragment as it seems totally unnecessary (or maybe it is).
Related
I need to find out if a native linux application window is maximized or minimized in a java program.
I tried using X11.XGetWindowProperty() and I get some results also, but I cant make out any useful information in it.
I am using JNA 4.2.1, Java 8 update72 on Ubuntu 14.04 LTS. Any pointers will be very helpful. Thanks in advance to all.
[Edit]
I have the code below which gives me the result I need. But the result is not same for every invocation. The atoms which are returned for the window vary within invocations. Is there any other reliable way to get the window state?
private static X11 x11 = X11.INSTANCE;
private static Display dispy = x11.XOpenDisplay(null);
public static void main(String[] args) {
try {
X11.Atom[] atoms = getAtomProperties(
bytesToInt(getProperty(X11.XA_ATOM, X11.INSTANCE.XInternAtom(dispy, "_NET_WM_STATE", false))));
boolean hidden = false;
boolean vmax = false;
boolean hmax = false;
for (int i = 0; i < atoms.length; i++) {
X11.Atom atom = atoms[i];
if (atom == null)
continue;
String atomName = X11.INSTANCE.XGetAtomName(dispy, atom);
if ("_NET_WM_STATE_HIDDEN".equals(atomName)) {
hidden = true;
} else if ("_NET_WM_STATE_MAXIMIZED_VERT".equals(atomName)) {
vmax = true;
} else if ("_NET_WM_STATE_MAXIMIZED_HORZ".equals(atomName)) {
hmax = true;
}
}
if (hidden)
System.out.println("Window minimized");
else if (vmax && hmax && !hidden)
System.out.println("Window maximized");
else
System.out.println("Window normal");
} catch (X11Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static X11.Atom[] getAtomProperties(int[] ids) {
X11.Atom[] atoms = new X11.Atom[ids.length];
for (int i = 0; i < ids.length; i++) {
if (ids[i] == 0)
continue;
atoms[i] = new X11.Atom(ids[i]);
}
return atoms;
}
private static int[] bytesToInt(byte[] prop) {
if (prop == null)
return null;
int[] res = new int[prop.length / 4];
for (int i = 0; i < res.length; i++) {
res[i] = ((prop[i * 4 + 3] & 0xff) << 24) | ((prop[i * 4 + 2] & 0xff) << 16) | ((prop[i * 4 + 1] & 0xff) << 8)
| ((prop[i * 4 + 0] & 0xff));
if (res[i] != 0)
continue;
}
return res;
}
private static byte[] getProperty(X11.Atom xa_prop_type, X11.Atom xa_prop_name) throws X11Exception {
X11.Window window = new X11.Window(73400355);
X11.AtomByReference xa_ret_type_ref = new X11.AtomByReference();
IntByReference ret_format_ref = new IntByReference();
NativeLongByReference ret_nitems_ref = new NativeLongByReference();
NativeLongByReference ret_bytes_after_ref = new NativeLongByReference();
PointerByReference ret_prop_ref = new PointerByReference();
NativeLong long_offset = new NativeLong(0);
NativeLong long_length = new NativeLong(4096 / 4);
/*
* MAX_PROPERTY_VALUE_LEN / 4 explanation (XGetWindowProperty manpage):
*
* long_length = Specifies the length in 32-bit multiples of the data to be retrieved.
*/
if (x11.XGetWindowProperty(dispy, window, xa_prop_name, long_offset, long_length, false, xa_prop_type, xa_ret_type_ref,
ret_format_ref, ret_nitems_ref, ret_bytes_after_ref, ret_prop_ref) != X11.Success) {
String prop_name = x11.XGetAtomName(dispy, xa_prop_name);
throw new X11Exception("Cannot get " + prop_name + " property.");
}
X11.Atom xa_ret_type = xa_ret_type_ref.getValue();
Pointer ret_prop = ret_prop_ref.getValue();
if (xa_ret_type == null) {
// the specified property does not exist for the specified window
return null;
}
if (xa_ret_type == null || xa_prop_type == null || !xa_ret_type.toNative().equals(xa_prop_type.toNative())) {
x11.XFree(ret_prop);
String prop_name = x11.XGetAtomName(dispy, xa_prop_name);
throw new X11Exception("Invalid type of " + prop_name + " property");
}
int ret_format = ret_format_ref.getValue();
long ret_nitems = ret_nitems_ref.getValue().longValue();
// null terminate the result to make string handling easier
int nbytes;
if (ret_format == 32)
nbytes = Native.LONG_SIZE;
else if (ret_format == 16)
nbytes = Native.LONG_SIZE / 2;
else if (ret_format == 8)
nbytes = 1;
else if (ret_format == 0)
nbytes = 0;
else
throw new X11Exception("Invalid return format");
int length = Math.min((int) ret_nitems * nbytes, 4096);
byte[] ret = ret_prop.getByteArray(0, length);
x11.XFree(ret_prop);
return ret;
}
I wanna write a Snake game with javaFX , but there is exception that I don't know about and I want to know how to fix it. ( i know it's not complete yet )
and I want to know , the class that extends Application ( with start override )
is exactly the main in other programs?
as you see , here is not static void main BC I didn't need, but if i want to add main where shoud i do?
it's the Exeption...
Exception in Application constructor
Exception in thread "main" java.lang.NoSuchMethodException: Main_Snake.main([Ljava.lang.String;)
at java.lang.Class.getMethod(Class.java:1819)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:125)
and my code is :
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.util.ArrayList;
/**
* Created by Nadia on 1/5/2016.
*/
public class Main_Snake extends Application{
Snake snake = new Snake();
Apple apple = new Apple();
Canvas canvas = new Canvas(800, 600);
boolean goNorth = true, goSouth, goWest, goEast;
int x, y = 0; // marbut be apple
boolean j = false;
// int gm_ov = 0; // vase game over shodan
ArrayList<Integer> X = new ArrayList<Integer>();
ArrayList<Integer> Y = new ArrayList<>();
#Override
public void start(Stage primaryStage) throws Exception {
BorderPane b = new BorderPane(canvas);
Scene scene = new Scene(b, 800, 600);
primaryStage.setScene(scene);
primaryStage.show();
//KeyBoard(scene);
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent e) {
switch (e.getText()) {
case "w":
if (!goSouth) {
goNorth = true;
goSouth = false;
goWest = false;
goEast = false;
}
break;
case "s":
if (!goNorth) {
goSouth = true;
goNorth = false;
goWest = false;
goEast = false;
}
break;
case "a":
if (!goEast) {
goWest = true;
goEast = false;
goSouth = false;
goNorth = false;
}
break;
case "d":
if (!goWest) {
goEast = true;
goWest = false;
goSouth = false;
goNorth = false;
}
break;
}
}
});
play();
}
public void play(){
AnimationTimer timer = new AnimationTimer() {
private long lastUpdate = 0;
#Override
public void handle(long now) {
if (now - lastUpdate >= 40_000_000) { // payin avordane sor#
snake.pos_S(); // har bar mar rasm mishe bad az move va ye sib ba X,Y khodesh rasm mishe tu tabe move dar morede tabe Point hast
apple.pos_A();
apple.random_Pos();
snake.Move();
lastUpdate = now; // sor#
}
}
};
timer.start();
}
/* public void KeyBoard(Scene scene) {
}*/
}
class Apple extends Main_Snake {
public void random_Pos() {
if (j == false) { // ye sib bede ke ru mar nabashe ( rasmesh tu rasme )
do {
x = (int) (Math.random() * 790 + 1);
y = (int) (Math.random() * 590 + 1);
} while (X.indexOf(x) != -1 && Y.get(X.indexOf(x)) == y || x % 10 != 0 || y % 10 != 0);
/*inja aval chek kardam tu araylist x hast ya na ag bud sharte aval ok hala sharte do ke tu Y ham mibinim tu hamun shomare khune
y barabare y mast ag bud pas ina bar ham montabeghan va sharte dovom ham ok . 2 sharte akhar ham vase ine ke mare ma faghat mazrab
haye 10 and pas ta vaghti in se shart bargharare jahayie ke ma nemikhaym va hey jaye dg mide*/
j = true;
}
}
public void pos_A() {
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.BLACK);
gc.fillRect(x, y, 10, 10);
}
public void Point() {
if (X.get(0) == x && Y.get(0) == y) {
j = false;
}
}
}
class Snake extends Main_Snake {
Snake(){ //cunstructor
X.add(400);
Y.add(300);
X.add(400);
Y.add(310);
X.add(400);
Y.add(320);
X.add(400);
Y.add(330);
X.add(400);
Y.add(340);
}
public void pos_S(){
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
apple.pos_A();
// keshidane mar (body yeki ezafe tar az adade morabaA mide)
for (int i = X.size() - 1; i >= 0; i--)
gc.fillRect(X.get(i), Y.get(i), 10, 10);
}
public void Move(){
int Px = X.get(X.size() - 1);
int Py = Y.get(Y.size() - 1);
for (int z = X.size() - 1 ; z > 0 ; z--){
X.remove(z);
X.add(z , X.get(z-1) ) ;
Y.remove(z);
Y.add(z , Y.get(z-1) ) ;
}
if (goNorth) {
Y.add(0 , Y.get(0) - 10);
Y.remove(1);
}
if (goSouth) {
Y.add(0 , Y.get(0) + 10);
Y.remove(1);
}
if (goEast) {
X.add(0 , X.get(0) + 10);
X.remove(1);
}
if (goWest) {
X.add(0 , X.get(0) - 10);
X.remove(1);
}
apple.Point(); // emtiaz gerefte
if ( j == false) {
X.add(Px);
Y.add(Py);
}
if ( X.get(0) > 790 ){
X.remove(0);
X.add(0 , 0);
}
if ( X.get(0) < 0 ){
X.remove(0);
X.add(0 , 800);
}
if ( Y.get(0) > 590 ){
Y.remove(0);
Y.add(0 , 0);
}
if ( Y.get(0) < 0 ){
Y.remove(0);
Y.add(0 , 600);
}
}
}
The standard Oracle Java Runtime Environment can execute Application subclasses directly from the command line, even if they do not contain a main method. So assuming you are using a standard JRE, from the command line you can execute
java Main_Snake
and it will run (assuming no other errors, etc).
Other environments, and most IDEs, don't support this execution mode, so if you want to run in those environments (including running in Eclipse, for example), you need a main(...) method which launches your JavaFX application. So just add
public static void main(String[] args) {
launch(args);
}
to the Main_Snake class.
In my code attached, I am trying to use two Android WebViews (webView1 and webView2) to display a javaScript enabled menu inside webView1 and a page showing the result of menu-click triggered in webView1 inside webView2.
As the code show, I am dynamically trying to fit the WebViews dynamically to the target screen by calculating my own initial scales and then plug the computed scales into the WebViews during Run-time.
Here is the problem I would like to ask for your assistance... When I click on the menu items in webView1 in order to show the result in webView2, extra horizontal white spaces (size of the horizontal white spaces are about the same width of the target screen, but the horizontal scroll bar is about the witdh of webView2) are shown in webView2. The white spaces appears randomly (i.e. The white spaces somtimes appears sometimes not).
I have tried adding function calls to clear the WebViews cache. The horiztonal white spaces appears less frequently in webView2, but the problem still persists.
It is interesting to know that this only happen in Android 4.0+ devices and does not happen in devices whose OS is Android 3 and below. We have tested this using Samsung Galaxy Notes II and Samsung Galaxy Tab 10.1 for Android 4 devices. We tested on Huawei Ideos U8150 for Android 2.2 device and a no brand device for Android 3 device.
I have set the minimum SDK target to API 8 and the maximum SDK target to API 15 when compiling the Android project.
I have already done extensive research on this problem in the Internet (including in StackOverflow) for 2 days, but I could not find any post similar to my problem's context.
I would like to know how to remove the horizontal white spaces in webView2. Please assists.
Thanks.
Please see code listing below:
package com.xyz.XyzPkg;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ScrollView;
import android.graphics.Bitmap;
public class OpenxyzActivitiesActivity extends Activity implements OnClickListener {
private final static int ID_BTNBACK = 987654321;
private final static int ID_BTNACTIVITY_UI1 = 999977777;
private final static int ID_BTNACTIVITY_UI2 = 999977776;
WebView webView1;
WebView webView2;
protected String TAG = OpenxyzActivitiesActivity.class.getSimpleName();
ImageButton btnBack;
int screenwidth = 0;
float fOrigWidth1 = 0.0f; //180.0f;
float fOrigWidth2 = 0.0f; //300.0f;
float fWeightSum = 0.0f;
float fWeight1 = 0.0f;
float fWeight2 = 0.0f;
float fWindowWidth = 0.0f;
float fWindowHeight = 0.0f;
float fWindowDensity = 0.0f;
float fInitScale1 = 0.0f;
float fInitScale2 = 0.0f;
int fViewportSize1 = 0;
int fViewportSize2 = 0;
int delta = 0;
boolean bChosenWidth = false;
String sUrlBase = "http://test.xyz.com/parents";
LinearLayout LinearLayout1;
ImageButton btnActivityUI1;
ImageButton btnActivityUI2;
FrameLayout frameLayout0;
LinearLayout LinearLayout4;
final int ID_WEBVIEW1 = 987654321;
#SuppressLint("SetJavaScriptEnabled")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
webView1 = new WebView(this);
webView1.setId(ID_WEBVIEW1);
webView1.getSettings().setJavaScriptEnabled(true);
webView2 = new WebView(this);
//new InitTask().execute(new String[]{sUrlBase + "/activities/sendActvtData.php"});
new InitTask().execute(new String[]{sUrlBase + "/activities/sendActvtData.php"});
}
//public class InitThread implements Runnable{
private class InitTask extends AsyncTask<String, Void, ArrayList<Float> >{
#Override
protected void onPostExecute(ArrayList<Float> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
frameLayout0 = new FrameLayout(getApplicationContext());
LinearLayout.LayoutParams oFrameLayout0Params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
frameLayout0.setLayoutParams(oFrameLayout0Params);
LinearLayout LinearLayout0 = new LinearLayout(getApplicationContext());
LinearLayout0.setWeightSum(100.0f);
LinearLayout LinearLayout1 = new LinearLayout(getApplicationContext());
LinearLayout.LayoutParams oLinearLayout1Params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
LinearLayout1.setLayoutParams(oLinearLayout1Params);
LinearLayout1.setWeightSum(100.0f);
//BEGIN: Setting up Window Size -- Change Windows Size in UI Thread
LayoutParams oLayoutParams = (LayoutParams)LinearLayout1.getLayoutParams();
oLayoutParams.width = (int)fWindowWidth;
oLayoutParams.height = (int)fWindowHeight;
LinearLayout1.setLayoutParams(oLayoutParams);
LinearLayout linearLayoutDummyProduct = new LinearLayout(getApplicationContext());
android.widget.LinearLayout.LayoutParams linearLayoutDummyProductLayoutParams = new android.widget.LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
linearLayoutDummyProduct.setLayoutParams(linearLayoutDummyProductLayoutParams);
oLayoutParams = (LayoutParams)linearLayoutDummyProduct.getLayoutParams();
LinearLayout linearLayoutDummyProduct2 = new LinearLayout(getApplicationContext());
linearLayoutDummyProduct2.setLayoutParams(linearLayoutDummyProductLayoutParams);
oLayoutParams = (LayoutParams)linearLayoutDummyProduct2.getLayoutParams();
float fDummy1Weight = 0.0f;
float fFrameLayoutWeight = 0.0f;
if (bChosenWidth)
{
LinearLayout0.setOrientation(LinearLayout.VERTICAL);
fDummy1Weight = 100.0f*delta/fWindowHeight;
linearLayoutDummyProductLayoutParams = new android.widget.LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, fDummy1Weight);
fFrameLayoutWeight = 100.0f-2*fDummy1Weight;
oFrameLayout0Params = new android.widget.LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, fFrameLayoutWeight);
Log.d(TAG, "fDummy1Weight = 100.0f*delta/fWindowHeight;");
}
else{
LinearLayout0.setOrientation(LinearLayout.HORIZONTAL);
fDummy1Weight = 100.0f*delta/fWindowWidth;
linearLayoutDummyProductLayoutParams = new android.widget.LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, fDummy1Weight);
fFrameLayoutWeight = 100.0f-2*fDummy1Weight;
oFrameLayout0Params = new android.widget.LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, fFrameLayoutWeight);
Log.d(TAG, "fDummy1Weight = 100.0f*delta/fWindowWidth;");
}
Log.d(TAG, "fDummy1Weight = " + fDummy1Weight);
Log.d(TAG, "fFrameLayoutWeight = " + fFrameLayoutWeight);
linearLayoutDummyProduct.setLayoutParams(linearLayoutDummyProductLayoutParams);
linearLayoutDummyProduct2.setLayoutParams(linearLayoutDummyProductLayoutParams);
frameLayout0.setLayoutParams(oFrameLayout0Params);
//END: Setting up Window Size
float fWeightSum = LinearLayout1.getWeightSum();
float fWidthSum = fOrigWidth1 + fOrigWidth2;
fWeight1 = fOrigWidth1 / fWidthSum * fWeightSum;
fWeight2 = fOrigWidth2 / fWidthSum * fWeightSum;
fViewportSize1 = screenwidth * (int)fOrigWidth1 / (int)(fOrigWidth1+fOrigWidth2);
fViewportSize2 = screenwidth * (int)fOrigWidth2 / (int)(fOrigWidth1+fOrigWidth2);
Log.d(TAG, "onPostExecute: fViewportSize1=" + fViewportSize1);
Log.d(TAG, "onPostExecute: fViewportSize2=" + fViewportSize2);
android.widget.LinearLayout.LayoutParams oLinearLayoutParams1 = new android.widget.LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, fWeight1);
android.widget.LinearLayout.LayoutParams oLinearLayoutParams2 = new android.widget.LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, fWeight2);
webView1.setLayoutParams(oLinearLayoutParams1);
webView2.setLayoutParams(oLinearLayoutParams2);
oLinearLayoutParams1 = (android.widget.LinearLayout.LayoutParams)webView1.getLayoutParams();
oLinearLayoutParams2 = (android.widget.LinearLayout.LayoutParams)webView2.getLayoutParams();
webView2.getSettings().setUseWideViewPort(false);
LinearLayout1.addView(webView1);
LinearLayout1.addView(webView2);
Log.d(TAG, "onPostExecute: fWeightSum=" + fWeightSum);
Log.d(TAG, "onPostExecute: fWidthSum=" + fWidthSum);
Log.d(TAG, "onPostExecute: oLinearLayoutParams1.weight=" + oLinearLayoutParams1.weight);
Log.d(TAG, "onPostExecute: oLinearLayoutParams2.weight=" + oLinearLayoutParams2.weight);
webView1.setInitialScale((int)fInitScale1);
webView2.setInitialScale((int)fInitScale2);
webView1.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView2.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView1.setPersistentDrawingCache(ViewGroup.PERSISTENT_NO_CACHE);
webView1.clearCache(true);
webView1.clearHistory();
webView1.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//webView1.loadUrl(sUrlBase + "/activities/?lang=en");
String sWebView1Url = sUrlBase + "/activities/?lang=en&viewport_width="+fViewportSize1 + "&viewport_initial_scale=" + fInitScale1*0.01f;
webView1.loadUrl(sWebView1Url);
Log.d(TAG, "onPostExecute(): sWebView1Url: " + sWebView1Url);
webView1.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url){
//webView1.stopLoading();
url = url + "&viewport_width=" + fViewportSize2 + "&viewport_initial_scale=" + fInitScale2*0.01f;
Log.d(TAG, "setWebViewClient: CHK000: url: " + url);
if (view.getId() == ID_WEBVIEW1)
{
Log.d(TAG, "ID_WEBVIEW1: " + ID_WEBVIEW1);
Log.d(TAG, "WebView1 stopped loading");
//view.stopLoading();
webView1.setPersistentDrawingCache(ViewGroup.PERSISTENT_NO_CACHE);
webView1.clearCache(true);
webView1.clearHistory();
webView2.setPersistentDrawingCache(ViewGroup.PERSISTENT_NO_CACHE);
webView2.clearView();
webView2.clearCache(true);
webView2.clearHistory();
Map<String, String> noCacheHeaders = new HashMap<String, String>(2);
noCacheHeaders.put("Pragma", "no-cache");
noCacheHeaders.put("Cache-Control", "no-cache");
// webView2.getSettings().setAppCacheMaxSize(0);
// webView2.getSettings().setAppCacheEnabled(false);
webView2.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView2.loadUrl(url, noCacheHeaders);
// webView2.loadUrl(url);
Log.d(TAG , "shouldOverrideUrlLoading(): fInitScale1: " + fInitScale1);
Log.d(TAG , "shouldOverrideUrlLoading(): fInitScale2: " + fInitScale2);
Log.d(TAG , "shouldOverrideUrlLoading(): webView1.getScale(): " + webView1.getScale());
Log.d(TAG , "shouldOverrideUrlLoading(): webView2.getScale(): " + webView2.getScale());
Log.d(TAG, "shouldOverrideUrlLoading(): ((LinearLayout.LayoutParams)webView2.getLayoutParams()).weight: " + ((LinearLayout.LayoutParams)webView2.getLayoutParams()).weight);
Log.d(TAG , "shouldOverrideUrlLoading(): url: " + url);
webView1.setInitialScale((int)fInitScale1);
webView2.setInitialScale((int)fInitScale2);
}
else
{
Log.d(TAG, "Other Web View triggered shouldOverrideUrlLoading");
}
return true;
}
});
webView2.setPersistentDrawingCache(ViewGroup.PERSISTENT_NO_CACHE);
webView2.clearView();
webView2.clearCache(true);
webView2.clearHistory();
// Map<String, String> noCacheHeaders = new HashMap<String, String>(2);
// noCacheHeaders.put("Pragma", "no-cache");
// noCacheHeaders.put("Cache-Control", "no-cache");
// webView2.getSettings().setAppCacheMaxSize(0);
// webView2.getSettings().setAppCacheEnabled(false);
webView2.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
// webView2.loadUrl("http://parents.xyz.com/activities/?catg=coloring", noCacheHeaders);
//webView2.loadUrl(sUrlBase + "/activities/?catg=coloring");
webView2.loadUrl(sUrlBase + "/activities/?catg=coloring&viewport_width="+fViewportSize2 + "&viewport_initial_scale=" + fInitScale1*0.01f);
//webView2.getSettings().setTextSize(t)
frameLayout0.addView(LinearLayout1);
LinearLayout LinearLayout2 = new LinearLayout(getApplicationContext());
LinearLayout.LayoutParams oLinearLayout2Params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
LinearLayout2.setLayoutParams(oLinearLayout2Params);
LinearLayout2.setWeightSum(100.0f);
LinearLayout2.setOrientation(LinearLayout.HORIZONTAL);
frameLayout0.addView(LinearLayout2);
ImageView btnInvisible0 = new ImageView(getApplicationContext());
LinearLayout.LayoutParams btnInvisible0Params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 90.0f);
btnInvisible0.setLayoutParams(btnInvisible0Params);
LinearLayout LinearLayout3 = new LinearLayout(getApplicationContext());
LinearLayout.LayoutParams oLinearLayout3Params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 10.0f);
LinearLayout3.setLayoutParams(oLinearLayout3Params);
LinearLayout3.setWeightSum(100.0f);
LinearLayout3.setOrientation(LinearLayout.VERTICAL);
btnBack = new ImageButton(getApplicationContext());
btnBack.setId(ID_BTNBACK);
LinearLayout.LayoutParams btnBackParams = new LinearLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 0, 18.0f);
btnBack.setLayoutParams(btnBackParams);
btnBack.setScaleType(ScaleType.FIT_XY);
btnBack.post(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
btnBack.setBackgroundDrawable((Drawable)getResources().getDrawable(R.drawable.btn_back));
}
});
btnBack.setOnClickListener(OpenxyzActivitiesActivity.this);
ImageView btnInvisible1 = new ImageView(getApplicationContext());
LinearLayout.LayoutParams btnInvisible1Params = new LinearLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 0, 82.0f);
btnInvisible1.setLayoutParams(btnInvisible1Params);
LinearLayout4 = new LinearLayout(getApplicationContext());
LinearLayout.LayoutParams oLinearLayout4Params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
LinearLayout4.setLayoutParams(oLinearLayout4Params);
LinearLayout4.setWeightSum(100.0f);
LinearLayout4.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout4.setOnClickListener(OpenxyzActivitiesActivity.this);
frameLayout0.addView(LinearLayout4);
btnActivityUI1 = new ImageButton(getApplicationContext());
btnActivityUI1.setId(ID_BTNACTIVITY_UI1);
LinearLayout.LayoutParams btnActivityUI1Params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 37.5f);
btnActivityUI1.setLayoutParams(btnActivityUI1Params);
btnActivityUI1.setScaleType(ScaleType.FIT_CENTER);
btnActivityUI1.post(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
btnActivityUI1.setImageDrawable((Drawable)getResources().getDrawable(R.drawable.activityui_300));
}
});
btnActivityUI1.setOnClickListener(OpenxyzActivitiesActivity.this);
btnActivityUI2 = new ImageButton(getApplicationContext());
btnActivityUI2.setId(ID_BTNACTIVITY_UI2);
LinearLayout.LayoutParams btnActivityUI2Params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 62.5f);
btnActivityUI2.setLayoutParams(btnActivityUI2Params);
btnActivityUI2.setScaleType(ScaleType.FIT_CENTER);
btnActivityUI2.post(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
btnActivityUI2.setImageDrawable((Drawable)getResources().getDrawable(R.drawable.activityui_500));
}
});
btnActivityUI2.setOnClickListener(OpenxyzActivitiesActivity.this);
LinearLayout4.addView(btnActivityUI1);
LinearLayout4.addView(btnActivityUI2);
LinearLayout3.addView(btnBack);
LinearLayout3.addView(btnInvisible1);
LinearLayout2.addView(btnInvisible0);
LinearLayout2.addView(LinearLayout3);
LinearLayout0.addView(linearLayoutDummyProduct);
LinearLayout0.addView(frameLayout0);
LinearLayout0.addView(linearLayoutDummyProduct2);
setContentView(LinearLayout0);
}
#Override
protected ArrayList<Float> doInBackground(String... params) {
// TODO Auto-generated method stub
Log.d(InitTask.class.getSimpleName() , "params[0]: " + params[0]);
return callHttp(params[0]);
}
private ArrayList<Float> callHttp(String url) {
ArrayList<Float> alResult = new ArrayList<Float>();
//BEGIN HTTP Request...
//String url = "http://parents.xyz.com/activities/sendActvtData.php";
Log.d(InitTask.class.getSimpleName() , "url: " + url);
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
Log.d(TAG , "CHK000");
// Execute the request
HttpResponse response;
String result = "";
try {
Log.d(TAG , "CHK010");
response = httpclient.execute(httpget);
// Examine the response status
Log.d(TAG , "CHK020");
Log.i(TAG,response.getStatusLine().toString());
Log.d(TAG , "CHK030");
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
Log.d(TAG , "Is entity null? " + ((entity == null)?"YES":"NO") );
Log.d(TAG , "CHK040");
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
result= convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
}
Log.d(TAG , "CHK100");
}
catch (ClientProtocolException cpe){
Log.e(TAG , cpe.getMessage());
}
catch (IOException ioe){
Log.e(TAG , ioe.getMessage());
}
catch (Exception e) {
Log.d(TAG , "CHK EXP");
Log.d(TAG, e.toString());
}
//END HTTP Request...
Log.d(TAG, "http result: " + result);
String[] ActvData = result.split(",");
fOrigWidth1 = Float.parseFloat(ActvData[0]);
fOrigWidth2 = Float.parseFloat(ActvData[1]);
Log.d(TAG, "fOrigWidth1: " + fOrigWidth1);
Log.d(TAG, "fOrigWidth2: " + fOrigWidth2);
//BEGIN: Setting up Window Size -- Calculation
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
screenwidth = metrics.widthPixels;
int screenheight = metrics.heightPixels;
Log.d(TAG, "screenwidth: " + screenwidth);
Log.d(TAG, "screenheight: " + screenheight);
//800x480
float heightFactor = (float)screenheight / 480f;
float widthFactor = (float)screenwidth / 800f;
float chosenFactor = 1f;
bChosenWidth = false;
if (widthFactor < heightFactor)
{
bChosenWidth = true;
chosenFactor = widthFactor;
}
else
{
bChosenWidth = false;
chosenFactor = heightFactor;
}
int newHeight = (int)((float)480.0 * (float)chosenFactor);
int newWidth = (int)((float)800.0 * (float)chosenFactor);
Log.d(TAG, "heightFactor: " + heightFactor);
Log.d(TAG, "widthFactor: " + widthFactor);
Log.d(TAG, "newHeight: " + newHeight);
Log.d(TAG, "newWidth: " + newWidth);
delta = 0;
if (bChosenWidth)
{
delta = (screenheight - newHeight) / 2;
}
else{
delta = (screenwidth - newWidth) / 2;
}
Log.d(TAG, "delta: " + delta);
//END: Setting up Window Size -- Calculation
fWindowWidth = newWidth;
fWindowHeight = newHeight;
fWindowDensity = (float)metrics.density;
fWeight1 = fOrigWidth1;
fWeight2 = fOrigWidth2;
fWeightSum = fWeight1 + fWeight2;
Log.d(TAG , "fWeight1: " + fWeight1);
Log.d(TAG , "fWeight2: " + fWeight2);
fInitScale1 = 0.0f;
fInitScale2 = 0.0f;
fInitScale1 = fInitScale2 = fWindowWidth / fWeightSum * 100;
Log.d(TAG , "fWindowWidth: " + fWindowWidth);
Log.d(TAG , "fWindowHeight: " + fWindowHeight);
Log.d(TAG , "fWindowDensity: " + fWindowDensity);
Log.d(TAG , "fInitScale1: " + fInitScale1);
Log.d(TAG , "fInitScale2: " + fInitScale2);
Log.d(TAG , "CHK200");
return alResult;
}
private String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case ID_BTNBACK:
Intent myIntent = new Intent();
setResult(Activity.RESULT_OK, myIntent);
finish();
break;
case ID_BTNACTIVITY_UI1: case ID_BTNACTIVITY_UI2:
LinearLayout4.setClickable(false);
frameLayout0.removeView(LinearLayout4);
break;
}
}
}
i have a working safari extension and i able to install it manually by dragging it on safari web browser. i want to know how can i install it programmatically.
i have done this for firefox, chrome and IE.
in firefox just copy your .xpi file to this folder ("C:\Users\admin\AppData\Roaming\Mozilla\Firefox\Profiles\xxx.default\extensions") in windows 7 and your extension will get installed.
and in chrome you have to write these registry keys
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Google\Chrome\Extensions\dlilbimladfdhkfbbcbjjnbleakbogef]
"version"="3.6"
"path"="C:\\extension.crx"
but in safari when i copy my .safariextz file to this folder "C:\Users\admin\AppData\Local\Apple Computer\Safari\Extensions" than extension not get installed.
can anybody guide me how can i do this.
In the folder:
~\Users\\AppData\Local\Apple Computer\Safari\Extensions
there is a file named Extensions.plist you will also need to add an entry for your extension in this file.
Extension.plist in "~\Users\AppData\Local\Apple Computer\Safari\Extensions" folder is a binary file. for read and add an entry we can use this class.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace PlistCS
{
public static class Plist
{
private static List<int> offsetTable = new List<int>();
private static List<byte> objectTable = new List<byte>();
private static int refCount;
private static int objRefSize;
private static int offsetByteSize;
private static long offsetTableOffset;
#region Public Functions
public static object readPlist(string path)
{
using (FileStream f = new FileStream(path, FileMode.Open, FileAccess.Read))
{
return readPlist(f);
}
}
public static object readPlistSource(string source)
{
return readPlist(System.Text.Encoding.UTF8.GetBytes(source));
}
public static object readPlist(byte[] data)
{
return readPlist(new MemoryStream(data));
}
public static plistType getPlistType(Stream stream)
{
byte[] magicHeader = new byte[8];
stream.Read(magicHeader, 0, 8);
if (BitConverter.ToInt64(magicHeader, 0) == 3472403351741427810)
{
return plistType.Binary;
}
else
{
return plistType.Xml;
}
}
public static object readPlist(Stream stream, plistType type = plistType.Auto)
{
if (type == plistType.Auto)
{
type = getPlistType(stream);
stream.Seek(0, SeekOrigin.Begin);
}
if (type == plistType.Binary)
{
using (BinaryReader reader = new BinaryReader(stream))
{
byte[] data = reader.ReadBytes((int)reader.BaseStream.Length);
return readBinary(data);
}
}
else
{
using (BinaryReader reader = new BinaryReader(stream))
{
byte[] data = reader.ReadBytes((int)reader.BaseStream.Length);
return readBinary(data);
}
}
}
public static void writeBinary(object value, string path)
{
using (BinaryWriter writer = new BinaryWriter(new FileStream(path, FileMode.Create)))
{
writer.Write(writeBinary(value));
}
}
public static void writeBinary(object value, Stream stream)
{
using (BinaryWriter writer = new BinaryWriter(stream))
{
writer.Write(writeBinary(value));
}
}
public static byte[] writeBinary(object value)
{
offsetTable.Clear();
objectTable.Clear();
refCount = 0;
objRefSize = 0;
offsetByteSize = 0;
offsetTableOffset = 0;
//Do not count the root node, subtract by 1
int totalRefs = countObject(value) - 1;
refCount = totalRefs;
objRefSize = RegulateNullBytes(BitConverter.GetBytes(refCount)).Length;
composeBinary(value);
writeBinaryString("bplist00", false);
offsetTableOffset = (long)objectTable.Count;
offsetTable.Add(objectTable.Count - 8);
offsetByteSize = RegulateNullBytes(BitConverter.GetBytes(offsetTable[offsetTable.Count - 1])).Length;
List<byte> offsetBytes = new List<byte>();
offsetTable.Reverse();
for (int i = 0; i < offsetTable.Count; i++)
{
offsetTable[i] = objectTable.Count - offsetTable[i];
byte[] buffer = RegulateNullBytes(BitConverter.GetBytes(offsetTable[i]), offsetByteSize);
Array.Reverse(buffer);
offsetBytes.AddRange(buffer);
}
objectTable.AddRange(offsetBytes);
objectTable.AddRange(new byte[6]);
objectTable.Add(Convert.ToByte(offsetByteSize));
objectTable.Add(Convert.ToByte(objRefSize));
var a = BitConverter.GetBytes((long)totalRefs + 1);
Array.Reverse(a);
objectTable.AddRange(a);
objectTable.AddRange(BitConverter.GetBytes((long)0));
a = BitConverter.GetBytes(offsetTableOffset);
Array.Reverse(a);
objectTable.AddRange(a);
return objectTable.ToArray();
}
#endregion
#region Private Functions
private static object readBinary(byte[] data)
{
offsetTable.Clear();
List<byte> offsetTableBytes = new List<byte>();
objectTable.Clear();
refCount = 0;
objRefSize = 0;
offsetByteSize = 0;
offsetTableOffset = 0;
List<byte> bList = new List<byte>(data);
List<byte> trailer = bList.GetRange(bList.Count - 32, 32);
parseTrailer(trailer);
objectTable = bList.GetRange(0, (int)offsetTableOffset);
offsetTableBytes = bList.GetRange((int)offsetTableOffset, bList.Count - (int)offsetTableOffset - 32);
parseOffsetTable(offsetTableBytes);
return parseBinary(0);
}
private static int countObject(object value)
{
int count = 0;
switch (value.GetType().ToString())
{
case "System.Collections.Generic.Dictionary`2[System.String,System.Object]":
Dictionary<string, object> dict = (Dictionary<string, object>)value;
foreach (string key in dict.Keys)
{
count += countObject(dict[key]);
}
count += dict.Keys.Count;
count++;
break;
case "System.Collections.Generic.List`1[System.Object]":
List<object> list = (List<object>)value;
foreach (object obj in list)
{
count += countObject(obj);
}
count++;
break;
default:
count++;
break;
}
return count;
}
private static byte[] writeBinaryDictionary(Dictionary<string, object> dictionary)
{
List<byte> buffer = new List<byte>();
List<byte> header = new List<byte>();
List<int> refs = new List<int>();
for (int i = dictionary.Count - 1; i >= 0; i--)
{
var o = new object[dictionary.Count];
dictionary.Values.CopyTo(o, 0);
composeBinary(o[i]);
offsetTable.Add(objectTable.Count);
refs.Add(refCount);
refCount--;
}
for (int i = dictionary.Count - 1; i >= 0; i--)
{
var o = new string[dictionary.Count];
dictionary.Keys.CopyTo(o, 0);
composeBinary(o[i]);//);
offsetTable.Add(objectTable.Count);
refs.Add(refCount);
refCount--;
}
if (dictionary.Count < 15)
{
header.Add(Convert.ToByte(0xD0 | Convert.ToByte(dictionary.Count)));
}
else
{
header.Add(0xD0 | 0xf);
header.AddRange(writeBinaryInteger(dictionary.Count, false));
}
foreach (int val in refs)
{
byte[] refBuffer = RegulateNullBytes(BitConverter.GetBytes(val), objRefSize);
Array.Reverse(refBuffer);
buffer.InsertRange(0, refBuffer);
}
buffer.InsertRange(0, header);
objectTable.InsertRange(0, buffer);
return buffer.ToArray();
}
private static byte[] composeBinaryArray(List<object> objects)
{
List<byte> buffer = new List<byte>();
List<byte> header = new List<byte>();
List<int> refs = new List<int>();
for (int i = objects.Count - 1; i >= 0; i--)
{
composeBinary(objects[i]);
offsetTable.Add(objectTable.Count);
refs.Add(refCount);
refCount--;
}
if (objects.Count < 15)
{
header.Add(Convert.ToByte(0xA0 | Convert.ToByte(objects.Count)));
}
else
{
header.Add(0xA0 | 0xf);
header.AddRange(writeBinaryInteger(objects.Count, false));
}
foreach (int val in refs)
{
byte[] refBuffer = RegulateNullBytes(BitConverter.GetBytes(val), objRefSize);
Array.Reverse(refBuffer);
buffer.InsertRange(0, refBuffer);
}
buffer.InsertRange(0, header);
objectTable.InsertRange(0, buffer);
return buffer.ToArray();
}
private static byte[] composeBinary(object obj)
{
byte[] value;
switch (obj.GetType().ToString())
{
case "System.Collections.Generic.Dictionary`2[System.String,System.Object]":
value = writeBinaryDictionary((Dictionary<string, object>)obj);
return value;
case "System.Collections.Generic.List`1[System.Object]":
value = composeBinaryArray((List<object>)obj);
return value;
case "System.Byte[]":
value = writeBinaryByteArray((byte[])obj);
return value;
case "System.Double":
value = writeBinaryDouble((double)obj);
return value;
case "System.Int32":
value = writeBinaryInteger((int)obj, true);
return value;
case "System.String":
value = writeBinaryString((string)obj, true);
return value;
case "System.DateTime":
value = writeBinaryDate((DateTime)obj);
return value;
case "System.Boolean":
value = writeBinaryBool((bool)obj);
return value;
default:
return new byte[0];
}
}
public static byte[] writeBinaryDate(DateTime obj)
{
List<byte> buffer = new List<byte>(RegulateNullBytes(BitConverter.GetBytes(PlistDateConverter.ConvertToAppleTimeStamp(obj)), 8));
buffer.Reverse();
buffer.Insert(0, 0x33);
objectTable.InsertRange(0, buffer);
return buffer.ToArray();
}
public static byte[] writeBinaryBool(bool obj)
{
List<byte> buffer = new List<byte>(new byte[1] { (bool)obj ? (byte)9 : (byte)8 });
objectTable.InsertRange(0, buffer);
return buffer.ToArray();
}
private static byte[] writeBinaryInteger(int value, bool write)
{
List<byte> buffer = new List<byte>(BitConverter.GetBytes((long)value));
buffer = new List<byte>(RegulateNullBytes(buffer.ToArray()));
while (buffer.Count != Math.Pow(2, Math.Log(buffer.Count) / Math.Log(2)))
buffer.Add(0);
int header = 0x10 | (int)(Math.Log(buffer.Count) / Math.Log(2));
buffer.Reverse();
buffer.Insert(0, Convert.ToByte(header));
if (write)
objectTable.InsertRange(0, buffer);
return buffer.ToArray();
}
private static byte[] writeBinaryDouble(double value)
{
List<byte> buffer = new List<byte>(RegulateNullBytes(BitConverter.GetBytes(value), 4));
while (buffer.Count != Math.Pow(2, Math.Log(buffer.Count) / Math.Log(2)))
buffer.Add(0);
int header = 0x20 | (int)(Math.Log(buffer.Count) / Math.Log(2));
buffer.Reverse();
buffer.Insert(0, Convert.ToByte(header));
objectTable.InsertRange(0, buffer);
return buffer.ToArray();
}
private static byte[] writeBinaryByteArray(byte[] value)
{
List<byte> buffer = new List<byte>(value);
List<byte> header = new List<byte>();
if (value.Length < 15)
{
header.Add(Convert.ToByte(0x40 | Convert.ToByte(value.Length)));
}
else
{
header.Add(0x40 | 0xf);
header.AddRange(writeBinaryInteger(buffer.Count, false));
}
buffer.InsertRange(0, header);
objectTable.InsertRange(0, buffer);
return buffer.ToArray();
}
private static byte[] writeBinaryString(string value, bool head)
{
List<byte> buffer = new List<byte>();
List<byte> header = new List<byte>();
foreach (char chr in value.ToCharArray())
buffer.Add(Convert.ToByte(chr));
if (head)
{
if (value.Length < 15)
{
header.Add(Convert.ToByte(0x50 | Convert.ToByte(value.Length)));
}
else
{
header.Add(0x50 | 0xf);
header.AddRange(writeBinaryInteger(buffer.Count, false));
}
}
buffer.InsertRange(0, header);
objectTable.InsertRange(0, buffer);
return buffer.ToArray();
}
private static byte[] RegulateNullBytes(byte[] value)
{
return RegulateNullBytes(value, 1);
}
private static byte[] RegulateNullBytes(byte[] value, int minBytes)
{
Array.Reverse(value);
List<byte> bytes = new List<byte>(value);
for (int i = 0; i < bytes.Count; i++)
{
if (bytes[i] == 0 && bytes.Count > minBytes)
{
bytes.Remove(bytes[i]);
i--;
}
else
break;
}
if (bytes.Count < minBytes)
{
int dist = minBytes - bytes.Count;
for (int i = 0; i < dist; i++)
bytes.Insert(0, 0);
}
value = bytes.ToArray();
Array.Reverse(value);
return value;
}
private static void parseTrailer(List<byte> trailer)
{
offsetByteSize = BitConverter.ToInt32(RegulateNullBytes(trailer.GetRange(6, 1).ToArray(), 4), 0);
objRefSize = BitConverter.ToInt32(RegulateNullBytes(trailer.GetRange(7, 1).ToArray(), 4), 0);
byte[] refCountBytes = trailer.GetRange(12, 4).ToArray();
Array.Reverse(refCountBytes);
refCount = BitConverter.ToInt32(refCountBytes, 0);
byte[] offsetTableOffsetBytes = trailer.GetRange(24, 8).ToArray();
Array.Reverse(offsetTableOffsetBytes);
offsetTableOffset = BitConverter.ToInt64(offsetTableOffsetBytes, 0);
}
private static void parseOffsetTable(List<byte> offsetTableBytes)
{
for (int i = 0; i < offsetTableBytes.Count; i += offsetByteSize)
{
byte[] buffer = offsetTableBytes.GetRange(i, offsetByteSize).ToArray();
Array.Reverse(buffer);
offsetTable.Add(BitConverter.ToInt32(RegulateNullBytes(buffer, 4), 0));
}
}
private static object parseBinaryDictionary(int objRef)
{
Dictionary<string, object> buffer = new Dictionary<string, object>();
List<int> refs = new List<int>();
int refCount = 0;
byte dictByte = objectTable[offsetTable[objRef]];
int refStartPosition;
refCount = getCount(offsetTable[objRef], out refStartPosition);
if (refCount < 15)
refStartPosition = offsetTable[objRef] + 1;
else
refStartPosition = offsetTable[objRef] + 2 + RegulateNullBytes(BitConverter.GetBytes(refCount), 1).Length;
for (int i = refStartPosition; i < refStartPosition + refCount * 2 * objRefSize; i += objRefSize)
{
byte[] refBuffer = objectTable.GetRange(i, objRefSize).ToArray();
Array.Reverse(refBuffer);
refs.Add(BitConverter.ToInt32(RegulateNullBytes(refBuffer, 4), 0));
}
for (int i = 0; i < refCount; i++)
{
buffer.Add((string)parseBinary(refs[i]), parseBinary(refs[i + refCount]));
}
return buffer;
}
private static object parseBinaryArray(int objRef)
{
List<object> buffer = new List<object>();
List<int> refs = new List<int>();
int refCount = 0;
byte arrayByte = objectTable[offsetTable[objRef]];
int refStartPosition;
refCount = getCount(offsetTable[objRef], out refStartPosition);
if (refCount < 15)
refStartPosition = offsetTable[objRef] + 1;
else
//The following integer has a header aswell so we increase the refStartPosition by two to account for that.
refStartPosition = offsetTable[objRef] + 2 + RegulateNullBytes(BitConverter.GetBytes(refCount), 1).Length;
for (int i = refStartPosition; i < refStartPosition + refCount * objRefSize; i += objRefSize)
{
byte[] refBuffer = objectTable.GetRange(i, objRefSize).ToArray();
Array.Reverse(refBuffer);
refs.Add(BitConverter.ToInt32(RegulateNullBytes(refBuffer, 4), 0));
}
for (int i = 0; i < refCount; i++)
{
buffer.Add(parseBinary(refs[i]));
}
return buffer;
}
private static int getCount(int bytePosition, out int newBytePosition)
{
byte headerByte = objectTable[bytePosition];
byte headerByteTrail = Convert.ToByte(headerByte & 0xf);
int count;
if (headerByteTrail < 15)
{
count = headerByteTrail;
newBytePosition = bytePosition + 1;
}
else
count = (int)parseBinaryInt(bytePosition + 1, out newBytePosition);
return count;
}
private static object parseBinary(int objRef)
{
byte header = objectTable[offsetTable[objRef]];
switch (header & 0xF0)
{
case 0:
{
//If the byte is
//0 return null
//9 return true
//8 return false
return (objectTable[offsetTable[objRef]] == 0) ? (object)null : ((objectTable[offsetTable[objRef]] == 9) ? true : false);
}
case 0x10:
{
return parseBinaryInt(offsetTable[objRef]);
}
case 0x20:
{
return parseBinaryReal(offsetTable[objRef]);
}
case 0x30:
{
return parseBinaryDate(offsetTable[objRef]);
}
case 0x40:
{
return parseBinaryByteArray(offsetTable[objRef]);
}
case 0x50://String ASCII
{
return parseBinaryAsciiString(offsetTable[objRef]);
}
case 0x60://String Unicode
{
return parseBinaryUnicodeString(offsetTable[objRef]);
}
case 0xD0:
{
return parseBinaryDictionary(objRef);
}
case 0xA0:
{
return parseBinaryArray(objRef);
}
}
throw new Exception("This type is not supported");
}
public static object parseBinaryDate(int headerPosition)
{
byte[] buffer = objectTable.GetRange(headerPosition + 1, 8).ToArray();
Array.Reverse(buffer);
double appleTime = BitConverter.ToDouble(buffer, 0);
DateTime result = PlistDateConverter.ConvertFromAppleTimeStamp(appleTime);
return result;
}
private static object parseBinaryInt(int headerPosition)
{
int output;
return parseBinaryInt(headerPosition, out output);
}
private static object parseBinaryInt(int headerPosition, out int newHeaderPosition)
{
byte header = objectTable[headerPosition];
int byteCount = (int)Math.Pow(2, header & 0xf);
byte[] buffer = objectTable.GetRange(headerPosition + 1, byteCount).ToArray();
Array.Reverse(buffer);
//Add one to account for the header byte
newHeaderPosition = headerPosition + byteCount + 1;
return BitConverter.ToInt32(RegulateNullBytes(buffer, 4), 0);
}
private static object parseBinaryReal(int headerPosition)
{
byte header = objectTable[headerPosition];
int byteCount = (int)Math.Pow(2, header & 0xf);
byte[] buffer = objectTable.GetRange(headerPosition + 1, byteCount).ToArray();
Array.Reverse(buffer);
return BitConverter.ToDouble(RegulateNullBytes(buffer, 8), 0);
}
private static object parseBinaryAsciiString(int headerPosition)
{
int charStartPosition;
int charCount = getCount(headerPosition, out charStartPosition);
var buffer = objectTable.GetRange(charStartPosition, charCount);
return buffer.Count > 0 ? Encoding.ASCII.GetString(buffer.ToArray()) : string.Empty;
}
private static object parseBinaryUnicodeString(int headerPosition)
{
int charStartPosition;
int charCount = getCount(headerPosition, out charStartPosition);
charCount = charCount * 2;
byte[] buffer = new byte[charCount];
byte one, two;
for (int i = 0; i < charCount; i += 2)
{
one = objectTable.GetRange(charStartPosition + i, 1)[0];
two = objectTable.GetRange(charStartPosition + i + 1, 1)[0];
if (BitConverter.IsLittleEndian)
{
buffer[i] = two;
buffer[i + 1] = one;
}
else
{
buffer[i] = one;
buffer[i + 1] = two;
}
}
return Encoding.Unicode.GetString(buffer);
}
private static object parseBinaryByteArray(int headerPosition)
{
int byteStartPosition;
int byteCount = getCount(headerPosition, out byteStartPosition);
return objectTable.GetRange(byteStartPosition, byteCount).ToArray();
}
#endregion
}
public enum plistType
{
Auto, Binary, Xml
}
public static class PlistDateConverter
{
public static long timeDifference = 978307200;
public static long GetAppleTime(long unixTime)
{
return unixTime - timeDifference;
}
public static long GetUnixTime(long appleTime)
{
return appleTime + timeDifference;
}
public static DateTime ConvertFromAppleTimeStamp(double timestamp)
{
DateTime origin = new DateTime(2001, 1, 1, 0, 0, 0, 0);
return origin.AddSeconds(timestamp);
}
public static double ConvertToAppleTimeStamp(DateTime date)
{
DateTime begin = new DateTime(2001, 1, 1, 0, 0, 0, 0);
TimeSpan diff = date - begin;
return Math.Floor(diff.TotalSeconds);
}
}
}
and use this method in commit action of Installer.cs class to add an entry of extension Extension.plist
public void InstallSafariExt()
{
string safariExtPlist = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Apple Computer\\Safari\\Extensions\\Extensions.plist";
string safariSetupPlist = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\YourComp\\YourSoft\\Extensions.plist";
string ExtDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Apple Computer\\Safari\\Extensions";
if (!Directory.Exists(ExtDir))
{
Directory.CreateDirectory(ExtDir);
if (!File.Exists(safariExtPlist))
{
File.Copy(safariSetupPlist, safariExtPlist);
}
}
else
{
if (!File.Exists(safariExtPlist))
{
File.Copy(safariSetupPlist, safariExtPlist);
}
}
object obj = Plist.readPlist(safariExtPlist);
Dictionary<string, object> dict = (Dictionary<string, object>)obj;
Dictionary<string, object> NewExt = new Dictionary<string, object>();
NewExt.Add("Hidden Bars", new List<object>());
NewExt.Add("Added Non-Default Toolbar Items", new List<object>());
NewExt.Add("Enabled", true);
NewExt.Add("Archive File Name", "YourExtName.safariextz");
NewExt.Add("Removed Default Toolbar Items", new List<object>());
NewExt.Add("Bundle Directory Name", "YourExtName.safariextension");
List<object> listExt = (List<object>)dict["Installed Extensions"];
listExt.Add(NewExt);
Plist.writeBinary(obj, safariExtPlist);
string safariExtFile = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\YourComp\\YourSoft\\YourExtName.safariextz";
string safariInstallfolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Apple Computer\\Safari\\Extensions\\YourExtName.safariextz";
string[] safExtFiles = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Apple Computer\\Safari\\Extensions\\", "YourExtName*.safariextz");
for (int i = 0; i < safExtFiles.Length; i++)
{
if (File.Exists(safExtFiles[i]))
File.Delete(safExtFiles[i]);
}
File.Copy(safariExtFile, safariInstallfolder);
}
Is there any way to create a Tab Menu in j2me?
I found a code but I am unable to understand it
In this code there is Tab Menu created which is in Canvas class and then Tab menu is created which is totally done in Canvas or painted. The only part I found difficult to grasp was the void go() method and then
When I try to draw anything above and below this code using paint method, it doesn't work - what's the problem?
Below is the code
// Tab Menu CANVAS class
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
public class TabMenuCanvas extends Canvas
{
TabMenu menu = null;
public TabMenuCanvas()
{
menu = new TabMenu(
new String[]{"Home", "News", "Community", "Your files", "Credits", "Events", "Blog", "Upload", "Forum Nokia"},
getWidth() - 20
);
}
protected void keyPressed(int key)
{
int gameAction = getGameAction(key);
if(gameAction == Canvas.RIGHT)
{
menu.goRight();
repaint();
}
else if(gameAction == Canvas.LEFT)
{
menu.goLeft();
repaint();
}
}
protected void paint(Graphics g)
{
g.translate(10, 30);
menu.paint(g);
g.translate(- 10, - 30);
}
}
// Tab Menu Class
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
public class TabMenu
{
int background = 0xffffff;
int bgColor = 0xcccccc;
int bgFocusedColor = 0x0000ff;
int foreColor = 0x000000;
int foreFocusedColor = 0xffffff;
int cornerRadius = 6;
int padding = 2;
int margin = 2;
Font font = Font.getDefaultFont();
int scrollStep = 20;
int selectedTab = 0; //selected tab index
int[] tabsWidth = null; //width of single tabs
int[] tabsLeft = null; //left X coordinate of single tabs
int tabHeight = 0; //height of tabs (equal for all tabs)
String[] tabs = null; //tab labels
int menuWidth = 0; //total menu width
int viewportWidth = 0; //visible viewport width
int viewportX = 0; //current viewport X coordinate
public TabMenu(String[] tabs, int width)
{
this.tabs = tabs;
this.viewportWidth = width;
initialize();
}
void initialize()
{
tabHeight = font.getHeight() + cornerRadius + 2 * padding; //[ same for all tabs]
menuWidth = 0;
tabsWidth = new int[tabs.length];
tabsLeft = new int[tabs.length];
for(int i = 0; i < tabsWidth.length; i++)
{
tabsWidth[i] = font.stringWidth(tabs[i]) + 2 * padding + 2 * cornerRadius;
tabsLeft[i] = menuWidth;
menuWidth += tabsWidth[i];
if(i > 0)
{
menuWidth += margin;
}
}
}
public void goRight()
{
go(+1);
}
public void goLeft()
{
go(-1);
}
private void go(int delta)
{
int newTab = Math.max(0, Math.min(tabs.length - 1, selectedTab + delta));
boolean scroll = true;
if(newTab != selectedTab && isTabVisible(newTab))
{
selectedTab = newTab;
if( (delta > 0 && tabsLeft[selectedTab] + tabsWidth[selectedTab] > viewportX + viewportWidth) ||
(delta < 0 && tabsLeft[selectedTab] < viewportX))
{
scroll = true;
}
else
{
scroll = false;
}
}
if(scroll)
{
viewportX = Math.max(0, Math.min(menuWidth - viewportWidth, viewportX + delta * scrollStep));
}
}
private boolean isTabVisible(int tabIndex)
{
return tabsLeft[tabIndex] < viewportX + viewportWidth &&
tabsLeft[tabIndex] + tabsWidth[tabIndex] >= viewportX;
}
public void paint(Graphics g)
{
int currentX = - viewportX;
g.setClip(0, 0, viewportWidth, tabHeight);
g.setColor(background);
g.fillRect(0, 0, viewportWidth, tabHeight);
for(int i = 0; i < tabs.length; i++)
{
g.setColor(i == selectedTab ? bgFocusedColor : bgColor);
g.fillRoundRect(currentX, 0, tabsWidth[i], tabHeight + cornerRadius, 2 * cornerRadius, 2 * cornerRadius);
g.setColor(i == selectedTab ? foreFocusedColor : foreColor);
g.drawString(tabs[i], currentX + cornerRadius + padding, cornerRadius + padding, Graphics.LEFT | Graphics.TOP);
currentX += tabsWidth[i] + margin;
}
}
}
When I try to draw anything above and below this code using paint method, it doesn't work
what of the paint methods you use to draw above and below? Pay attention that there are two methods named that way - first is in TabMenuCanvas, second is in TabMenu (second method is invoked from TabMenuCanvas#repaint).
whatever you would try to draw in TabMenuCanvas#paint will most likely be overwritten by setClip and fillRect when TabMenu#paint is invoked following repaint request
The only place where one can expect to be able to draw something visible seems to be in TabMenu#paint method, inside the clip area that is set there.
You can use GUI Libraries for J2ME,for example Lightweight User Interface Toolkit (LWUIT),Flemil have "tab menu".You can see list of GUI Libraries here.