Cleaning up a one file project - java

So I'm working on a project and am using a lot of code or atleast a decent amount all in one file and am wondering if there is a way to clean it up into multiple files. I've only every worked with single file. So when It come to adding more files I'm not really sure how to go about this so I'm gonna ask for help on cleaning up the project. the ideal outcome is to have it more understandable via small chunks in other files to clean up the CoreActivity. or if you see a way to clean up some code into a easier and less exhaustive way of writing it then do fix
CoreActivity.java
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;
import com.github.pwittchen.gesture.library.Gesture;
import com.github.pwittchen.gesture.library.GestureListener;
import com.github.pwittchen.swipe.library.rx2.Swipe;
import com.github.pwittchen.swipe.library.rx2.SwipeListener;
public class CoreActivity extends AppCompatActivity {
//Widgets
ConstraintLayout m_Preference_Toolbar;
ConstraintLayout m_Toolbar;
ConstraintLayout m_Preferences;
EditText m_WebView_Search;
WebView m_WebView;
private Swipe WebSwipe;
private Gesture WebGesture;
//Variables
String Url = "https://www.Google.ca";
int WebS =0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_core);
//Find Views
m_Toolbar = findViewById(R.id.m_Toolbar);
m_Preferences = findViewById(R.id.m_Preferences);
m_WebView_Search = findViewById(R.id.m_WebView_Search);
m_WebView = findViewById(R.id.m_WebView);
m_Preference_Toolbar = findViewById(R.id.m_Preferences_Toolbar);
m_Preference_Toolbar.setVisibility(View.GONE);
m_Preferences.setOnTouchListener(new View.OnTouchListener() {
Animation ToolbarGone,ToolbarPrefVisible;
int x = 0;
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
m_Preferences.setVisibility(View.GONE);
x =1;
ToolbarGone = AnimationUtils.loadAnimation(CoreActivity.this, R.anim.m_toolbar_gone);
m_Toolbar.startAnimation(ToolbarGone);
if(m_Preferences.getVisibility() == View.GONE || x == 1) {
ToolbarPrefVisible = AnimationUtils.loadAnimation(CoreActivity.this, R.anim.m_preference_toolbar_appear);
m_Preference_Toolbar.startAnimation(ToolbarPrefVisible);
}
return false;
}
});
//m_WebView
final WebSettings m_WebViewSetting = m_WebView.getSettings();
m_WebView.setWebViewClient(new WebViewClient());
m_WebViewSetting.setJavaScriptEnabled(true);
m_WebViewSetting.setSupportZoom(true);
m_WebViewSetting.setLoadWithOverviewMode(true);
m_WebViewSetting.setUseWideViewPort(true);
m_WebView.getSettings().setUserAgentString("Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3");
m_WebView.loadUrl(Url); //Default HomePage
//m_WebView_Search TextView and Keyboard
m_WebView_Search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
if (m_WebView_Search.getText().toString().contains(".com")
|| m_WebView_Search.getText().toString().contains(".ca")
|| m_WebView_Search.getText().toString().contains(".net")
|| m_WebView_Search.getText().toString().contains(".org")) {
Url = m_WebView_Search.getText().toString();
m_WebView.loadUrl("https://www." + Url);
m_WebView_Search.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(m_WebView_Search.getWindowToken(), 0);
} else {
if (m_WebView_Search.getText().toString().contains("")) {
Url = m_WebView_Search.getText().toString();
m_WebView.loadUrl("https://www.google.ca/search?q=" + Url);
m_WebView_Search.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(m_WebView_Search.getWindowToken(), 0);
}
}
}
return false;
}
});
//Swipe Events WebSwipe
WebSwipe = new Swipe(350, 700);
WebSwipe.setListener(new SwipeListener() {
int Web = 0;
Animation WebShrink, WebEnlarge;
#Override
public void onSwipingLeft(final MotionEvent event) {
if(m_WebView.canGoForward()){
m_WebView.goForward();
}
else{
m_WebView.reload();
}
}
#Override
public void onSwipedLeft(final MotionEvent event) {
}
#Override
public void onSwipingRight(final MotionEvent event) {
if(m_WebView.canGoBack()){
m_WebView.goBack();
}
else{
m_WebView.reload();
}
}
#Override
public void onSwipedRight(final MotionEvent event) {
}
#Override
public void onSwipingUp(final MotionEvent event) {
}
#Override
public void onSwipedUp(final MotionEvent event) {
//WebView Animation (Enlarge)
if(Web == 0){
WebEnlarge = AnimationUtils.loadAnimation(CoreActivity.this, R.anim.m_webview_enlarge);
m_WebView.startAnimation(WebEnlarge);
Web = 1;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
m_Toolbar.setVisibility(View.GONE);
}
}, 350);
}
}
#Override
public void onSwipingDown(final MotionEvent event) {
}
#Override
public void onSwipedDown(final MotionEvent event) {
//WebView Animation (Shrink)
if(Web == 1){
WebShrink = AnimationUtils.loadAnimation(CoreActivity.this,R.anim.m_webview_shrink);
m_WebView.startAnimation(WebShrink);
m_Preference_Toolbar.setVisibility(View.GONE);
Web = 0;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
m_Toolbar.setVisibility(View.VISIBLE);
}
}, 350);
}
}
});
WebGesture = new Gesture();
WebGesture.addListener(new GestureListener() {
#Override public void onPress(MotionEvent motionEvent) {
}
#Override public void onTap(MotionEvent motionEvent) {
}
#Override public void onDrag(MotionEvent motionEvent) {
}
#Override public void onMove(MotionEvent motionEvent) {
}
#Override public void onRelease(MotionEvent motionEvent) {
}
#Override public void onLongPress(MotionEvent motionEvent) {
}
#Override public void onMultiTap(MotionEvent motionEvent, int clicks) {
}
});
}
#Override
public boolean dispatchTouchEvent (MotionEvent event){
WebSwipe.dispatchTouchEvent(event);
WebGesture.dispatchTouchEvent(event);
return super.dispatchTouchEvent(event);
}
}

