I am using navigationdrawer in an activity.If I click any of the item in the navigation drawer
in default with some color it should allow us to paint some thing.But I tried for a long time i was unable to do it.Kindly hep as soon as possible.Below is my code which i am using.
Painting.java
package com.example.painturselfnew;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class Painting extends Activity {
private ListView mdrawerlist;
private DrawerLayout mdrawerlayout;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mdrawertitle;
private CharSequence mtitle;
private String[] mfragmenttitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_painting);
mtitle = mdrawertitle = getTitle();
mfragmenttitles = getResources().getStringArray(R.array.widgets);
mdrawerlayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mdrawerlist = (ListView) findViewById(R.id.left_drawer);
mdrawerlist.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mfragmenttitles));
getActionBar().setDisplayShowHomeEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
mdrawerlist.setOnItemClickListener(new DrawerItemClickListener());
mDrawerToggle = new ActionBarDrawerToggle(this, mdrawerlayout,
R.drawable.ic_launcher, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mtitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mdrawertitle);
invalidateOptionsMenu();
}
};
mdrawerlayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.painting, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean draweropen = mdrawerlayout.isDrawerOpen(mdrawerlist);
menu.findItem(R.id.action_settings).setVisible(!draweropen);
return super.onPrepareOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
if (mdrawerlayout.isDrawerOpen(mdrawerlist)) {
mdrawerlayout.closeDrawer(mdrawerlist);
} else {
mdrawerlayout.openDrawer(mdrawerlist);
}
mdrawerlayout.openDrawer(mdrawerlist);
/*
* Toast.makeText(getApplicationContext(), "Options Selected",
* Toast.LENGTH_LONG).show();
*/
return true;
case android.R.id.home:
startActivity(new Intent(Painting.this, MainActivity.class));
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
Fragment fragment = new Fragment();
Bundle args = new Bundle();
// args.putInt(Fragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
switch (position) {
case 0:
fragment = new Fragment1();
Toast.makeText(getApplicationContext(), "Camera Selected",
Toast.LENGTH_LONG).show();
break;
case 1:
fragment = new Fragment2();
Toast.makeText(getApplicationContext(), "Color Selected",
Toast.LENGTH_LONG).show();
break;
case 2:
/*
* PaintFragment fragment1; fragment1 = new PaintFragment();
*/
PaintFragment fragment1 = new PaintFragment();
Toast.makeText(getApplicationContext(), "Paint Selected",
Toast.LENGTH_LONG).show();
break;
case 3:
fragment = new Fragment4();
Toast.makeText(getApplicationContext(), "Save selected",
Toast.LENGTH_LONG).show();
break;
case 4:
fragment = new Fragment5();
Toast.makeText(getApplicationContext(), "Share Selected",
Toast.LENGTH_LONG).show();
break;
case 5:
fragment = new Fragment6();
Toast.makeText(getApplicationContext(), "ArtBy Selected",
Toast.LENGTH_LONG).show();
break;
case 6:
fragment = new Fragment7();
Toast.makeText(getApplicationContext(), "Refresh Selected",
Toast.LENGTH_LONG).show();
break;
}
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
mdrawerlist.setItemChecked(position, true);
setTitle(mfragmenttitles[position]);
mdrawerlayout.closeDrawer(mdrawerlist);
}
#Override
public void setTitle(CharSequence title) {
mtitle = title;
getActionBar().setTitle(mtitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
PainitngFragment.java
package com.example.painturselfnew;
import android.annotation.TargetApi;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Build;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class PaintFragment extends Activity {
/*private static int displayWidth = 0;
private static int displayHeight = 0;
*/
/*
* #Override public void onCreate(Bundle savedInstanceState) {
* super.onCreate(savedInstanceState);
* //setContentView(R.layout.activity_fragment3); //setContentView(new
* MyView(this));
*
*
* }
*/
/*public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BrushView view=new BrushView(this);
setContentView(view);
addContentView(view.btnEraseAll, view.params);
/*
* View view = inflater.inflate(R.layout.activity_fragment3, container,
* false);
*/
// getActivity();
/*
* Display display =
* ((WindowManager)this.getSystemService(Context.WINDOW_SERVICE
* )).getDefaultDisplay(); displayWidth = display.getWidth();
* displayHeight = display.getHeight();
*/
//ImageView iv = (ImageView) view.findViewById(R.id.imageView1);
/*
* iv.setOnClickListener(new View.OnClickListener() {
*
* #Override public void onClick(View arg0) { // TO DO Auto-generated
* method stub
*
* BrushView view = new BrushView(getActivity()); //setContentView(new
* BrushView(this)); } });
*/
//return view;
}
#Override
protected void onPause() {
super.onPause();
finish();
}
public class BrushView extends View {
private Paint brush = new Paint();
private Path path = new Path();
public Button btnEraseAll;
public LayoutParams params;
public BrushView(Context paintFragment) {
super(paintFragment);
brush.setAntiAlias(true);
brush.setColor(Color.BLUE);
brush.setStyle(Paint.Style.STROKE);
brush.setStrokeJoin(Paint.Join.ROUND);
brush.setStrokeWidth(15f);
btnEraseAll = new Button(paintFragment);
btnEraseAll.setText("Erase Everything!!");
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
btnEraseAll.setLayoutParams(params);
btnEraseAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// reset the path
path.reset();
// invalidate the view
postInvalidate();
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float pointX = event.getX();
float pointY = event.getY();
// Checks for the event that occurs
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(pointX, pointY);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(pointX, pointY);
break;
case MotionEvent.ACTION_UP:
break;
default:
return false;
}
// Force a view to draw.
postInvalidate();
return false;
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, brush);
}
}
}
Thanks In Advance...
Related
in https://github.com/Yalantis/Side-Menu.Android
please help me :(
How can when i click on each item in side menu, go to command "intent to other activity" instead of transport between images
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.List;
import io.codetail.animation.SupportAnimator;
import io.codetail.animation.ViewAnimationUtils;
import yalantis.com.sidemenu.interfaces.Resourceble;
import yalantis.com.sidemenu.interfaces.ScreenShotable;
import yalantis.com.sidemenu.model.SlideMenuItem;
import yalantis.com.sidemenu.sample.fragment.ContentFragment;
import yalantis.com.sidemenu.util.ViewAnimator;
public class MainActivity extends ActionBarActivity implements ViewAnimator.ViewAnimatorListener {
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private List<SlideMenuItem> list = new ArrayList<>();
private ContentFragment contentFragment;
private ViewAnimator viewAnimator;
private int res = R.drawable.content_music;
private LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contentFragment = ContentFragment.newInstance(R.drawable.content_music);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, contentFragment)
.commit();
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerLayout.setScrimColor(Color.TRANSPARENT);
linearLayout = (LinearLayout) findViewById(R.id.left_drawer);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawerLayout.closeDrawers();
}
});
setActionBar();
createMenuList();
viewAnimator = new ViewAnimator<>(this, list, contentFragment, drawerLayout, this);
}
private void createMenuList() {
SlideMenuItem menuItem0 = new SlideMenuItem(ContentFragment.CLOSE, R.drawable.icn_close);
list.add(menuItem0);
SlideMenuItem menuItem = new SlideMenuItem(ContentFragment.BUILDING, R.drawable.icn_1);
list.add(menuItem);
SlideMenuItem menuItem2 = new SlideMenuItem(ContentFragment.BOOK, R.drawable.icn_2);
list.add(menuItem2);
SlideMenuItem menuItem3 = new SlideMenuItem(ContentFragment.PAINT, R.drawable.icn_3);
list.add(menuItem3);
SlideMenuItem menuItem4 = new SlideMenuItem(ContentFragment.CASE, R.drawable.icn_4);
list.add(menuItem4);
SlideMenuItem menuItem5 = new SlideMenuItem(ContentFragment.SHOP, R.drawable.icn_5);
list.add(menuItem5);
SlideMenuItem menuItem6 = new SlideMenuItem(ContentFragment.PARTY, R.drawable.icn_6);
list.add(menuItem6);
SlideMenuItem menuItem7 = new SlideMenuItem(ContentFragment.MOVIE, R.drawable.icn_7);
list.add(menuItem7);
}
private void setActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
drawerLayout, /* DrawerLayout object */
toolbar, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
linearLayout.removeAllViews();
linearLayout.invalidate();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
if (slideOffset > 0.6 && linearLayout.getChildCount() == 0)
viewAnimator.showMenuContent();
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.setDrawerListener(drawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private ScreenShotable replaceFragment(ScreenShotable screenShotable, int topPosition) {
this.res = this.res == R.drawable.content_music ? R.drawable.content_films : R.drawable.content_music;
View view = findViewById(R.id.content_frame);
int finalRadius = Math.max(view.getWidth(), view.getHeight());
SupportAnimator animator = ViewAnimationUtils.createCircularReveal(view, 0, topPosition, 0, finalRadius);
animator.setInterpolator(new AccelerateInterpolator());
animator.setDuration(ViewAnimator.CIRCULAR_REVEAL_ANIMATION_DURATION);
findViewById(R.id.content_overlay).setBackgroundDrawable(new BitmapDrawable(getResources(), screenShotable.getBitmap()));
animator.start();
ContentFragment contentFragment = ContentFragment.newInstance(this.res);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, contentFragment).commit();
return contentFragment;
}
#Override
public ScreenShotable onSwitch(Resourceble slideMenuItem, ScreenShotable screenShotable, int position) {
switch (slideMenuItem.getName()) {
case ContentFragment.CLOSE:
return screenShotable;
default:
return replaceFragment(screenShotable, position);
}
}
#Override
public void disableHomeButton() {
getSupportActionBar().setHomeButtonEnabled(false);
}
#Override
public void enableHomeButton() {
getSupportActionBar().setHomeButtonEnabled(true);
drawerLayout.closeDrawers();
}
#Override
public void addViewToContainer(View view) {
linearLayout.addView(view);
}
}
Very Thanks for All
Hi currently I also using that library. I've attached my working code.
(In this case im using fragment)
Go and find how to use startActivity then you can use Intent & putExtra your resId.
#Override
public ScreenShotable onSwitch(Resourceble resourceble, ScreenShotable screenShotable, int position) {
int primaryColorCanvas = R.color.colorPrimary;
switch (resourceble.getName()) {
case ContentFragment.CLOSE:
return screenShotable;
case ContentFragment.DASHBOARD:
DashboardFragment fragment = DashboardFragment.newInstance(primaryColorCanvas);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).commit();
return replaceFragment(fragment, position);
case ContentFragment.FRIDGE:
FridgeFragment fragment2 = FridgeFragment.newInstance(primaryColorCanvas);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment2).commit();
return replaceFragment(fragment2, position);
case ContentFragment.COOKBOOK:
DashboardFragment fragment3 = DashboardFragment.newInstance(primaryColorCanvas);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment3).commit();
return replaceFragment(fragment3, position);
case ContentFragment.SHOPPINGLIST:
case ContentFragment.FEEDBACK:
ContentFragment fragment4 = ContentFragment.newInstance(primaryColorCanvas);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame,fragment4).commit();
return replaceFragment(fragment4, position);
default:
ContentFragment fragment0 = ContentFragment.newInstance(primaryColorCanvas);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame,fragment0).commit();
return replaceFragment(fragment0, position);
}
}
private ScreenShotable replaceFragment(ScreenShotable screenShotable, int position) {
int finalRadius = Math.max(contentFrame.getWidth(), contentFrame.getHeight());
SupportAnimator animator = ViewAnimationUtils.createCircularReveal(contentFrame, 0, position, 0, finalRadius);
animator.setInterpolator(new AccelerateInterpolator());
animator.setDuration(ViewAnimator.CIRCULAR_REVEAL_ANIMATION_DURATION);
findViewById(R.id.content_overlay).setBackground(new BitmapDrawable(getResources(), screenShotable.getBitmap()));
animator.start();
return screenShotable;
}
private void initializedMenu() {
SlideMenuItem menuItem0 = new SlideMenuItem(contentFragment.CLOSE, R.drawable.back_btn);
list.add(menuItem0);
SlideMenuItem menuItem = new SlideMenuItem(contentFragment.DASHBOARD, R.drawable.dashboard_icon_a);
list.add(menuItem);
SlideMenuItem menuIte2 = new SlideMenuItem(contentFragment.FRIDGE, R.drawable.fridge_icon_a);
list.add(menuIte2);
SlideMenuItem menuItem3 = new SlideMenuItem(contentFragment.COOKBOOK, R.drawable.cookbook_icon_a);
list.add(menuItem3);
SlideMenuItem menuItem4 = new SlideMenuItem(contentFragment.SHOPPINGLIST, R.drawable.right_icon_a);
list.add(menuItem4);
SlideMenuItem menuItem5 = new SlideMenuItem(contentFragment.FEEDBACK, R.drawable.feedback_icon_a);
list.add(menuItem5);
}
Remember that I've assigned static string variable in ContentFragment.
You can see at the initializedMenu().
Hope that help!
I am trying to update a image from another thread to a fragment via interface. The code does manage to get into the interface but every time it gets to Left_Image.setImageDrawable(Image_Rotated); I keep getting a null pointer exception. If on the on create for the fragment i set a image it works but as soon as it tries to do it for the interface it comes up with the null pointer exception. I used the command isAdded()) to check if the fragment is attached and that keeps coming back as nothing but i cant seem to fix it and have it attached. Here is the code
Fragment:
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.logging.Handler;
public class Augmented_Reality extends PreferenceFragment implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mRotationVectorSensor;
private Sensor mMagneticSensor;
private final float[] mRotationMatrix = new float[16];
private Boolean MagnetButtonPressed = false;
private Boolean Left;
private Boolean Right;
Boolean Admin_Mode;
boolean Lock = false;
public SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs";
ToggleButton HeadTracker;
TextView Position;
TextView Position_Left;
TextView Position_Right;
ImageView Left_Image;
ImageView Right_Image;
private Image_Packet_Flag Image_Flag;
public final byte Image_Sync_Flag = 0x09;
private Context context;
Activity activity;
public Augmented_Reality() {
Image_Flag = new Image_Packet_Flag();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
mRotationVectorSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
mMagneticSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mSensorManager.registerListener(this, mRotationVectorSensor, 10000);
mSensorManager.registerListener(this, mMagneticSensor, 10000);
} catch (Exception ex) {
Toast.makeText(getActivity().getApplicationContext(), "failed sensor", Toast.LENGTH_SHORT).show();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
activity = getActivity();
View rootView = inflater.inflate(R.layout.augmented_reality_view, container, false);
ActionBar actionBar = ((ActionBarActivity) activity).getSupportActionBar();
actionBar.hide();
HeadTracker = (ToggleButton) rootView.findViewById(R.id.HeadTracker);
Left_Image = (ImageView) rootView.findViewById(R.id.lefty);
Right_Image = (ImageView) rootView.findViewById(R.id.righty);
Bitmap icon = BitmapFactory.decodeResource(activity.getResources(),
R.drawable.ytyty);
BitmapDrawable Image = Rotate_Image(icon);
Left_Image.setImageDrawable(Image);
return rootView;
}
#Override
public void onSensorChanged(SensorEvent event) {
if (HeadTracker.isChecked() == true) {
if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
SensorManager.getRotationMatrixFromVector(
mRotationMatrix, event.values);
if (mRotationMatrix[2] >= 0.6 && mRotationMatrix[0] >= -0.1 && mRotationMatrix[0] <= 0.2) {
Left = true;
Right = false;
} else if (mRotationMatrix[2] <= -0.6 && mRotationMatrix[0] >= -0.1 && mRotationMatrix[0] <= 0.2) {
Left = false;
Right = true;
} else {
Left = false;
Right = false;
}
}
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
if (event.values[2] >= 390) {
MagnetButtonPressed = true;
} else {
MagnetButtonPressed = false;
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
public BitmapDrawable Rotate_Image(Bitmap Image) {
Bitmap bitmapOrg = Image;
int width = bitmapOrg.getWidth();
int height = bitmapOrg.getHeight();
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, width, height, matrix, true);
BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
return bmd;
}
public void UpdateImages(Bitmap Image) {
System.out.println("Image Updated");
final BitmapDrawable Image_Rotated = Rotate_Image(Image);
System.out.println("Is Added Result: " + isAdded());
if(isAdded()) {
System.out.println("Fragment Added");
Left_Image.setImageDrawable(Image_Rotated);
Right_Image.setImageDrawable(Image_Rotated);
}
}
}
MainActivity:
package com.example.jaynesh.mobile_robot_interface.Main_Files;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.jaynesh.mobile_robot_interface.Fragments.Augmented_Reality;
import com.example.jaynesh.mobile_robot_interface.Fragments.Main_Screen;
import com.example.jaynesh.mobile_robot_interface.Fragments.Settings;
import com.example.jaynesh.mobile_robot_interface.Fragments.Mission_Data;
import com.example.jaynesh.mobile_robot_interface.Navigation_Drawer.DrawerItemCustomAdapter;
import com.example.jaynesh.mobile_robot_interface.Navigation_Drawer.ObjectDrawerItem;
import com.example.jaynesh.mobile_robot_interface.Packets.Fragment_Tags.Augmented_Reality_Identifier;
import com.example.jaynesh.mobile_robot_interface.Packets.Fragment_Tags.Main_Screen_Identifier;
import com.example.jaynesh.mobile_robot_interface.Packets.Fragment_Tags.Mission_Data_Identifier;
import com.example.jaynesh.mobile_robot_interface.Packets.Fragment_Tags.Settings_Identifier;
import com.example.jaynesh.mobile_robot_interface.R;
import com.example.jaynesh.mobile_robot_interface.Socket.ClientThread;
public class MainActivity extends ActionBarActivity implements ClientThread.Image_Listener{
// declare properties
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
public SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs" ;
ClientThread clientThread;
private Augmented_Reality Augmented_Reality_Fragment;
private Main_Screen Main_Screen_Fragment;
private Mission_Data Mission_Data_Fragment;
private Settings Settings_Fragment;
private boolean Socket_Connected = false;
private int Current_Page = 0;
Main_Screen_Identifier MS;
Augmented_Reality_Identifier AR;
Mission_Data_Identifier MD;
Settings_Identifier SF;
Thread serverThread = null;
boolean NewPage = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
MS = new Main_Screen_Identifier();
AR = new Augmented_Reality_Identifier();
MD = new Mission_Data_Identifier();
SF = new Settings_Identifier();
NewPage = true;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// for proper titles
mTitle = mDrawerTitle = getTitle();
// initialize properties
mNavigationDrawerItemTitles = getResources().getStringArray(R.array.navigation_drawer_items_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// list the drawer items
ObjectDrawerItem[] drawerItem = new ObjectDrawerItem[4];
drawerItem[0] = new ObjectDrawerItem(R.drawable.ic_action_share, "Main Screen");
drawerItem[1] = new ObjectDrawerItem(R.drawable.ic_action_share, "Augment Reality View");
drawerItem[2] = new ObjectDrawerItem(R.drawable.ic_action_share, "Mission Data");
drawerItem[3] = new ObjectDrawerItem(R.drawable.ic_action_share, "Settings");
// Pass the folderData to our ListView adapter
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.listview_item_row, drawerItem);
// Set the adapter for the list view
mDrawerList.setAdapter(adapter);
// set the item click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// for app icon control for nav drawer
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mTitle);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(mDrawerTitle);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
if (savedInstanceState == null) {
// on first time display view for first nav item
selectItem(0);
}
}
#Override
public void OnNewImageListenerBitmap(final Bitmap Image) {
if (Thread.currentThread().getName() == "main") {
Augmented_Reality_Fragment.UpdateImages(Image);
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (Augmented_Reality_Fragment != null) {
Augmented_Reality_Fragment.UpdateImages(Image);
}
}
});
}
#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) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
// to change up caret
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
// navigation drawer click listener
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
Fragment fragment = null;
SharedPreferences.Editor editor = sharedpreferences.edit();
switch (position) {
case 0:
editor.putBoolean("Image_Listener", false);
editor.commit();
if (Main_Screen_Fragment == null) {
Main_Screen_Fragment = new Main_Screen();
}
fragment = Main_Screen_Fragment;
Current_Page = 1;
NewPage = true;
break;
case 1:
editor.putBoolean("Image_Listener", true);
editor.commit();
if (Augmented_Reality_Fragment == null) {
Augmented_Reality_Fragment = new Augmented_Reality();
}
fragment = new Augmented_Reality();
Current_Page = 2;
NewPage = true;
break;
case 2:
editor.putBoolean("Image_Listener", false);
editor.commit();
if (Mission_Data_Fragment == null) {
Mission_Data_Fragment = new Mission_Data();
}
fragment = Mission_Data_Fragment;
Current_Page = 3;
NewPage = true;
break;
case 3:
editor.putBoolean("Image_Listener", false);
editor.commit();
if (Settings_Fragment == null) {
Settings_Fragment = new Settings();
}
fragment = Settings_Fragment;
Current_Page = 4;
NewPage = true;
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#Override
public void onBackPressed() {
}
}
Thread on which Updated Interface:
if (Listener != null) {
System.out.println("Listener Found");
Image_data = BitmapFactory.decodeByteArray(tmp, 0, tmp.length);
System.out.println("Image Created");
Listener.OnNewImageListenerBitmap(Image_data);
//sendMessage(Image_Flag.to_byte_array(Image_Sync_Flag));
System.out.println("Updated");
}
Ive been stuck on this problem for a while now and im not sure whats going wrong, Any help would be awesome :)
Steve
///////////................\\\\\\
Added Crash log
08-02 01:16:29.997 26346-26346/com.interface E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageDrawable(android.graphics.drawable.Drawable)' on a null object reference
at com.example.jaynesh.mobile_robot_interface.Fragments.Augmented_Reality.UpdateImages(Augmented_Reality.java:215)
at com.example.jaynesh.mobile_robot_interface.Main_Files.MainActivity$2.run(MainActivity.java:180)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
EDIT: In your case 1, be sure to use the fragment that you had set earlier
You have:
if (Augmented_Reality_Fragment == null) {
Augmented_Reality_Fragment = new Augmented_Reality();
}
fragment = new Augmented_Reality();
You should have:
if (Augmented_Reality_Fragment == null) {
Augmented_Reality_Fragment = new Augmented_Reality();
}
fragment = Augmented_Reality_Fragment;
Context:
I am new to android. I have created a navigation drawer with fragments. When I run my code the app works but the choreographer says:
** frames skipped, heavy work is done in main thread.
The Problem:
The App became slow when I move to a fragment layout where there is more data. I searched for how to solve this problem and I learned using threads will solve the issue but I am so confused to use it.
Can anyone help me?
The Code:
package com.example.venkatesh.settaiboyz;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public final void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = home_fragment.newInstance(position + 1);
break;
case 1:
fragment = member_fragment.newInstance(position + 1);
break;
case 2:
fragment = photo_fragment.newInstance(position + 1);
break;
case 3:
fragment = event_fragment.newInstance(position + 1);
break;
case 4:
fragment = about_fragment.newInstance(position + 1);
break;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
case 4:
mTitle = getString(R.string.title_section4);
break;
case 5:
mTitle = getString(R.string.title_section5);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
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";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static Fragment 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.home_layout, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (item.getItemId()) {
case R.id.action_facebook:
Open_facebook();
return true;
case R.id.action_twitter:
Open_Twitter();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//Anvar
public void OpenActivityAnvar(View view) {
setContentView(R.layout.anvar);
ImageButton b;
b = (ImageButton) findViewById(R.id.call_anvar);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:+919841463562"));
startActivity(callIntent);
}
});
b = (ImageButton) findViewById(R.id.sms_anvar);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address", "+919841463562");
smsIntent.putExtra("sms_body", "");
startActivity(smsIntent);
}
});
b = (ImageButton) findViewById(R.id.mail_anvar);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);//common intent
intent.setData(Uri.parse("mailto:mailtoanvar8055#gmail.com"));
startActivity(intent);
}
});
}
//Main menu list
public void Open_facebook() {
Uri webpage = Uri.parse("https://www.facebook.com/settaiboyz");
Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);
startActivity(webIntent);
}
public void Open_Twitter() {
Uri webpage = Uri.parse("https://www.Twitter.com");
Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);
startActivity(webIntent);
}
}
I am making some android apps with viewpager in fragment. It shows tabs correct, but I can't see any content in my code. I trying to find and search in stackoverflow and google but I don't know why this code is not working. The code looks strange and i am very sorry about that. I am a first quesiton on here. Thx to help me :-)
This is MainActivity.java
package com.yeungnam.food;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.Fragment;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
CustomDrawerAdapter adapter;
List<DrawerItem> dataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing
dataList = new ArrayList<DrawerItem>();
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
/* mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START); */
dataList.add(new DrawerItem(true));
dataList.add(new DrawerItem("Message", R.drawable.ic_action_camera));
dataList.add(new DrawerItem("Likes", R.drawable.ic_action_cloud));
dataList.add(new DrawerItem("Games", R.drawable.ic_action_email));
adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,
dataList);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
SelectItem(1);
}
}
public void SelectItem(int possition) {
Fragment fragment = null;
Bundle args = new Bundle();
switch (possition) {
case 1:
fragment = new FragmentFood();
/* args.putString(FragmentFood.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentFood.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID()); */
break;
case 2:
fragment = new FragmentFood();
/* args.putString(FragmentFood.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentFood.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID()); */
break;
case 3:
fragment = new FragmentFood();
/* args.putString(FragmentFood.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentFood.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID()); */
break;
default:
break;
}
fragment.setArguments(args);
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment)
.commit();
mDrawerList.setItemChecked(possition, true);
setTitle(dataList.get(possition).getItemName());
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return false;
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if(dataList.get(position).isFirst == false)
SelectItem(position);
}
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
} */
}
This is FragmentFood.java
package com.yeungnam.food;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.astuetz.PagerSlidingTabStrip;
public class FragmentFood extends Fragment {
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private FoodAdapter adapter;
public FragmentFood() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_food, container,
false);
tabs = (PagerSlidingTabStrip) view.findViewById(R.id.tabs);
pager = (ViewPager) view.findViewById(R.id.pager);
adapter = new FoodAdapter(getActivity());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
return view;
}
public class FoodAdapter extends PagerAdapter {
private final String[] TITLES = { "breafkast", "lunch", "dinner" };
private LayoutInflater mInflater;
public FoodAdapter(Context c) {
super(); mInflater = LayoutInflater.from(c);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Object instantiateItem(ViewGroup pager, int position) {
// looks a little bit messy here
TextView v = new TextView(getActivity());
v.setBackgroundResource(R.color.background_window);
v.setText("PAGE " + (position + 1));
final int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, getResources()
.getDisplayMetrics());
v.setPadding(padding, padding, padding, padding);
v.setGravity(Gravity.CENTER);
pager.addView(v, 0);
return v;
}
#Override
public void destroyItem(ViewGroup container, int position, Object view) {
container.removeView((View) view);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
}
}
I also encountered a similar problem,but i use FragmentAdapter. you can refer to the following:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_first_main, container, false);
textViewMesuemInfo = (TextView) view.findViewById(R.id.textViewMesuemInfo);
textViewOpenInfo = (TextView) view.findViewById(R.id.textViewOpenInfo);
fragmentAdapter = new IntroPagerAdapter(**getChildFragmentManager()**);
sliViewPager = (ViewPager) view.findViewById(R.id.viewPagerMain);
sliViewPager.setOnPageChangeListener(pagerChangeListener);
sliViewPager.setAdapter(fragmentAdapter);
sliViewPager.setCurrentItem(0);
return view;
}
private class IntroPagerAdapter extends FragmentPagerAdapter {
public IntroPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 4;
}
#Override
public Fragment getItem(int position) {
Log.i("position=",position+"");
switch (position) {
case 0:
return new IntroFragment().setLayout(R.layout.fragment_colckbuild);
case 1:
return new IntroFragment().setLayout(R.layout.fragment_playclock);
case 2:
return new IntroFragment().setLayout(R.layout.fragment_measureinfo);
case 3:
return new IntroFragment().setLayout(R.layout.fragment_playclock);
default:
return null;
}
}
I have created a activity(MainActivity.java) extends to Activity.java
and again I create the another activity(prodicts.java) now here I extends this activity(products.java) to MainActivity.java
So my question is that which onCreate(bundle) will call in my products.java class its super class onCreate(bundle) or its own onCreate(bundle) and my code is below:
MainActivity.java
import java.util.Locale;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
protected DrawerLayout mDrawerLayout;
private ListView mDrawerList;
public ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.List_Content);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
//displayView(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
displayView(position);
}
}
#SuppressWarnings("unused")
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0: Intent product = new Intent(MainActivity.this,Products.class);
startActivity(product);
break;
case 1: Intent notes = new Intent (MainActivity.this,Notes.class);
startActivity(notes);
break;
case 2: Intent Contacts = new Intent (MainActivity.this,Contacts.class);
startActivity(Contacts);
break;
case 3:
Intent viewPdf = new Intent (MainActivity.this,pdfView.class);
startActivity(viewPdf);
break;
case 4:
Intent search = new Intent (MainActivity.this,search.class);
startActivity(search);
break;
/*case 5:
fragment = new WhatsHotFragment();
break;*/
default:
break;
}
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
//setTitle(mDrawerList[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PlanetFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.List_Content)[i];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
}
and products.java
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;
public class Products extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
LayoutInflater inflater = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(R.layout.products, null, false);
mDrawerLayout.addView(contentView, 0);
GridView gridview = (GridView)findViewById(R.id.productgridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(Products.this, " "+position, Toast.LENGTH_SHORT).show();
}
});
}
}
So please tell what will happen in this Activity , I am confused about it.
when i will call the products.java class which onCreate(bundle) it will call MainActivity.java's onCreate(bundle) or products.java's onCreate(bundle).
onCreate() of Product Class will be called, then onCreate() of MainActivity class and finally onCreate() of Activity class will be called.