ImageView Scrolls But Disappears - Android Software Development

Okay so after working hard I finally have scrolling somewhat working using the information from the accelerometer. I am using scrollBy() to make it move. But it scrolls I guess what you could say "in spot". It disappears when it goes outside its bounds. Here is my code:
Code:
package com.bobhoil.tdodger;
import android.app.Activity;
import android.os.Bundle;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.widget.ImageView;
import android.widget.TextView;
public class TestActivity extends Activity implements SensorEventListener {
private int accelXValue;
private int accelYValue;
private TextView accelZValue;
private ImageView mobil1;
private SensorManager sensorManager = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
setContentView(R.layout.test);
accelZValue = (TextView) findViewById(R.id.accel_z_value);
mobil1 = (ImageView) findViewById(R.id.mobil);
accelZValue.setText("0.00");
}
public void onSensorChanged(SensorEvent sensorEvent) {
synchronized (this) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
accelXValue = (int) sensorEvent.values[0];
accelYValue = (int) sensorEvent.values[1];
accelZValue.setText(Float.toString(sensorEvent.values[2]));
}
mobil1.scrollBy(accelXValue,accelYValue);
}
}
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
}
@Override
protected void onStop() {
sensorManager.unregisterListener(this);
super.onStop();
}
}

Can I get some assistance please?

Okay so I tried using a few other ways of moving the imageview but it is still doing the same thing. Is it that I am using a absolute view??

I'd definitely recommend against using an AbsoluteLayout, but I'm guessing that you intend for the ImageView to move within another layout and instead you're telling the ImageView to move within itself. Basically, the scroll methods scroll the content of a view, so you would want to scroll a parent view if you're intending to move the ImageView.

So right now it isn't scrolling the ImageView? It is scrolling within the ImageView?
So now I need to figure out how to move a view in a view?
Just making sure I understood this.

Can I get some more help? I really need this for my game..

Related

TextView Into and Integer

I am trying to pass information from a text view into an ImageView to move the ImageView. The problem is I can't use the TextView information because it is defined as a TextView. So is there a way I can get it to use the TextView as an integer?
Do you mean you want to convert the text string in the textview to an integer? There's the java.lang.Integer class which has a static member parseInt() which might do what you need:
http://developer.android.com/reference/java/lang/Integer.html#parseInt(java.lang.String)
Not completely sure what your looking for but if I read it right,
imageView.setMethod(parseInt(textView.getText()))
setMethod being which ever method your trying to set the int into.
I need the data from my accelerometer code which looks like so:
package com.bobhoil.tdodger;
import android.app.Activity;
import android.os.Bundle;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.widget.TextView;
public class TestActivity extends Activity implements SensorEventListener {
private TextView accelXValue;
private TextView accelYValue;
private TextView accelZValue;
private SensorManager sensorManager = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
setContentView(R.layout.test);
accelXValue = (TextView) findViewById(R.id.accel_x_value);
accelYValue = (TextView) findViewById(R.id.accel_y_value);
accelZValue = (TextView) findViewById(R.id.accel_z_value);
accelXValue.setText("0.00");
accelYValue.setText("0.00");
accelZValue.setText("0.00");
}
public void onSensorChanged(SensorEvent sensorEvent) {
synchronized (this) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
accelXValue.setText(Float.toString(sensorEvent.values[0]));
accelYValue.setText(Float.toString(sensorEvent.values[1]));
accelZValue.setText(Float.toString(sensorEvent.values[2]));
}
}
}
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
}
@Override
protected void onStop() {
sensorManager.unregisterListener(this);
super.onStop();
}
}
Click to expand...
Click to collapse
I need to put that into my imageview and use scrollby to move the imageview around the screen.
I'm not too familiar with imageviews, are you using XMLs for the layout or creating the imageViews programmaticly? I'm assuming the textViews and imageViews are in seperate classes. Thus the easiest way to get the text from the textViews would be to first give them the "protected" token rather than "private" and reference them directly.
Code:
imageView.scrollBy(parseInt(TestActivity.accelXValue.getText()));
I have tried that before but no matter what I try I get an error. Here is the error:
Cannot make a static reference to the non-static field TestActivity.accelXValue
Click to expand...
Click to collapse
So then I change it to static and get the following error:
The method parseInt(CharSequence) is undefined for the type TestActivity
Click to expand...
Click to collapse
I can't seem to get something that seems so simple to work.