The simplest way to split code is to think about Single Responsibility (as per the SOLID principles).
As an example in your code, your touch listener can be separated. This would entail making a class that extended the touch listener's class (View.OnTouchListener) instead of extending an activity.
This block in your code:
m_Preferences.setOnTouchListener(new View.OnTouchListener() {
...
});
Would become MyTouchListener.java:
public class MyTouchListener implements View.OnTouchListener {
Animation ToolbarGone,ToolbarPrefVisible;
int x = 0;
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
... // keep exactly your same code here
}
}
And then your activity gets changed to:
m_Preferences.setOnTouchListener(new MyTouchListener());

Related

How to manage exoplayer with java in android studio?

I am searching Exoplayer using with ViewPager in java but can not find the full tutorial.
I have issue for stopping and pausing exoplayer while swiping another video.
Is there any tutorial please suggest me.
Adapter.java
package com.daasuu.gpuvideoandroid.Adapter;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
import com.daasuu.gpuvideoandroid.Activity.OtherUser.OtherUserProfileActivity;
import com.daasuu.gpuvideoandroid.Model.MainVideoDataModel;
import com.daasuu.gpuvideoandroid.R;
import com.daasuu.gpuvideoandroid.Utils.VideoCache;
import com.daasuu.gpuvideoandroid.databinding.ItemMainVideoBinding;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.ui.StyledPlayerView;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource;
import com.google.android.exoplayer2.upstream.cache.CacheDataSource;
import java.util.List;
public class MainVideoAdapter2 extends RecyclerView.Adapter<MainVideoAdapter2.MyViewHolder> {
private Context context;
private List<MainVideoDataModel> data;
private boolean likeFlag = false;
private boolean followFlag = false;
private boolean isPlaying = false;
ExoPlayer exoplayer;
StyledPlayerView styledPlayerView;
public MainVideoAdapter2(Context context, List<MainVideoDataModel> data) {
this.context = context;
this.data = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ItemMainVideoBinding binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.item_main_video, parent, false);
return new MyViewHolder(binding);
}
#Override
public void onBindViewHolder(MainVideoAdapter2.MyViewHolder holder, int position) {
MainVideoDataModel model = data.get(position);
holder.setExoplayerStyled(model.getVideo_url());
}
#Override
public int getItemCount() {
return data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ItemMainVideoBinding binding;
public MyViewHolder(ItemMainVideoBinding binding) {
super(binding.getRoot());
this.binding = binding;
binding.imageUserMainVideo.setOnClickListener(this);
binding.videoView.setOnClickListener(this);
}
// styled exoplayer with cache
void setExoplayerStyled(String video_url){
binding.progressCircular.setVisibility(View.VISIBLE);
exoplayer = new ExoPlayer.Builder(context).build();
styledPlayerView = binding.videoStyledPlayerView;
styledPlayerView.hideController();
styledPlayerView.setUseController(false);
ProgressiveMediaSource mediaSource = new ProgressiveMediaSource.Factory(
new CacheDataSource.Factory()
.setCache(VideoCache.getInstance2(context))
.setUpstreamDataSourceFactory(new DefaultHttpDataSource.Factory()
.setUserAgent("rgcache"))
.setFlags(CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR)
).createMediaSource(MediaItem.fromUri(video_url));
exoplayer.seekTo(0);
exoplayer.prepare();
exoplayer.pause();
styledPlayerView.setPlayer(exoplayer);
exoplayer.setPlayWhenReady(false);
binding.videoStyledPlayerView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
#Override
public void onViewAttachedToWindow(View view) {
styledPlayerView.setKeepScreenOn(true);
exoplayer.addMediaSource(mediaSource);
exoplayer.prepare();
exoplayer.setPlayWhenReady(true);
exoplayer.setRepeatMode(exoplayer.REPEAT_MODE_ONE);
if(binding.videoStyledPlayerView.getPlayer() != null) {
binding.videoStyledPlayerView.getPlayer().play();
}
}
#Override
public void onViewDetachedFromWindow(View view) {
binding.videoStyledPlayerView.getPlayer().stop();
binding.videoStyledPlayerView.getPlayer().clearMediaItems();
exoplayer.seekTo(0);
exoplayer.setPlayWhenReady(false);
exoplayer.stop();
if(binding.videoStyledPlayerView.getPlayer() != null) {
binding.videoStyledPlayerView.getPlayer().pause();
}
}
});
//buffering
exoplayer.addListener(new Player.Listener() {
#Override
public void onIsLoadingChanged(boolean isLoading) {
Player.Listener.super.onIsLoadingChanged(isLoading);
// Log.e("onIsLoadingChanged", String.valueOf(isLoading));
}
#Override
public void onPlaybackStateChanged(int playbackState) {
Player.Listener.super.onPlaybackStateChanged(playbackState);
Log.e("onPlaybackStateChanged", String.valueOf(playbackState));
binding.imgVideoStop.setVisibility(View.GONE);
if (playbackState == 3){
binding.progressCircular.setVisibility(View.GONE);
}
}
#Override
public void onPlayWhenReadyChanged(boolean playWhenReady, int reason) {
Player.Listener.super.onPlayWhenReadyChanged(playWhenReady, reason);
}
});
// touch listener play & pause
binding.videoStyledPlayerView.getVideoSurfaceView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isPlaying == false){
binding.imgVideoStop.setVisibility(View.VISIBLE);
isPlaying = true;
exoplayer.setPlayWhenReady(false);
}else{
binding.imgVideoStop.setVisibility(View.GONE);
isPlaying = false;
styledPlayerView.setKeepScreenOn(true);
styledPlayerView.setPlayer(exoplayer);
exoplayer.addMediaSource(mediaSource);
exoplayer.prepare();
exoplayer.setPlayWhenReady(true);
exoplayer.setRepeatMode(exoplayer.REPEAT_MODE_ONE);
}
}
});
}
//on click event
#Override
public void onClick(View v) {
if (v == binding.imageUserMainVideo) {
context.startActivity(new Intent(context, OtherUserProfileActivity.class));
}
if (v == binding.videoView) {
Log.e("isPlaying = " , String.valueOf(isPlaying));
if (isPlaying) {
binding.videoView.pause();
// binding.imgVideoStop.setVisibility(View.VISIBLE);
isPlaying = false;
} else {
binding.videoView.start();
// binding.imgVideoStop.setVisibility(View.GONE);
isPlaying = true;
}
}
}
}
}
item.xml
<com.google.android.exoplayer2.ui.StyledPlayerView
android:id="#+id/videoStyledPlayerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible"
app:animation_enabled="true"/>
Issues:
After a specific position, it plays previous videos when swipe to next video.
Plays multiple videos on swipe
On swipe back(previous videos) don't stops previous video.
How to stop when to redirect another activity.
Please suggest the solution.
You can use addOnPageChangeListener for getting the user interaction for the view pager. add this code snippet in the onCreate method.In my project ,I handle it like this ::
binding!!.mediaViewPager.addOnPageChangeListener(object : OnPageChangeListener {
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
if (exoPlayer.isPlaying) {
exoPlayer.pause()
}
}
override fun onPageSelected(position: Int) {
if (exoPlayer.isPlaying) {
exoPlayer.pause()
}
}
override fun onPageScrollStateChanged(state: Int) {
exoPlayer.pause()
}
})
Play Exo Player With PageViwer
Link:
https://github.com/google/ExoPlayer/issues/7947
Example:
https://github.com/kakajika/PlayerPagerExample

