Android:如何设置YoutubePlayerSupportFragment的宽度/高度

时间:2016-10-14 09:34:15

标签: java android android-fragments layout youtube

我在我的应用中使用YoutubePlayerSupportFragment。我从代码(而不是xml)创建片段,并使用FragmentManager将其注入活动:

String video_id = "LHcP4MWABGY";

YoutubeFragment youtubeFragment = YoutubeFragment.newInstance(video_id);

mFragmentManager.beginTransaction().replace(R.id.activity_main, youtubeFragment).commit()

如何定义youtube片段的宽度/高度?我试过了:

ViewGroup.LayoutParams params = (ViewGroup.LayoutParams)youtubeFragment.getView().getLayoutParams();

params.height = 400;

youtubeFragment.getView().setLayoutParams(params);

但是这给了我一个NullPointerException。例外是在这一行:

ViewGroup.LayoutParams params = (ViewGroup.LayoutParams)youtubeFragment.getView().getLayoutParams();

这是错误日志:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.ViewGroup$LayoutParams android.view.View.getLayoutParams()' on a null object reference
                at com.test.revy.radioshake.MainActivity$1.onItemClick(MainActivity.java:249)
                at android.widget.AdapterView.performItemClick(AdapterView.java:346)
                at android.widget.AbsListView.performItemClick(AbsListView.java:1550)
                at android.widget.AbsListView$PerformClick.run(AbsListView.java:3830)
                at android.widget.AbsListView$3.run(AbsListView.java:5855)
                at android.os.Handler.handleCallback(Handler.java:739)
                at android.os.Handler.dispatchMessage(Handler.java:95)
                at android.os.Looper.loop(Looper.java:148)
                at android.app.ActivityThread.main(ActivityThread.java:7325)
                at java.lang.reflect.Method.invoke(Native Method)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

1 个答案:

答案 0 :(得分:1)

正如Abbas所说,问题是FragmentManager的Transaction()。[..]。commit()(异步调用)。 使用commitNow()而不是commit()解决:

mFragmentManager.beginTransaction().replace(R.id.activity_main, youtubeFragment).commitNow()