last tempt at asking for help

Ok all i have tried for weeks now to get a simple webview app sorted. i have managed to get this up on the market but it needs a few more features like menu for refresh back forward etc.
It seems nobody really wants to helps so how much will it cost me for you to help with it?
explain a little more, you after someone to code it for you or design the ui ?
Well basically I got a basic webview made from tutorials, but that is about as far as my skills go. I need a few more features like options menu, stop the back button exiting app and go back a page instead and also if possible but not essential change loading bar for loading circle which spins in middle if screen while loading. I have tried to ask for help with what code I need and where to put it but no luck. I pretty much need it coded or at least to be told what code and exactly where in my code I need to fit it in.
Sent from my Desire HD using XDA App
Where have you tried asking? Tackle one issue at a time, and post some example code.
StackOverflow is a great site for programming questions and you should get some good answers there.
But before posting make sure you search first.
The back button shouldnt exit the app if there is a activity that was displayed before it.
cyberpedz said:
Ok finally i have a running webview in the market what i would like to do now is add a soft menu for a back, refresh and forward button what code do i need and where would i put it in my java below?
Code:
package com.windowcleaningforums;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class windowcleaningforums extends Activity
{
final Activity activity = this;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
WebView webView = (WebView) findViewById(R.id.WebView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle(" Loading...");
activity.setProgress(progress * 100);
if(progress == 100)
activity.setTitle(R.string.app_name);
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
// Handle the error
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://www.windowcleaningforums.co.uk");
}
}
Click to expand...
Click to collapse
Sent from my Desire HD using XDA App
Sent from my Desire HD using XDA App
I found this tutorial after a quick google search - http://kahdev.wordpress.com/2008/11/25/building-a-menu-for-your-android-v10-r1-app/
It seems quite simple to follow. Let me know if you have any issues and I try give you an example for your code tonight.
Ok I have edited your code to add a menu, and also to set the back button of the phone to go back to the previous page in the webview, instead of previous activity.
I found the code for this here
I have commented bits of the code so hopefully its understandable.
If you have any questions or it doesn't work let me know.
Don't just take what I have done and use it (although you can). Go through it and make sure you understand what I have done. That's the only way you will learn app development.
Code:
package com.windowcleaningforums;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class windowcleaningforums extends Activity {
final Activity activity = this;
//DECLARE webview variable outside of onCreate function so we can access it in other functions (menu)
public WebView webView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
webView = (WebView) findViewById(R.id.WebView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setTitle(" Loading...");
activity.setProgress(progress * 100);
if (progress == 100)
activity.setTitle(R.string.app_name);
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// Handle the error
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://www.windowcleaningforums.co.uk");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//Add menu items, second value is the id, use this in the onOptionsItemSelected
menu.add(0,1, 0, "Back");
menu.add(0, 2, 0, "Forward");
return true;
}
@Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()){
//If the ID equals 1 , go back
case 1:
webView.goBack();
return true;
//If the ID equals 2 , go forward
case 2 :
webView.goForward();
return true;
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
I have seen these tutorials but my problem is I don't know how to fit it into my webview where should I add this in my code
Sent from my Desire HD using XDA App
Have a look at the code I posted.
What we are basically doing is adding new functions (or methods) inside our activity class. When I first started app development I also got confused as to where to add things.
These new methods override methods built into the activity, so we don't want to put them inside our onCreate method (where everything goes for setting up the activity, and where all your current code resides).
So we put them at any position after the closing brace of our onCreate. I've put them at the end.
I also moved the declaration of the webView variable to outside the onCreate method, so we can access it in the other functions we added.
Thank you so much I will look at this properly when I next get chance on my pc. thanks again for the help and taking the time to explain.
Sent from my Desire HD using XDA App
Thank you have have looked over the code and even added another button!
I have also added icons for each menu item after looking over some other code but not sure if i have done it correctly. they dont show untill the menu item has been clicked once. how can i get them to show right away? i put the images in res/drawable and called then in the code below, is this the correct way to do it?
Code:
package com.windowcleaningforums;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class windowcleaningforums extends Activity {
final Activity activity = this;
//DECLARE webview variable outside of onCreate function so we can access it in other functions (menu)
public WebView webView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
webView = (WebView) findViewById(R.id.WebView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setTitle(" Loading...");
activity.setProgress(progress * 100);
if (progress == 100)
activity.setTitle(R.string.app_name);
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// Handle the error
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://www.windowcleaningforums.co.uk");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//Add menu items, second value is the id, use this in the onOptionsItemSelected
menu.add(0,1, 0, "Back");
menu.add(0, 2, 0, "Forward");
menu.add(0, 3, 0, "Refresh");
return true;
}
@Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()){
//If the ID equals 1 , go back
case 1:
webView.goBack();
item.setIcon(R.drawable.back);
return true;
//If the ID equals 2 , go forward
case 2 :
webView.goForward();
item.setIcon(R.drawable.forward);
return true;
//If the ID equals 3 , go back
case 3:
webView.reload();
item.setIcon(R.drawable.refresh);
return true;
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Comments below (marked -->), I'm not going to give you the answer, you need to understand why more that how.
Code:
package com.windowcleaningforums;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class windowcleaningforums extends Activity {
final Activity activity = this;
//DECLARE webview variable outside of onCreate function so we can access it in other functions (menu)
public WebView webView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
webView = (WebView) findViewById(R.id.WebView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setTitle(" Loading...");
activity.setProgress(progress * 100);
if (progress == 100)
activity.setTitle(R.string.app_name);
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// Handle the error
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://www.windowcleaningforums.co.uk");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//Add menu items, second value is the id, use this in the onOptionsItemSelected
menu.add(0,1, 0, "Back");
menu.add(0, 2, 0, "Forward");
menu.add(0, 3, 0, "Refresh");
//--> Here you have finished configuring the menu
return true;
}
@Override
public boolean onOptionsItemSelected (MenuItem item){
// -->This is called when you select/tap a menu item (look at the method name)
switch (item.getItemId()){
//If the ID equals 1 , go back
case 1:
webView.goBack();
// --> Hence this happens _after_ you have tapped on the back menu item
item.setIcon(R.drawable.back);
return true;
//If the ID equals 2 , go forward
case 2 :
webView.goForward();
item.setIcon(R.drawable.forward);
return true;
//If the ID equals 3 , go back
case 3:
webView.reload();
item.setIcon(R.drawable.refresh);
return true;
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
As SilentMobius' comments pointout, you need to set your icons in the onCreateOptionsMenu, not the onOptionsItemSelected.
That's why they are only showing when you select the button.
Ah great thanks i figured it, didn't want to be given correct code just you giving the correct info to sort my self is good i know these are most likely simple things but nobody learns unless they ask questions thanks again.
Check my apps out in the market Luvdroid and window cleaning forums
Would you mind sharing your back, forward and refresh icons with me? I'm looking for something very clean and standardized for use on 12 webview apps for the some of the local municipalities.
SilentMobius said:
Comments below (marked -->), I'm not going to give you the answer, you need to understand why more that how.
Code:
package com.windowcleaningforums;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class windowcleaningforums extends Activity {
final Activity activity = this;
//DECLARE webview variable outside of onCreate function so we can access it in other functions (menu)
public WebView webView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
webView = (WebView) findViewById(R.id.WebView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setTitle(" Loading...");
activity.setProgress(progress * 100);
if (progress == 100)
activity.setTitle(R.string.app_name);
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// Handle the error
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.loadUrl("m.xxx.co.jp");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//Add menu items, second value is the id, use this in the onOptionsItemSelected
menu.add(0,1, 0, "Back");
menu.add(0, 2, 0, "Forward");
menu.add(0, 3, 0, "Refresh");
//--> Here you have finished configuring the menu
return true;
}
@Override
public boolean onOptionsItemSelected (MenuItem item){
// -->This is called when you select/tap a menu item (look at the method name)
switch (item.getItemId()){
//If the ID equals 1 , go back
case 1:
webView.goBack();
// --> Hence this happens _after_ you have tapped on the back menu item
item.setIcon(R.drawable.back);
return true;
//If the ID equals 2 , go forward
case 2 :
webView.goForward();
item.setIcon(R.drawable.forward);
return true;
//If the ID equals 3 , go back
case 3:
webView.reload();
item.setIcon(R.drawable.refresh);
return true;
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Click to expand...
Click to collapse

[Q] Drawing a circle custom view centered with pinch zoom gesture

I'm trying to make a custom view that draw a circle in the center os this view (position always fixed) and I want to implement the scale of this circule use pinch gesture (I've used ScaleGestureDetector).
I managed to draw the circle in the center of the custom layout but I can not implement the functionality of scaling correctly using pinch gesture.
Please, can you give a hint please how I could do it?
Thanks in advance!!
Code:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
public class CoasterView extends View {
private static float MIN_ZOOM = 0;
private static float MAX_ZOOM = 5f;
private static float RADIO = 100f;
private float scaleFactor = 1.f;
private ScaleGestureDetector detector;
Paint paint;
public CoasterView(Context paramContext) {
super(paramContext);
detector = new ScaleGestureDetector(paramContext, new ScaleListener());
init();
}
public CoasterView(Context paramContext, AttributeSet paramAttributeSet) {
super(paramContext, paramAttributeSet);
detector = new ScaleGestureDetector(getContext(), new ScaleListener());
init();
}
public CoasterView(Context paramContext, AttributeSet paramAttributeSet, int paramInt) {
super(paramContext, paramAttributeSet, paramInt);
detector = new ScaleGestureDetector(getContext(), new ScaleListener());
init();
}
private void init() {
this.paint = new Paint();
this.paint.setColor(-16711936);
this.paint.setStrokeWidth(40.0F);
this.paint.setStyle(Paint.Style.FILL);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
canvas.scale(scaleFactor, scaleFactor);
canvas.drawCircle(getWidth() / 2, getHeight() / 2, RADIO, paint);
canvas.restore();
}
[user=439709]@override[/user]
public boolean onTouchEvent(MotionEvent event) {
detector.onTouchEvent(event);
invalidate();
return true;
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
[user=439709]@override[/user]
public boolean onScale(ScaleGestureDetector detector) {
scaleFactor *= detector.getScaleFactor();
scaleFactor = Math.max(MIN_ZOOM, Math.min(scaleFactor, MAX_ZOOM));
invalidate();
return true;
}
}
}

How to use Navigation Drawer inside Tabs menu.

Hi guys.
I've been developing an app which has Swipeable menu in bottom and one of the pages , should have a Navigation Drawer to change its own Fragments.
MainActivity.java
Code:
package com.example.elizehprotowithshlkandvpis;
import com.example.elizehprotowithshlkandvpis.adapter.MainMenuAdapter;
import com.viewpagerindicator.TabPageIndicator;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
private static final String[] CONTENT = { "Home", "AboutUs", "Maps", "Resturants", "Tours", "CustomerClub", "Neccesseries", "UrgentCall" };
private ViewPager mViewPager;
private FragmentPagerAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new MainMenuAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator) findViewById(R.id.indicator);
indicator.setViewPager(mViewPager);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public static String[] getCONTENT() {
return CONTENT;
}
}
MainMenuAdapter.java
Code:
package com.example.elizehprotowithshlkandvpis.adapter;
import com.example.elizehprotowithshlkandvpis.MainActivity;
import com.example.menuclasses.AboutUs;
import com.example.menuclasses.CustomerClub;
import com.example.menuclasses.Maps;
import com.example.menuclasses.Neccesseries;
import com.example.menuclasses.Tours;
import com.example.menuclasses.UrgentCall;
import com.example.menuclasses.Resturants;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MainMenuAdapter extends FragmentPagerAdapter {
private static final String[] CONTENT = { "Home", "AboutUs", "Maps", "Resturants", "Tours", "CustomerClub", "Neccesseries", "UrgentCall" };
private final int HOME_INDEX = 0;
private final int ABOUTUS_INDEX = 1;
private final int MAPS_INDEX = 2;
private final int RESTURANTS_INDEX = 3;
private final int TOURS_INDEX = 4;
private final int CUSTOMERCLUB_INDEX = 5;
private final int NECCESSERIES_INDEX = 6;
private final int URGENTCALL_INDEX = 7;
private final int NUMBEROFMENUS = CONTENT.length;
public MainMenuAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
@Override
public CharSequence getPageTitle(int position) {
String[] CONTENT = MainActivity.getCONTENT();
return CONTENT[position % CONTENT.length].toUpperCase();
}
@Override
public Fragment getItem(int index) {
switch(index) {
case HOME_INDEX:
return new AboutUs();
case ABOUTUS_INDEX:
return new AboutUs();
case MAPS_INDEX:
return new Maps();
case RESTURANTS_INDEX:
return new Resturants();
case TOURS_INDEX:
return new Tours();
case CUSTOMERCLUB_INDEX:
return new CustomerClub();
case NECCESSERIES_INDEX:
return new Neccesseries();
case URGENTCALL_INDEX:
return new UrgentCall();
}
return null;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return NUMBEROFMENUS;
}
}
The Fragment that should contain a Navigation Drawer is Resturants , also drawer's mainactivity is implemented with Sherlock Library(SherlockFragmentActivity).
I'm puzzled how to call the SherlockFragmentActivity from the SherlockActivity
Thanks
Pouya_am said:
Hi guys.
I've been developing an app which has Swipeable menu in bottom and one of the pages , should have a Navigation Drawer to change its own Fragments.
MainActivity.java
Code:
package com.example.elizehprotowithshlkandvpis;
import com.example.elizehprotowithshlkandvpis.adapter.MainMenuAdapter;
import com.viewpagerindicator.TabPageIndicator;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
private static final String[] CONTENT = { "Home", "AboutUs", "Maps", "Resturants", "Tours", "CustomerClub", "Neccesseries", "UrgentCall" };
private ViewPager mViewPager;
private FragmentPagerAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new MainMenuAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator) findViewById(R.id.indicator);
indicator.setViewPager(mViewPager);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public static String[] getCONTENT() {
return CONTENT;
}
}
MainMenuAdapter.java
Code:
package com.example.elizehprotowithshlkandvpis.adapter;
import com.example.elizehprotowithshlkandvpis.MainActivity;
import com.example.menuclasses.AboutUs;
import com.example.menuclasses.CustomerClub;
import com.example.menuclasses.Maps;
import com.example.menuclasses.Neccesseries;
import com.example.menuclasses.Tours;
import com.example.menuclasses.UrgentCall;
import com.example.menuclasses.Resturants;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MainMenuAdapter extends FragmentPagerAdapter {
private static final String[] CONTENT = { "Home", "AboutUs", "Maps", "Resturants", "Tours", "CustomerClub", "Neccesseries", "UrgentCall" };
private final int HOME_INDEX = 0;
private final int ABOUTUS_INDEX = 1;
private final int MAPS_INDEX = 2;
private final int RESTURANTS_INDEX = 3;
private final int TOURS_INDEX = 4;
private final int CUSTOMERCLUB_INDEX = 5;
private final int NECCESSERIES_INDEX = 6;
private final int URGENTCALL_INDEX = 7;
private final int NUMBEROFMENUS = CONTENT.length;
public MainMenuAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
@Override
public CharSequence getPageTitle(int position) {
String[] CONTENT = MainActivity.getCONTENT();
return CONTENT[position % CONTENT.length].toUpperCase();
}
@Override
public Fragment getItem(int index) {
switch(index) {
case HOME_INDEX:
return new AboutUs();
case ABOUTUS_INDEX:
return new AboutUs();
case MAPS_INDEX:
return new Maps();
case RESTURANTS_INDEX:
return new Resturants();
case TOURS_INDEX:
return new Tours();
case CUSTOMERCLUB_INDEX:
return new CustomerClub();
case NECCESSERIES_INDEX:
return new Neccesseries();
case URGENTCALL_INDEX:
return new UrgentCall();
}
return null;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return NUMBEROFMENUS;
}
}
The Fragment that should contain a Navigation Drawer is Resturants , also drawer's mainactivity is implemented with Sherlock Library(SherlockFragmentActivity).
I'm puzzled how to call the SherlockFragmentActivity from the SherlockActivity
Thanks
Click to expand...
Click to collapse
That last sentence does not make sense I assume you mean from the Fragment?! Well to access the holding activity you need to add an interface to the Fragment which the activity will implement.
Am I understanding you correctly that have a horizontal ViewPager and one of the Fragments should have a Navigation drawer? To accomplish that you would still need the whole activity to hold the drawer and figure out a way to disable it when the user is on some other Fragment. But my question is why you want to use a navigation drawer in that case, because the drawer is meant for navigating on the same hierarchical level, but the different items are more independent than with the ViewPager. It doesn't really make sense to have both a drawer and horizontal swiping, even the YouTube app really bothers me with its swiping between suggestions and feed. I think what you need to use here is a spinner in the ActionBar, replacing the title of the Fragment.
SimplicityApks said:
That last sentence does not make sense I assume you mean from the Fragment?! Well to access the holding activity you need to add an interface to the Fragment which the activity will implement.
Am I understanding you correctly that have a horizontal ViewPager and one of the Fragments should have a Navigation drawer? To accomplish that you would still need the whole activity to hold the drawer and figure out a way to disable it when the user is on some other Fragment. But my question is why you want to use a navigation drawer in that case, because the drawer is meant for navigating on the same hierarchical level, but the different items are more independent than with the ViewPager. It doesn't really make sense to have both a drawer and horizontal swiping, even the YouTube app really bothers me with its swiping between suggestions and feed. I think what you need to use here is a spinner in the ActionBar, replacing the title of the Fragment.
Click to expand...
Click to collapse
Yeah you're right , I just want to use the drawer in order to change contents.
So as you suggest , I just have to use a simple tricks to make the drawer enable in desire Fragment.
I don't want to , I am asked to make it possible....

How to make the buttons in a fragment manipulate integer variables in seperate activi

This is a rudimentary android application that serves as an umpires strike/ball/out counter. There is a settings icon in the action bar of the MainActivity. When this icon is 'clicked on', a new Activity is started consisting of a PreferenceFragment, which consists of a checkboxpreference, and a Fragment that consists of 3 buttons. These buttons reset the stike_count, ball_count and total_outs_count to zero. I have spent a day on this and am having trouble figuring out how to manipulate integer variables in my MainActivity from button clicks in a seperate Activity's Fragment. Please point me in the right direction.
package edu.umkc.baldwin;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "UmpireActivity";
// Constant variables declared/initialized to keep track of values
// across lifecycle states
@SuppressWarnings("unused")
private static final String STRIKES = "0";
@SuppressWarnings("unused")
private static final String BALLS = "0";
@SuppressWarnings("unused")
private static final String OUTS = "0";
TextView strikeCounterTV;
TextView ballCounterTV;
TextView totalOutCounterTV;
private Button strikeCounterButton;
private Button ballCounterButton;
private int strike_count;
private int ball_count;
private int out_count;
private void updateViews(){
strikeCounterTV.setText(String.valueOf(strike_count));
ballCounterTV.setText(String.valueOf(ball_count));
totalOutCounterTV.setText(String.valueOf(out_count));
}
private void displayToast(boolean x){
int messageId = 0;
if (x == true){
messageId = R.string.strike_toast_view;
} else {
messageId = R.string.ball_toast_view;
}
Toast toast = Toast.makeText(MainActivity.this, messageId,
Toast.LENGTH_SHORT);
LinearLayout toastLayout = (LinearLayout) toast.getView();
TextView toastTV = (TextView) toastLayout.getChildAt(0);
toast.setGravity(Gravity.CENTER|Gravity.CENTER, 0, -150);
toastTV.setTextSize(42);
toast.show();
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "OnCreate(Bundle) called");
setContentView(R.layout.main_page_layout);
//Declare TextView objects and Button objects
strikeCounterTV = (TextView) findViewById(R.id.strikeCountTextView);
ballCounterTV = (TextView) findViewById(R.id.ballCountTextView);
totalOutCounterTV = (TextView) findViewById(R.id.totalOutsTextViewCounter);
strikeCounterButton = (Button) findViewById(R.id.strikeCountButton);
ballCounterButton = (Button) findViewById(R.id.ballCountButton);
strikeCounterButton.setOnClickListener(new OnClickListener(){
@override
public void onClick(View v) {
if (strike_count < 2){
strike_count++;
updateViews();
} else {
// batter has reached strike limit
displayToast(true);
out_count++;
strike_count = 0;
ball_count = 0;
updateViews();
}
}
});
ballCounterButton.setOnClickListener(new OnClickListener(){
@override
public void onClick(View v) {
if (ball_count < 3){
ball_count++;
updateViews();
} else {
// batter has reached ball limit
displayToast(false);
strike_count = 0;
ball_count = 0;
updateViews();
}
}
});
// Check for screen rotation
if (savedInstanceState == null){
strike_count = 0;
ball_count = 0;
} else {
strike_count = savedInstanceState.getInt("STRIKES");
ball_count = savedInstanceState.getInt("BALLS");
}
// Save 'totalOuts' variable through application exit
SharedPreferences savedObject = getPreferences(Context.MODE_PRIVATE);
out_count = savedObject.getInt(getString(R.string.total_outs_key), 0);
updateViews();
}
@override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.d(TAG, "onSaveInstanceState() called");
savedInstanceState.putInt("STRIKES", strike_count);
savedInstanceState.putInt("BALLS", ball_count);
savedInstanceState.putInt("OUTS", out_count);
}
@override
public boolean onCreateOptionsMenu(Menu menu) {
//Displays actionbar items in app actionbar
getMenuInflater().inflate(R.menu.actionbar_layout, menu);
return super.onCreateOptionsMenu(menu);
}
@override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
switch (item.getItemId()){
case (R.id.reset_option):
strike_count = 0;
ball_count = 0;
updateViews();
return true;
case (R.id.about_menu_option):
Intent i = new Intent(this, About.class);
startActivity(i);
return true;
case (R.id.settings_menu_option):
Intent j = new Intent(this, SettingsActivity.class);
startActivity(j);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
@override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
}
@override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
@override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop() called");
SharedPreferences out_file = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = out_file.edit();
editor.putInt(getString(R.string.total_outs_key), out_count);
editor.commit();
}
@override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() called");
}
}
package edu.umkc.baldwin;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
public class SettingsActivity extends Activity {
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_layout);
FragmentManager ttsFragmentManager = getFragmentManager();
FragmentTransaction ttsFragmentTransaction = ttsFragmentManager.beginTransaction();
EnableTTSPreferenceFragment ttsFragment = new EnableTTSPreferenceFragment();
ttsFragmentTransaction.add(R.id.tts_fragment, ttsFragment);
ttsFragmentTransaction.commit();
FragmentManager resetFragmentManager = getFragmentManager();
FragmentTransaction resetFragmentTransaction = resetFragmentManager.beginTransaction();
ResetFragment resetFragment = new ResetFragment();
resetFragmentTransaction.add(R.id.reset_fragment, resetFragment);
resetFragmentTransaction.commit();
}
}
package edu.umkc.baldwin;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ResetFragment extends Fragment {
@override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View resetFragment = inflater.inflate(R.layout.reset_layout, container, false);
return resetFragment;
}
}
package edu.umkc.baldwin;
import android.os.Bundle;
import android.preference.PreferenceFragment;
public class EnableTTSPreferenceFragment extends PreferenceFragment {
@override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.tts_preference_fragment);
}
@override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
}
To modify anything in your activity from one of its child Fragments you would typically create an interface in the Fragment and have the activity implement that. That interface would either contain one method setting all three vars or multiple ones, one for each variable. To call the methods in the interface call getActivity() and typecast it to the interface.

Categories

Resources