Dynamically change the status of a ProgressBar based on two TextFields

I'm trying to change the status of a ProgressBar while the user is typing a text on either text fields.
For example , the user starts typing on the first TextView, the ProgressBar should change it's value, if he deletes the text, it should reset to the previous value which is 30
package com.example.phill.jokes;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
public class Entry extends AppCompatActivity {
private ProgressBar pr;
private Handler rHandler = new Handler();
private TextView tv ;
private TextView tv2 ;
private boolean titleboolean;
private boolean jokeboolean;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entry);
pr = (ProgressBar) findViewById(R.id.progressBar);
tv=(TextView) findViewById(R.id.textView9) ;
tv2=(TextView) findViewById(R.id.textView6) ;
new Thread(new Runnable() {
#Override
public void run() {
while (true)
{
android.os.SystemClock.sleep(300);
rHandler.post(new Runnable() {
#Override
public void run() {
pr.setProgress(30);
if(tv.getText().toString().matches(""))
{
titleboolean=true;
}
else
titleboolean=false;
if(tv2.getText().toString().matches(""))
{
jokeboolean=true;
}
else
jokeboolean=false;
if(titleboolean)
{
pr.setProgress(60);
}
if(jokeboolean)
{
pr.setProgress(100);
}
}
});
if(titleboolean && jokeboolean)
break;
}
rHandler.post(new Runnable() {
#Override
public void run() {
if(titleboolean && jokeboolean){
tv2.setVisibility(View.INVISIBLE);
tv.setVisibility(View.VISIBLE);
}
;
}
});
}
}).start();
}
}
The value of the ProgressBar never changes.
Any Ideas?
Let me explain you in detail
if(titleboolean && jokeboolean)
break;
when your both text fields clears it calls break statement after that your thread stops running you can achieve this in another way
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ProgressBar;
import android.widget.TextView;
public class TestActivity extends AppCompatActivity
{
private ProgressBar pr;
private EditText tv;
private EditText tv2;
private boolean titleboolean;
private boolean jokeboolean;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
pr=(ProgressBar)findViewById(R.id.progressBar);
tv = (EditText) findViewById(R.id.tv);
tv2 = (EditText) findViewById(R.id.tv2);
TextView tV = new TextView(this);
tV.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence
s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s,
int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
setProgress();
}
});
tv2.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence
s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s,
int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
setProgress();
}
});
}
public void setProgress() {
pr.setProgress(30);
if (tv.getText().toString().matches("")) {
titleboolean = true;
} else
titleboolean = false;
if (tv2.getText().toString().matches("")) {
jokeboolean = true;
} else
jokeboolean = false;
if (titleboolean) {
pr.setProgress(60);
}
if (jokeboolean) {
pr.setProgress(100);
}
}
}
Use EditText instead TextView with TextChangedListener.
TextView does not allow to type text.
Also infinite cycle with pauses is bad approach, use EditText.addTextChangedListener to handle text after it have changed

