Android为片段设置透明背景

amo*_*the 13 android android-theme android-fragments android-activity android-support-library

在我的应用程序中,我有单个活动和所有其他片段

我正在设置style.xml的活动背景,如下所示

<item name="android:windowBackground">@color/very_light_gray</item>
Run Code Online (Sandbox Code Playgroud)

现在只有一个特殊的片段,我想设置背景透明,我无法做到尝试下面的片段代码片段对我来说不起作用

  @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

// create ContextThemeWrapper from the original Activity Context with the custom theme
final Context contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.yourCustomTheme);

// clone the inflater using the ContextThemeWrapper
LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);

// inflate the layout using the cloned inflater, not default inflater
return localInflater.inflate(R.layout.yourLayout, container, false);
}
Run Code Online (Sandbox Code Playgroud)

知道怎么做吗?

Man*_*ddy 7

这不是完美的解决方案,但它有效

而不是使用Fragment使用DialogFragment

 //exploreCategory is argument
class MyFragment(val exploreCategory: ExploreCategory) : DialogFragment() {

    override fun onStart() {
      super.onStart()
      setWindowParams()
    }

   private fun setWindowParams(){
      dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
      dialog?.window?.setLayout(
        LinearLayout.LayoutParams.MATCH_PARENT,
        LinearLayout.LayoutParams.MATCH_PARENT
      )
    }

}
Run Code Online (Sandbox Code Playgroud)

其余代码与您在片段中编写的代码相同

为了显示在片段中使用下面的代码,如果在活动中显示则使用fragmentManager

MyFragment(exploreCategory).show(childFragmentManager,null)
//exploreCategory is argument, you can choose to send no arguments
Run Code Online (Sandbox Code Playgroud)


小智 -1

您刚刚在代码下面设置了布局片段的背景:

<LinearLayout
...
android:background="@android:color/transparent"/>
Run Code Online (Sandbox Code Playgroud)