I'm wanting to add a button to the YouTubePlayerView but don't know the best way to go about doing so. I would like the button only to be present when the user clicks on the screen to bring up the youtube controls (play/pause, timeline, share, etc.) that fades away after a few seconds just as the controls fade. I've looked into ViewGroupOverlay but not sure if this is the best way to do so and I'm not sure how to only have the button added to the overlay when the controls are available. It feels like I have to override one of the YouTubePlayer or YouTubePlayerView functions to know when the controls are visible but I'm just making a hypothesis here. I'm relatively new to android and it's been a while since I've done anything serious in Java. Any direction here would be great if others don't know the exact answer. I've looked around for about 2 hours before posting this :)
package com.example.something.exampletube;
import android.os.Bundle;
import android.view.ViewGroupOverlay;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
/**
* Created by Nicholas Dwyer on 4/17/2015.
* This class is used to play youtube videos
*/
public class PlayerActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
YouTubePlayerView playerView;
ViewGroupOverlay groupOverlay;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_player);
playerView = (YouTubePlayerView) findViewById(R.id.player_view);
playerView.initialize(YoutubeConnector.KEY, this);
groupOverlay = playerView.getOverlay();
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean restored) {
if(!restored) {
youTubePlayer.cueVideo(getIntent().getStringExtra("VIDEO_ID"));
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
String errorMessage = "There was an error initializing the YouTubePlayer" + youTubeInitializationResult.toString();
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
//Toast.makeText(this,getString(R.string.failed), Toast.LENGTH_LONG).show();
}
}
It is not possible to add buttons as overlays above the player as specified by Google:
https://developers.google.com/youtube/android/player/reference/com/google/android/youtube/player/YouTubePlayerView
Note that while videos are playing, this View has a minimum size of
200x110 dp. If you make the view any smaller, videos will
automatically stop playing. Also, it is not permitted to overlay the
view with other views while a video is playing.
See also here Is it possible to overlay some views on YouTube Android Player?
If any view only partially overlaps (or YouTubeVideoView is only partially scrolled outside the visible screen), the video is stopped after approximately one second. Google supposedly does that to prevent abuse of videos for advertising outside YouTube.
Alternatives: Use a WebView and embed it.
Another good alternative is to used Exoplayer, to overlay your video with view. It is not part of the android sdk, but it's recommended by google and included in android developer documentation :
http://google.github.io/ExoPlayer/
https://developer.android.com/guide/topics/media/exoplayer.html
Exoplayer allow you to stream any kind of video, not only Youtubes videos.
It's also good to mention that Exoplayer is used in Youtube application.
Instead of adding button as a layer above the player, you can add it INSIDE the player:
Button b = new Button(this);
b.setBackgroundResource(R.drawable.close);
((ViewGroup)((ViewGroup) youTubePlayerView.getChildAt(0)).getChildAt(0)).addView(b);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
Working for me.
Related
I am new to android programming and trying to develop TIC TAC TOE game. I have created gameLogic() method and the problem is this that it is not working as it is expected to do, means on click of ImageView none of the images is getting displayed. Any help will be highly appreciated.
This is my code:
public class MainActivity extends AppCompatActivity {
public void gameLogic(View view) {
ImageView tappedView = (ImageView)view;
tappedView.setTranslationY(-3000f);
tappedView.setImageResource(R.drawable.black);
tappedView.animate().translationYBy(3000f).setDuration(500);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public void onClick (View view) {
ImageView tappedView = (ImageView)view;
tappedView.setTranslationY(-3000f);
tappedView.setImageResource(R.drawable.black);
tappedView.animate().translationYBy(3000f).setDuration(500)
Try changing the class name to onClick and go to XML the page where you designs the button and declare onClick method in the image view button.
All you have to do is let the design page know where the code is by providing a common name to look for which is on click.
Also you have to add an onClick listener which listens for the button to click as the code should know which button it is linked to.
So declare a setonclicklistener method on the button Id and you're set to go.
Also write the code within the override after the setting of the layout.
Hope you understood :)
If you're new try head first Android it'll be really helpful I know how struggling it is during the initial days.
I have this in my MainActivity.java:
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupHomeScreen();
}
public void setupHomeScreen() {
File latestPic = getMostRecentSnappiePicture();
if(latestPic != null){
//display pic
LinearLayout layout = (LinearLayout) findViewById(R.id.mainLayout);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
layout.setBackground(Drawable.createFromPath(latestPic.getAbsolutePath()));
}
else{
layout.setBackgroundDrawable(Drawable.createFromPath(latestPic.getAbsolutePath()));
}
//hide tutorial
findViewById(R.id.howitworks).setVisibility(View.INVISIBLE);
}
else{
//show tutorial
findViewById(R.id.howitworks).setVisibility(View.VISIBLE);
new ShowcaseView.Builder(this)
.setTarget(new ActionViewTarget(this, ActionViewTarget.Type.HOME))
.setContentTitle("ShowcaseView")
.setContentText("This is highlighting the Home button")
.hideOnTouchOutside()
.build();
}
}
}
As you can see, in onCreate, it calls setupHomeScreen and checks if a file exists. If it doesn't exist, it displays a tutorial "howitworks" layout image as well as building a showcase view.
So this all works fine and well. The only issue comes when trying to leave the activity while the showcaseView is still there, OR sometimes even after you exit the showcase view and try and launch the new activity, this error comes up: ShowcaseView - width and height must be > 0
As you can see in the answers, the solution is to only create the showcase view in the callback after the original view has been created like so:
someView.post(new Runnable() {
#Override
public void run() {
// my ShowcaseView builder here
}
});
The only thing is, I have no idea where to put this, since my showcase view should only show up if the file from getMostRecentSnappiePicture() is null. So how can I put the view creation callback inside of my logic to check that that file is null first?
it looks like you're highlighting the HOME button instead of the 'howitworks' view. Try switching the line
.setTarget(new ActionViewTarget(this, ActionViewTarget.Type.HOME))
with
.setTarget(new ViewTarget(R.id.howitworks,this));
Also, the following video might help. It's 20 minute tutorial on how to use ShowCaseView inside an activity with 3 buttons. He is declaring an onClickListener where he changes programmatically the TargetView highlighted by the showCaseView
https://www.youtube.com/watch?v=3zdeFSBplps
The video is in spanish, but at least you'll be able to follow the steps, since he's writing the code from scratch.
HomeActivity.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
Button btnopen = (Button)findViewById(R.id.btnWindowAnimation);
btnopen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent slideactivity = new Intent(HomeActivity.this, CartActivity.class);
Bundle bndlanimation =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animation,R.anim.animation2).toBundle();
startActivity(slideactivity, bndlanimation);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.layout.home, menu);
return true;
}
HomeActivity has a button and it will help to slide the 1st screen and bring the second screen.
animation.xml
android:fromXDelta="100%p"
android:toXDelta="25%p"
android:duration="5000"
This animation code is helping me to slide my screen after pressing the button. As shown in this video
https://www.youtube.com/watch?v=EzgGGWpRES0
I want to stop the new screen at the middle without covering the 1st screen completely.
Any suggestions? I have used another activity called cart( i haven't used fragments here)
Sounds like you want a NavigationDrawer.
You can find out more information on the Android developer site:
https://developer.android.com/design/patterns/navigation-drawer.html
https://developer.android.com/training/implementing-navigation/nav-drawer.htmlA
Your Requirement is to partially Display an Overlapping Activity on an Existing Activity. This is Possible with Sliding Menu Library (Which does not mean to technically create a floating Activity, but to create a Floating View integrated within the Sliding Menu that will be displayed partially on top on an Activity).
In case, if you are regarding this as some sort of Default Menu then please take a look at this Image
If this is your actual Requirement, then here are the details for you.
Sliding Menu Library is an OpenSource Library, you can use it for displaying a partially visible Sliding Menu on top of an Activity.
Here is the link of Sliding Menu Lib :
https://github.com/jfeinstein10/SlidingMenu
You can navigate to the example directory present in this Project for the demonstration of it's Usage.
I hope thie helps :)
I am very new to mobile development, this isn't homework I am working ahead of my class, I developed a simple app that has a button and when it's pressed it shows a message "Hello Android". I would like to build on this and change the color of the background when the onClickListener is called, I will post my code below, I am asking for the best approach to achieve my goal (change background). I want to iterate that this code below works, and that I am not asking for anything to do with the code I have presented, I want to add to it to change the background color (it's currently white, I'm assuming by default). Oh and I have never worked with Java before (very difficult course teaching android/iOS/WinMobile in 1 class). Thank you.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupMessageButton();
}
private void setupMessageButton() {
// 1. Get a reference to the button
final Button messageButton = (Button) findViewById(R.id.helloDroidButton);
//Set the click listener to run my code.
//Code will run when user clicks button.
messageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Anonymous class? --> not sure what he means
Log.i("DemoButtonApp", "Hello Android!");
Toast.makeText(
MainActivity.this,
"Hello Android!",
Toast.LENGTH_LONG
).show();
}
});
}
Android support feature called Selector , that help you to change the background of any view in each state of it like pressed , forces and so one , take look on this useful tutorial and feed me back in any not obvious point
http://www.mkyong.com/android/android-imagebutton-selector-example/
hope it help you
I'm trying to use Google Analytics in my Android application with
Google Configuration
Add .jar in my project
Insert this in AndroidManifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Add this in my java file
public class MainActivity extends Activity {
GoogleAnalyticsTracker tracker;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tracker = GoogleAnalyticsTracker.getInstance();
tracker.startNewSession("My-UA–XXXXXXXX", this);
setContentView(R.layout.main);
Button createEventButton = (Button)findViewById(R.id.NewEventButton);
createEventButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tracker.trackEvent(
"Clicks", // Category
"Button", // Action
"clicked", // Label
77); // Value
}
});
setContentView(R.layout.main);
Button createPageButton = (Button)findViewById(R.id.NewPageButton);
createPageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Add a Custom Variable to this pageview, with name of "Medium" and value "MobileApp" and
// scope of session-level.
tracker.setCustomVar(1, "Navigation Type", "Button click", 2);
// Track a page view. This is probably the best way to track which parts of your application
// are being used.
// E.g.
// tracker.trackPageView("/help"); to track someone looking at the help screen.
// tracker.trackPageView("/level2"); to track someone reaching level 2 in a game.
// tracker.trackPageView("/uploadScreen"); to track someone using an upload screen.
tracker.trackPageView("/testApplicationHomeScreen");
}
});
Button quitButton = (Button)findViewById(R.id.QuitButton);
quitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
Button dispatchButton = (Button)findViewById(R.id.DispatchButton);
dispatchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Manually start a dispatch, not needed if the tracker was started with a dispatch
// interval.
tracker.dispatch();
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
// Stop the tracker when it is no longer needed.
tracker.stopSession();
}
}
==> And it's ok, no error, compiling and executing but i have created my ua account yesterday (more 24h) and i have nothing in my google analytics panel.
My Question : is there an error in my code or i want to wait again ? Live trafic works for Android application (like tradicional website) ???
I have no information about Live trafic (when i play my app, i would like to show the number of person using my application) and Saved trafic (with viewed pages, time)
Thank you for your replies and excuse my poor english :)
bye
UPDATE 1 :
i've used this tuto : http://www.xatik.com/2012/03/27/how-to-use-google-analytics-in-android-applications/ and i've got this in my Logcat :
04-07 14:21:59.669: INFO/GoogleAnalyticsTracker(864): Host: www.google-analytics.com
04-07 14:21:59.669: INFO/GoogleAnalyticsTracker(864): User-Agent: GoogleAnalytics/1.4.2 (Linux; U; Android 2.2; en-us; sdk Build/FRF91)
04-07 14:21:59.669: INFO/GoogleAnalyticsTracker(864): GET /__utm.gif?utmwv=4.8.1ma&utmn=235327630&utme=8(1!Navigation%20Type)9(1!Button%20click)11(1!2)&utmcs=UTF-8&utmsr=240x320&utmul=en-US&utmp=%2FtestApplicationHomeScreen&utmac=BLIBLUBLIBLO–1&utmcc=more_and_more
in progress but nothing in my Live Analytics panel....
i've added EasyTracker .jar in my project
Here my Activity Code:
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import com.google.android.apps.analytics.easytracking.EasyTracker;
import com.google.android.apps.analytics.easytracking.TrackedActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends TrackedActivity {
GoogleAnalyticsTracker tracker;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button quitButton = (Button)findViewById(R.id.QuitButton);
quitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EasyTracker.getTracker().trackEvent("ButtonClick", "MyButtonName", "", 0);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
//How can i stop the tracking onDestroy ???
}
}
I know this is a couple months old but I'll give a response to potentially help others. I am the person who wrote the guide that was referenced in Update 1 of the OP. One issue I originally ran into was the fact that I was using a custom ROM on my phone. A lot of custom ROMs have modified 'hosts' files that block an apps access to display ads or in this case blocks the sending of data to Google Analytics. If you do have a custom ROM on your phone, you can check the 'hosts' file to see if Google Analytics is listed in there. The fastest way to do this is to open the file in a text editor on your computer. To do this:
Get a file explorer app on you android device (I use 'ES File Explorer').
Navigate to '/etc'.
Locate and copy the 'hosts' file to a known location on your SD card.
Connect phone/SD card to computer and open the 'hosts' file in a text editor (Notepad++ is nice and free).
Search through file for anything that relates to Google Analytics and delete it. I first searched for 'analytics', went through all results, and deleted everything that had something to do with Google attached to the name (there are other analytic sites). Then I searched for 'google', went through all the results, and deleted anything that still related to Analytics.
Save 'hosts' file.
Disconnect from computer and use file explorer to copy the 'hosts' file from SD card back to '/etc' and overwrite.
This should allow your phone to send data to Google Analytics. I will update my guide to include this somewhere.