How to create an interface from a class

I am new to Android Programming/ Java I wanted to know how I should add gesture Directions when I already have a class extended to MainActvity?
package #####app.myapplication;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.MotionEvent;
import android.view.GestureDetector;
import android.support.v4.view.GestureDetectorCompat;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements GestureDetector.OnGestureListener,GestureDetector.OnDoubleTapListener{
private GestureDetectorCompat mygesture;
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
#Override
public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
return false;
}
#Override
public boolean onDoubleTap(MotionEvent motionEvent) {
return false;
}
#Override
public boolean onDoubleTapEvent(MotionEvent motionEvent) {
return false;
}
#Override
public boolean onDown(MotionEvent motionEvent) {
return false;
}
#Override
public void onShowPress(MotionEvent motionEvent) {
}
#Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
return false;
}
#Override
public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
return false;
}
#Override
public void onLongPress(MotionEvent motionEvent) {
}
#Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
#Override
public boolean onTouchEvent(MotionEvent event) {
this.mygesture.onTouchEvent(event);
return super.onTouchEvent(event);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context context = getApplicationContext();
CharSequence text = "Welcome to ####";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
WebView vedant = (WebView) findViewById(R.id.vedant);
vedant.loadUrl("http://##.ml");
WebSettings webSettings = vedant.getSettings();
webSettings.setJavaScriptEnabled(true);
vedant.setWebViewClient(new WebViewClient());
this.mygesture = new GestureDetectorCompat(this,this);
mygesture.setOnDoubleTapListener(this);
}
}
I know that to use Gesture Direction I need to :
#Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH){
return false;
}
// right to left swipe
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
onLeftSwipe();
}
// left to right swipe
else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
onRightSwipe();
}
} catch (Exception e) {
}
return false;
}
return false;
}
But for which I need to extend another class SimpleOnGestureListener.
As i could not extend to the SimpleOnGestureListener class I thought i could create a interface and then implement it. Is that possible. If so how?
If I understand correctly, you have a GestureDetectorCompat with 2 parameters:
The Context
a listener (GestureDetector.OnGestureListener)
At the moment you do mygesture = new GestureDetectorCompat(this,this); where this is your Activity. But why do you want your Activity to be the listener? You can create a listener in a separated class.
So you can do:
MainActivity
this.mygesture = new GestureDetectorCompat(this, new MyGestureListener());
MyGestureListener
public class MyGestureListener extends SimpleOnGestureListener {
#Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
// ...
// Your code
}
}

