Android Wallpaper App Screen Size - wallpaper

I am working on an Android wallpaper app. I am trying to develop it for 4.0 and higher Android devices. But even I research a lot, read a lot about scailng wallpaper for different screen sizes I could not fix the problem about it. Here is the main_activiy:
package com.abcd.iphone5sduvarkagidi;
import static com.abcd.iphone5sduvarkagidi.HeavyLifter.FAIL;
import static com.abcd.iphone5sduvarkagidi.HeavyLifter.SUCCESS;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.abcd.iphone5sduvarkagidi.R;
import com.abcd.iphone5sduvarkagidi.HeavyLifter;
public class MainActivity extends Activity {
/**
* A list containing the resource identifiers for all of our selectable
* backgrounds
*/
private static final List<Integer> backgrounds = new ArrayList<Integer>();
/** The total number of backgrounds in the list */
private static final int TOTAL_IMAGES;
/**
* Instantiate the list statically, so this will be done once on app load,
* also calculate the total number of backgrounds
*/
static {
backgrounds.add(R.drawable.iphone5s_1);
backgrounds.add(R.drawable.iphone5s_big_2_600_1024);
// We -1 as lists are zero indexed (0-2 is a size of 2) - we'll make use
// of this to implement a browsing loop
TOTAL_IMAGES = (backgrounds.size() - 1);
}
/** the state of what wallpaper is currently being previewed */
private int currentPosition = 0;
/** our image wallpaper preview */
private ImageView backgroundPreview;
/**
* A helper class that will do the heavy work of decoding images and
* actually setting the wallpaper
*/
private HeavyLifter chuckNorris;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
backgroundPreview = (ImageView) findViewById(R.id.imageView1);
// Set the default image to be shown to start with
changePreviewImage(currentPosition);
// Load are heavy lifter (goes and does work on another thread), to get
// a response after the lifters thread
// has finished we pass in a Handler that will be notified when it
// completes
chuckNorris = new HeavyLifter(this, chuckFinishedHandler);
}
/**
* Called from XML when the previous button is pressed Decrement the current
* state position If the position is now less than 0 loop round and show the
* last image (the array size)
*
* #param v
*/
public void gotoPreviousImage(View v) {
int positionToMoveTo = currentPosition;
positionToMoveTo--;
if (positionToMoveTo < 0) {
positionToMoveTo = TOTAL_IMAGES;
}
changePreviewImage(positionToMoveTo);
}
/**
* Called from XML when the set wallpaper button is pressed Thie retrieves
* the id of the current image from our list It then asks chuck to set it as
* a wallpaper! The chuckHandler will be called when this operation is
* complete
*
* #param v
*/
public void setAsWallpaper(View v) {
int resourceId = backgrounds.get(currentPosition);
chuckNorris.setResourceAsWallpaper(resourceId);
}
/**
* Called from XML when the next button is pressed Increment the current
* state position If the position is now greater than are array size loop
* round and show the first image again
*
* #param v
*/
public void gotoNextImage(View v) {
int positionToMoveTo = currentPosition;
positionToMoveTo++;
if (currentPosition == TOTAL_IMAGES) {
positionToMoveTo = 0;
}
changePreviewImage(positionToMoveTo);
}
/**
* Change the currently showing image on the screen This is quite an
* expensive operation as each time the system has to decode the image from
* our resources - alternatives are possible (a list of drawables created at
* app start)
*
* #param pos
* the position in {#link MainActivity#backgrounds} to select the
* image from
*/
public void changePreviewImage(int pos) {
currentPosition = pos;
backgroundPreview.setImageResource(backgrounds.get(pos));
Log.d("Main", "Current position: " + pos);
}
/**
* This is the handler that is notified when are HeavyLifter is finished
* doing an operation
*/
private Handler chuckFinishedHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SUCCESS:
Toast.makeText(MainActivity.this, "Duvar kağıdı ayarlandı",
Toast.LENGTH_SHORT).show();
break;
case FAIL:
Toast.makeText(MainActivity.this, "Bir hata oluştu",
Toast.LENGTH_SHORT).show();
break;
default:
super.handleMessage(msg);
}
}
};
}
Here's the Heavy Lifter.java
package com.abcd.iphone5sduvarkagidi;
import java.io.IOException;
import android.app.WallpaperManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.util.Log;
/**
* <b>This class uses Threads</b>
* An alternative to this class would be to use an ASyncTask
* #author aflazi
*
*/
public class HeavyLifter {
public static final int SUCCESS = 0;
public static final int FAIL = 1;
private final Context context;
private final Handler callback;
private WallpaperManager manager;
/**
* Setup the HeavyLifter
* #param context the context we are running in - typically an activity
* #param callback the handler you want to be notified when we finish doing an operation
*/
public HeavyLifter(Context context, Handler callback) {
this.context = context;
this.callback = callback;
this.manager = (WallpaperManager) context.getSystemService(Context.WALLPAPER_SERVICE);
}
/**
* Takes a resource id of a file within our /res/drawable folder<br/>
* It then spawns a new thread to do its work on<br/>
* The resource is decoded and converted to a byte array<br/>
* This array is passed to the system which can use it to set the phones wallpaper<br/>
* Upon completion the callback handler is sent a message with {#link HeavyLifter#SUCCESS} or {#link HeavyLifter#FAIL}
*
* #param resourceId id of a file within our /res/drawable/ldpi/mdpi/hdpi/xhdpi folder
*/
public void setResourceAsWallpaper(final int resourceId) {
new Thread() {
#Override
public void run() {
try {
manager.setBitmap(getImage(resourceId));
callback.sendEmptyMessage(SUCCESS);
} catch (IOException e) {
Log.e("Main", "Duvar kağıdı ayarlanamadı");
callback.sendEmptyMessage(FAIL);
}
}
}.start();
}
/**
* Decodes a resource into a bitmap, here it uses the convenience method 'BitmapFactory.decodeResource', but you can decode
* using alternatives these will give you more control over the size and quality of the resource.
*/
private Bitmap getImage(int resourceId) {
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId, null);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, manager.getDesiredMinimumWidth(), manager.getDesiredMinimumHeight(), true);
bitmap.recycle();
bitmap = null;
return scaledBitmap;
}
}
Also I created different layouts for small,normal,large and xlarge screens. I added different sized images to drawable folder. But when I tried to set wallpaper in AVDs the wallpaper looks bad, not scale for the device. Please help.

