问题
I am trying out youtube video to be played on my app. I understand this can be achieve by extending activity as YouTubeBaseActivity by doing this I don't have access to you my toolbar.
mActionBar = (Toolbar) findViewById(R.id.toolbar);
if (mActionBar != null)
{
setSupportActionBar(mActionBar);
}
getSupportActionBar().setTitle(getResources().getString(R.string.youtubetitle));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
I am getting getSupportActionbar could not be resolved. Is there an easy way to get access to toolbar by extending activity YouTubeBaseActivity.
Am I doing anything wrong?
Thanks!
回答1:
YouTubeBaseActivity extends Activity, (as opposed to, for example AppCompatActivity
), so the getSupportActionBar()
method doesn't exist.
You could try to make your class extend AppCompatActivity
, and use a YouTubePlayerSupportFragment instead wherever you would normally use a YouTubePlayerView
.
Edit:
Add the following to your layout
file, in place of a YouTubePlayerView
<fragment
android:name="com.google.android.youtube.player.YouTubePlayerSupportFragment"
android:id="@+id/youtube_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
Access it in onCreate()
of your Activity
in the same way you would any other static Fragment
public class CustomYouTubeActivity extends AppCompatActivity implements YouTubePlayer.OnInitialisedListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragments_demo);
YouTubePlayerSupportFragment frag =
(YouTubePlayerSupportFragment) getSupportFragmentManager().findFragmentById(R.id.youtube_fragment);
frag.initialize(DeveloperKey.DEVELOPER_KEY, this);
}
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
boolean wasRestored) {
if (!wasRestored) {
//I assume the below String value is your video id
player.cueVideo("nCgQDjiotG0");
}
@Override
public void onInitializationFailure (YouTubePlayer.Provider provider, YouTubeInitializationResult error) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
String errorMessage = String.format(getString(R.string.error_player), errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
}
来源:https://stackoverflow.com/questions/35584073/getsupportactionbar-with-youtubebaseactivity