Having code problems from MainActivity to FragmentActivity

I wrote a simple code in MainActivity with its xml code previously which run successfully. Now, I want to make a fragment and run that MainActivity code in that fragment. I have tried everything, even by combining both codes etc. but all in vain. I'm attaching my MainActivity code below. This is the one I want to use in Fragment. I already know that fragment is like sub-activity of an activity and both have separate xmls too which I also know how to use. Just unable to use my MainActivity code from old app as FragmentActivity in a new app.
1) MainActivity Code which needs to act as a Fragment
package com.ranatalha.userauthority;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
public class MainActivity
extends AppCompatActivity
implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener{
private TextView mytext;
private GestureDetector gestureDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //this is above two lines cox phly content set hoga tbi agy kam hna na
this.gestureDetector = new GestureDetector(this, this);
gestureDetector.setOnDoubleTapListener(this); }
//******************Upon clicking the button*************************
public void changetextshort(View v) {
mytext = (TextView) findViewById(R.id.mytext);
mytext.setText("Surpriseeee"); }
//******************initializing touch event*************************
#Override
public boolean onTouchEvent(MotionEvent event) {
this.gestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);}
//******************Implements Methods from alt+ins(0) for touch properties*************************
#Override
public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
mytext.setText("I tapped Once");
return false;}
#Override
public boolean onDoubleTap(MotionEvent motionEvent) {
mytext.setText("I tapped Twice");
return false;}
#Override
public boolean onDoubleTapEvent(MotionEvent motionEvent) {
mytext.setText("Double Tap Event Occurred");
return false;}
#Override
public boolean onDown(MotionEvent motionEvent) {
mytext.setText("Down goes");
return false;}
#Override
public void onShowPress(MotionEvent motionEvent) {
mytext.setText("I have pressed");}
#Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
mytext.setText("Single Tap Up");
return false;}
#Override
public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
mytext.setText("I'm Scrolling");
return false;}
#Override
public void onLongPress(MotionEvent motionEvent) {
mytext.setText("I long pressed");}
#Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
mytext.setText("I FLINNGED");
return false; }
}
2) Fragment Code (MainActivity is not having any code now except the basic code of Mainactivity like class name and OnCreate code - although I have added Mainactivity code in 3rd point too which needs to be actually almost like that when we make fragments in android app)
package com.ranatalha.userauthority;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TopSectionFragment extends Fragment {
public class Top
extends AppCompatActivity
implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener{
private TextView mytext;
private GestureDetector gestureDetector;
//******************Override method oncreateview for fragment*************************
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.top_section_fragment,container, false);
this.gestureDetector = new GestureDetector(this, this);
gestureDetector.setOnDoubleTapListener(this);
return view; //designing of top section fragment completed
}
//******************Upon clicking the button*************************
public void changetextshort(View v) {
mytext = (TextView) findViewById(R.id.mytext);
mytext.setText("Surpriseeee"); }
//******************initializing touch event*************************
#Override
public boolean onTouchEvent(MotionEvent event) {
this.gestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);}
//******************Implements Methods from alt+ins(0) for touch properties*************************
#Override
public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
mytext.setText("I tapped Once");
return false;}
#Override
public boolean onDoubleTap(MotionEvent motionEvent) {
mytext.setText("I tapped Twice");
return false;}
#Override
public boolean onDoubleTapEvent(MotionEvent motionEvent) {
mytext.setText("Double Tap Event Occurred");
return false;}
#Override
public boolean onDown(MotionEvent motionEvent) {
mytext.setText("Down goes");
return false;}
#Override
public void onShowPress(MotionEvent motionEvent) {
mytext.setText("I have pressed");}
#Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
mytext.setText("Single Tap Up");
return false;}
#Override
public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
mytext.setText("I'm Scrolling");
return false;}
#Override
public void onLongPress(MotionEvent motionEvent) {
mytext.setText("I long pressed");}
#Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
mytext.setText("I FLINNGED");
return false; }
}
}
3) MainActivity code (which will incorporate Fragment sub-activity)
package com.ranatalha.userauthority;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class MainActivity
extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); }
}
One of the main things to keep in mind when converting code from activities and fragments is that you may have to switch things that use context in them.
This line: this.gestureDetector = new GestureDetector(this, this); is likely one of the things that is giving you trouble.
This:
GestureDetector(Context context, GestureDetector.OnGestureListener listener)
is probably the constructor you are trying to use.
The parameters that are context, will need to be changed from this in an activity to getContext() (or to something that extends Context) in a fragment.
For creating the fragment in the first place:
https://developer.android.com/guide/components/fragments.html
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
The container mentioned in the code sample is normally something like a FrameLayout.
It is not clear what you mean by "make a fragment and run that MainActivity code in that fragment"...
If you want to start an activity and make it overlay the Fragment you can try the code from MCeley in Start an activity from a fragment
> Intent intent = new Intent(getActivity(), mFragmentFavorite.class);
> startActivity(intent);