As per this
those layouts your using are deprecated
And what do u mean by the wallpaper looks bad exactly? is it larger than the screen? is it very small?
and what are the devices your having problems with?

Related

JavaFX 3D: Rotating PerspectiveCamera using keyboard ends up changing camera's view

I want to be able to rotate a perspective camera using the WASD keys. Pressing the W and S keys should rotate the camera along the X axis, and pressing the A and D keys should rotate it along the Y. In an attempt to do this I created a class called RotateCamera that extends the PerspectiveCamera class and includes methods I made to rotate the camera. This way mostly works, but I find if I first move the camera forward using the up arrow key, and then spam the W key so that the camera rotates 360 degrees, when the sphere comes back in view it is very far away, and moving the camera using the arrow keys seems to move it in random directions. I was wondering why this is/how to fix it? A copy of my classes is below.
package ui;
import javafx.scene.PerspectiveCamera;
import javafx.scene.transform.Rotate;
import javafx.scene.transform.Transform;
/**
* A PerspectiveCamera that includes methods which allow it to be rotated
*/
public class RotateCamera extends PerspectiveCamera {
Transform currTransform;
/**
* Constructor
* Creates a new camera with default Rotate transform
*/
public RotateCamera() {
currTransform = new Rotate();
}
/**
* Rotates the camera along the x-axis according to the given angle
* #param angle the amount of degrees the camera is rotated
*/
public void rotateInX(int angle) {
Rotate newRotation = new Rotate(angle, Rotate.X_AXIS);
rotateCam(newRotation);
}
/**
* Rotates the camera along the y-axis according to the given angle
* #param angle the amount of degrees the camera is rotated
*/
public void rotateInY(int angle) {
Rotate newRotation = new Rotate(angle, Rotate.Y_AXIS);
rotateCam(newRotation);
}
/**
* Applies both the currTransform and given rotation to the camera
*/
private void rotateCam(Rotate rotation) {
currTransform = currTransform.createConcatenation(rotation);
getTransforms().clear();
getTransforms().addAll(currTransform);
}
}
>
package ui;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Sphere;
import javafx.stage.Stage;
import javafx.scene.Group;
import model.Molecule;
import java.util.Observable;
import java.util.Observer;
/**
* Represents the window in which the molecule drawing editor appears.
* Run the main method to start the program!
*/
public class MarsBonds extends Application {
private static final int CAM_NEAR_CLIP = 0;
private static final int CAM_FAR_CLIP = 1000;
private static final int CAM_ORG_DISTANCE = -10;
private static final int WIDTH = 1000;
private static final int HEIGHT = 800;
private static final Color SCENE_COLOR = Color.BLACK;
private static final int CAM_SPEED = 30;
private static Stage primaryStage;
private static RotateCamera camera;
private static Scene scene;
#Override
public void start(Stage primaryStage) throws Exception {
setScene();
setCamera();
setPrimaryState(primaryStage);
}
/**
* Creates scene with molecule in center of screen and black background
*/
public static void setScene() {
Sphere molecule = new Sphere(30);
molecule.translateXProperty().set(WIDTH/2);
molecule.translateYProperty().set(HEIGHT/2);
Group root = new Group();
root.getChildren().add(molecule);
scene = new Scene(root, WIDTH, HEIGHT);
scene.setFill(SCENE_COLOR);
}
/**
* Initializes camera and adds to scene
*/
private static void setCamera() {
camera = new RotateCamera();
camera.setNearClip(CAM_NEAR_CLIP);
camera.setFarClip(CAM_FAR_CLIP);
camera.translateZProperty().set(CAM_ORG_DISTANCE);
scene.setCamera(camera);
}
/**
* Sets up the primary stage by setting its scene, title, and adding key control
* #param stage the primary stage
*/
private static void setPrimaryState(Stage stage) {
primaryStage = stage;
addEventHandlers();
primaryStage.setTitle("Mar's Bonds");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* Adds KeyEvent handler to primary stage
* The KeyEvent handler uses input from the WASD keys to rotate
* the camera and the arrow keys to move the camera
*/
private static void addEventHandlers() {
primaryStage.addEventHandler(KeyEvent.KEY_PRESSED, e -> {
switch(e.getCode()) {
case W:
camera.rotateInX(-1);
break;
case S:
camera.rotateInX(1);
break;
case A:
camera.rotateInY(1);
break;
case D:
camera.rotateInY(-1);
break;
case UP:
camera.setTranslateZ(camera.getTranslateZ() + CAM_SPEED);
break;
case DOWN:
camera.setTranslateZ(camera.getTranslateZ() - CAM_SPEED);
break;
case LEFT:
camera.setTranslateX(camera.getTranslateX() - CAM_SPEED/3);
break;
case RIGHT:
camera.setTranslateX(camera.getTranslateX() + CAM_SPEED/3);
break;
}
});
}
public static void main( String[] args ) {
launch(args);
}
}

Is there a way of tracking stages

I want to track focused node to perform some action after user inactivity on that node. But focused for my application means that there could be only 1 focus node in the entire application (application has numerous Stages and they creation are out of my control. I also cannot force different department of my company to use registry to register stages after they create them).
E.g. I have a property for focused component scene.focusOwnerProperty(), I can track whether Stage is stage.focusedProperty() but I'm searching the way to retrieve all stages.
Do you know the way?
I found a solution. com.sun.javafx.stage.StageHelper.getStages() list all stages.
You can Use Window[] windows = Window.getWindows(); this is part of the Public Api and works fine for me.
Thanks guys for answers. I write a class which provides an easy way to track currently focused Node and "focused" Scene. "Focused" means the focused component from focused Stage. If there are any mistakes in my code I would be grateful for if you notice and inform me.
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.stage.Stage;
import com.sun.javafx.stage.StageHelper;
/**
* Tracks focused component among all {#link Stage}'s. Currently this is singleton but it will make service
* out of it.
*
* #author created: kszymanek on 8 sty 2016 15:19:32
*/
public class GlobalFocusTracker
{
private static final GlobalFocusTracker INSTANCE = new GlobalFocusTracker();
/**
* tracks stage list and each stage and registers {#link #sceneListener} on
* the focused stage
*/
private StagesListener stagesListener;
/**
* tracks scene of the focused stage and registers
* {#link #focusOwnerListener} on it
*/
private SceneListener sceneListener;
private FocusOwnerListener focusOwnerListener;
private ReadOnlyObjectWrapper focusedNodeProperty = new ReadOnlyObjectWrapper();
private ReadOnlyObjectWrapper focusedSceneProperty = new ReadOnlyObjectWrapper();
private GlobalFocusTracker()
{
}
public static GlobalFocusTracker getInstance()
{
return INSTANCE;
}
/**
* #return current {#link Scene} from the currently focused {#link Stage}
*/
public ReadOnlyObjectProperty focusedSceneProperty()
{
init();
return focusedSceneProperty.getReadOnlyProperty();
}
/**
* #return focused node among all stages. There could be one focus owner at
* the time. If end user focuses some other application there would
* be no focus node.
*/
public ReadOnlyObjectProperty focusedNodeProperty()
{
init();
return focusedNodeProperty.getReadOnlyProperty();
}
private void init()
{
if(stagesListener == null)
{
stagesListener = new StagesListener();
sceneListener = new SceneListener();
focusOwnerListener = new FocusOwnerListener();
stagesListener.register();
}
}
private class StagesListener implements ListChangeListener, ChangeListener
{
private ObservableList stages;
#Override
public void onChanged(javafx.collections.ListChangeListener.Change aChange)
{
while(aChange.next())
{
if(aChange.wasRemoved())
{
for(Stage stage : aChange.getRemoved())
{
stage.focusedProperty().removeListener(this);
}
}
if(aChange.wasAdded())
{
for(Stage stage : aChange.getAddedSubList())
{
stage.focusedProperty().addListener(this);
}
}
}
}
#Override
public void changed(ObservableValue aObservable, Boolean aOld, Boolean aNew)
{
Stage focusedStage = null;
for(Stage stage : stages)
{
if(stage.isFocused())
{
focusedStage = stage;
}
}
sceneListener.register(focusedStage);
}
public void register()
{
if(stages == null)
{
stages = StageHelper.getStages();
stages.addListener(this);
for(Stage stage : stages)
{
stage.focusedProperty().addListener(this);
if(stage.isFocused())
{
sceneListener.register(stage);
}
}
}
}
}
private class SceneListener implements ChangeListener
{
private Stage stage;
#Override
public void changed(ObservableValue aObservable, Scene aOld, Scene aNew)
{
focusOwnerListener.register(aNew);
}
/**
* #param aStage is {#code null} protected
*/
public void register(Stage aStage)
{
if(aStage != stage)
{
unregister();
stage = aStage;
if(aStage != null)
{
aStage.sceneProperty().addListener(this);
focusOwnerListener.register(aStage.getScene());
}
}
}
public void unregister()
{
if(stage != null)
{
focusOwnerListener.unregister();
stage.sceneProperty().removeListener(this);
stage = null;
}
}
}
private class FocusOwnerListener implements ChangeListener
{
private Scene scene;
#Override
public void changed(ObservableValue aObservable, Node aOld, Node aNew)
{
focusedNodeProperty.set(aNew);
}
/**
* #param aScene can be {#code null} in such case it is only an equivalent
* of {#link #unregister()}
*/
public void register(Scene aScene)
{
if(scene != aScene)
{
unregister();
scene = aScene;
focusedSceneProperty.set(aScene);
if(aScene != null)
{
focusedNodeProperty.set(aScene.getFocusOwner());
aScene.focusOwnerProperty().addListener(this);
}
}
}
public void unregister()
{
if(scene != null)
{
focusedSceneProperty.set(null);
focusedNodeProperty.set(null);
scene.focusOwnerProperty().removeListener(this);
scene = null;
}
}
}
}

Tab changing in Android Studio

I am new to Android Programming and Android studio.
Basically, I am creating a Memo App by Android Studio, created a Tabbed Activity(Action Bar Tabs(with viewpager)), then created 4 Fragment class and layout, all codes generated automatically by Android Studio.
But I get stuck in Tab changing......
package com.example.user.memoapp;
import java.util.Locale;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
static ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the four
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below)
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
case 3:
return getString(R.string.title_section4).toUpperCase(l);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public int mPage;
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_all, container, false);
return rootView;
}
}
}
I tried to change getItem() to something Like this:
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below)
//return PlaceholderFragment.newInstance(position + 1);
switch(position){
case 0:
return new All();
case 1:
return new Urgent();
case 2:
return new Late();
case 3:
return new Done();
default:
return null;
}
}
But it dont even work, said "Unfortunately, MemoApp has stopped".
Here are the codes of the 4 fragment class, they are all generated by Android Studio, are basically the same....
All.java:
package com.example.user.memoapp;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link All.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link All#newInstance} factory method to
* create an instance of this fragment.
*/
public class All extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment all.
*/
// TODO: Rename and change types and number of parameters
public static All newInstance(String param1, String param2) {
All fragment = new All();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public All() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_all, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
Urgent.java
package com.example.user.memoapp;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link Urgent.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link Urgent#newInstance} factory method to
* create an instance of this fragment.
*/
public class Urgent extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Urgent.
*/
// TODO: Rename and change types and number of parameters
public static Urgent newInstance(String param1, String param2) {
Urgent fragment = new Urgent();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public Urgent() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_urgent, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
Late.java,
package com.example.user.memoapp;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link Late.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link Late#newInstance} factory method to
* create an instance of this fragment.
*/
public class Late extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Late.
*/
// TODO: Rename and change types and number of parameters
public static Late newInstance(String param1, String param2) {
Late fragment = new Late();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public Late() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_late, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
Done.java:
package com.example.user.memoapp;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link Done.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link Done#newInstance} factory method to
* create an instance of this fragment.
*/
public class Done extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Done.
*/
// TODO: Rename and change types and number of parameters
public static Done newInstance(String param1, String param2) {
Done fragment = new Done();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public Done() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_done, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
Sorry for extremely long boring coding...
As the logcat says, you are assigning your MainActivity to All.mListener, which is an OnFragmentInteractionListener, but MainActivity does not implement this interface
So you need to make MainActivity implement OnFragmentInteractionListener:
public class MainActivity extends ActionBarActivity implements
ActionBar.TabListener, OnFragmentInteractionListener {
// ... all your Activity code ...
#Override
public void onFragmentInteraction(Uri uri) {
// ... implement communication here ...
}
}
This will prevent the app from crashing, but still you will need to implement communication between Fragments and Activity. Change the parameters required by onFragmentInteraction() if you need to send something else, or remove the interface and any reference of mListener if you don't need that kind of communication.
Good luck!

Error : Running array of objects in JavaFX with same method

Here's the code :
Main File :
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package testobjectarray;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
/**
*
*
*/
public class TestObjectArray extends Application {
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* The main() method is ignored in correctly deployed JavaFX application. main() serves only as fallback in case the application can not be launched through deployment artifacts, e.g., in IDEs
* with limited FX support. NetBeans ignores main().
*
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
myClass[] c = new myClass[5];
c[2].myMethod();
}
}
Class declared outside :
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package testobjectarray;
/**
*
*
*/
public class myClass {
public void myMethod(){
System.out.println("Inside myMethod");
}
}
Problem, I get errors when I compile i.e. initializing an array of objects and invoking the method. If I have just one object, it works great. Any help appreciated.
The problem with your code is you are initialising an array of size 5, but you never add values to it. Try the following code
myClass[] c = new myClass[5];
c[0] = new myClass();
c[1] = new myClass(); // and so on till c[4]
//now you can call the methods
c[1].myMethod();

Combining Fragments and ActionBar in Android level < 13. Is there a feasible way?

I would like to write my project in the lowest possible Android version for my reqs, which is 11.
But I need Fragment.attach and ActionBars.
Since level 11 does not include Fragment.attach I import the support package for v4.
But now the problem is that the TabListerner for the ActionTab does not use the v4 Fragment but rather the level 11 Fragment. Casting won't work.
Do I really need to switch to level 13 or is there a feasible solution to implement all this in level 11.
Here is the code:
import android.app.ActionBar;
import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.os.Bundle;
import android.support.v4.app.Fragment;
public class TestActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public static class TabListener<T extends android.support.v4.app.Fragment> /* to make sure it take the Fragment from the support package! */
implements ActionBar.TabListener {
private Fragment mFragment;
private final Activity mActivity;
private final String mTag;
private final Class<T> mClass;
/**
* Constructor used each time a new tab is created.
*
* #param activity
* The host Activity, used to instantiate the fragment
* #param tag
* The identifier tag for the fragment
* #param clz
* The fragment's Class, used to instantiate the fragment
*/
public TabListener(Activity activity, String tag, Class<T> clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
}
/* The following are each of the ActionBar.TabListener callbacks */
public void onTabSelected(Tab tab,
android.support.v4.app.FragmentTransaction ft) {
// Check if the fragment is already initialized
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.add(android.R.id.content, mFragment, mTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
}
}
/* these are NOT the implementation of the TabListener above, since the use the
*
* the FragmentTransactionof the support package and not of level 11
*
*/
public void onTabUnselected(Tab tab,
android.support.v4.app.FragmentTransaction ft) {
if (mFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(mFragment);
}
}
public void onTabReselected(Tab tab,
android.support.v4.app.FragmentTransaction ft) {
// User selected the already selected tab. Usually do nothing.
}
/* these are added since they belong to the above definition of TabListener
*
* unfortunately the use the FragmentTransaction of level 11, not the one of the support package!
*
*/
#Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
}
#Override
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
}
#Override
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
}
}
}
im using ActionBarCompat and Fragments on Api Ver 8.0 , the only diference with your code its that im using ft.replace instead of ft.add and a ViewPager on the xml to show the fragments, it runs ok so far ..
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
public final class TabListener<T extends Fragment> implements ActionBar.TabListener {
private Fragment mFragment;
private final Activity mActivity;
private final String mTag;
private final Class<T> mClass;
/** Constructor used each time a new tab is created.
* #param activity The host Activity, used to instantiate the fragment
* #param tag The identifier tag for the fragment
* #param clz The fragment's Class, used to instantiate the fragment
*/
public TabListener(Activity activity, String tag, Class<T> clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
}
/* The following are each of the ActionBar.TabListener callbacks */
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.replace(R.id.pager, mFragment, mTag);
} else {
// If it exists, simply attach it in order to show it
ft.replace(R.id.pager, mFragment, mTag);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
// Detach the fragment, because another one is being attached
ft.remove(mFragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// User selected the already selected tab. Usually do nothing.
}
}
Not sure if you still need this, but we use ActionBarSherlock and it sounds like it could help you as well:
http://actionbarsherlock.com/

Resources