어떤 이유에서인지
com.google.android.youtube.player.YouTubePlayerView
를 이용하려는데 계속 에러가 나서 Fragment 를 활용하였다.
1) 일단, api key 를 발급받아야 하므로, 아래 참조.
글에서 처럼,
- api key 발급받고
- YouTubeAndroidPlayerApi.jar 다운로드해서 프로젝트에 포함
2) AndroidManifestxml 추가
3) 아래 소스는 누군가의 github 에서 ....ㅋ
[MainActivity.java]
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); YoutubeFragment fragment = new YoutubeFragment(); FragmentManager manager = getSupportFragmentManager(); manager.beginTransaction() .replace(R.id.main, fragment) .addToBackStack(null) .commit(); } @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); } }
[YoutubeFragment.java]
public class YoutubeFragment extends Fragment { private static final String API_KEY = ""; private static String VIDEO_ID = "wzHn15IvLlc"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.youtube_api, container, false); YouTubePlayerSupportFragment youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance(); FragmentTransaction transaction = getChildFragmentManager().beginTransaction(); transaction.add(R.id.youtube_layout, youTubePlayerFragment).commit(); youTubePlayerFragment.initialize(API_KEY, new YouTubePlayer.OnInitializedListener() { @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) { if (!wasRestored) { player.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT); player.loadVideo(VIDEO_ID); player.play(); } } @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult error) { // YouTube error String errorMessage = error.toString(); Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show(); Log.d("errorMessage:", errorMessage); } }); return rootView; } }
4) 최종 결과
'개발 > 안드로이드' 카테고리의 다른 글
how to get activity's content view (0) | 2016.11.08 |
---|---|
android insufficient permissions error 9 (0) | 2016.11.06 |
android studio github error (non-fast-forward) (0) | 2016.10.24 |
안드로이드 button 클릭 이벤트 처리 4가지 (0) | 2016.10.20 |
restful (0) | 2016.10.10 |
댓글