Android game loop thread crash

I am very new to programming and I have a problem with a game which I am trying to make.
Almost every time when I exit the game it was crashing.
After adding: if (canvas != null) beforew canvas.drawColor(Color.CYAN); it does not crash on exit anymore but when I return to the game.
Here is the code: (its not my actual game... there is nothing in OnDraw exept canvas.drawColor(Color.CYAN); that keeps it simple)
GameView.java:
package com.example.test.threadtest;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class GameView extends SurfaceView {
private GameLoopThread theGameLoopThread;
private SurfaceHolder surfaceHolder;
public GameView(Context context) {
super(context);
theGameLoopThread = new GameLoopThread(this);
surfaceHolder = getHolder();
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
theGameLoopThread.setRunning(false);
while (retry) {
try {
theGameLoopThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
theGameLoopThread.setRunning(true);
theGameLoopThread.start();
}
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
// TODO Auto-generated method stub
}
});
}
#Override
protected void onDraw(Canvas canvas) {
if (canvas != null)
canvas.drawColor(Color.CYAN);
}
}
GameLoopThread.java:
package com.example.test.threadtest;
import android.annotation.SuppressLint;
import android.graphics.Canvas;
public class GameLoopThread extends Thread {
static final long FPS = 20;
private GameView theView;
private boolean isRunning = false;
public GameLoopThread(GameView theView) {
this.theView = theView;
}
public void setRunning(boolean run) {
isRunning = run;
}
#SuppressLint("WrongCall") #Override
public void run() {
long TPS = 1000 / FPS;
long startTime, sleepTime;
while (isRunning) {
Canvas theCanvas = null;
startTime = System.currentTimeMillis();
try {
theCanvas = theView.getHolder().lockCanvas();
synchronized (theView.getHolder()) {
theView.onDraw(theCanvas);
}
} finally {
if (theCanvas != null) {
theView.getHolder().unlockCanvasAndPost(theCanvas);
}
}
sleepTime = TPS - (System.currentTimeMillis() - startTime);
try {
if (sleepTime > 0)
sleep(sleepTime);
else
sleep(10);
} catch (Exception e) {
}
}
}
}
MainAcitvity.java:
package com.example.test.threadtest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GameView(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Categories