As I don't have any experience with Android prior to JetPack compose, I'm unable to figure this out.
I'm using the barteksc/AndroidPdfViewer but since this is an old library, I need to wrap this in a AndroidView() composable. This works and displays the PDF correctly.
#Composable
fun PDFView(
byteArray: ByteArray,
) {
AndroidView(
modifier = Modifier
.fillMaxSize(),
factory = { context ->
PDFView(
ContextThemeWrapper(context, R.style.PdfView), null
)
},
update = { pdfView ->
Log.d(TAG, "PDF view UPDATE called")
pdfView
.fromBytes(byteArray)
.autoSpacing(false)
.spacing(25)
.pageFitPolicy(FitPolicy.BOTH)
.load()
}
)
}
As per documentation of the lib, setting some spacing and adding a background colour would result in a visual separation of the PDF pages.
Setting the AndroidView's modifier background does not work.
So I tried setting background on R.style.PDFView like so (tried several options):
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="PdfView" parent="Theme.MyPDFView">
<item name="colorSurface">#color/blue</item>
<item name="background">#color/blue</item>
<item name="backgroundColor">#color/blue</item>
</style>
</resources>
But this still does not change the background.
To be complete, the Theme.MyPDFTheme looks as follows:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.MyPDFView" parent="Theme.MaterialComponents.DayNight">
<item name="android:statusBarColor">#color/background_material_light</item>
<item name="android:windowLightStatusBar">true</item>
<item name="android:navigationBarColor">#color/background_material_light</item>
<item name="android:windowLightNavigationBar">true</item>
</style>
</resources>
I also tried setting background color in Theme.kt
private val LightColorPalette = lightColors(
surface = Color.Green,
background = Color.Yellow,
But the background of the PDFView does not change, yes, device is in light mode.
How can I set the background on this view?
You can set PDFView background color with setBackgroundColor:
factory = { context ->
PDFView(
context,
null
).also {
it.setBackgroundColor(Color.Transparent.toArgb())
}
},
Then the background color set with the Modifier will become visible. Full example:
AndroidView(
factory = { context ->
PDFView(
context,
null
).also {
it.setBackgroundColor(Color.Transparent.toArgb())
}
},
update = { pdfView ->
pdfView
.fromStream(pdfView.context.resources.openRawResource(R.raw.sample))
.autoSpacing(false)
.spacing(25)
.pageFitPolicy(FitPolicy.BOTH)
.load()
},
modifier = Modifier
.fillMaxSize()
.background(Color.Red)
)
Related
I am trying to migrate an app from XML layouts to jetpack compose. As the app allows setting different user themes, I wanted to use the XML themes until all files are migrated. However, I just can't get it to work.
Basically I am doing as described in
https://material-components.github.io/material-components-android-compose-theme-adapter/#compose-material-3
I have a simple activity with a defined Composable:
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import at.example.myapp.ui.composables.about.About
import com.google.android.material.composethemeadapter3.Mdc3Theme
class AboutActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(MainActivity.getUserTheme(this))
super.onCreate(savedInstanceState)
setContent {
// Use MdcTheme instead of MaterialTheme
// Colors, typography, and shape have been read from the
// View-based theme used in this Activity
Mdc3Theme {
About()
}
}
}
}
setTheme(...) correctly loads the theme, the color on the very top is corretly set, but nothing else. All other colors, styles and fonts are not set in the composable.
The About() composable itself has nothing special, just a few texts, images and a card.
I am importing the following versions:
//JETPACK COMPOSE
// Integration with activities
implementation 'androidx.activity:activity-compose:1.4.0'
// Compose Material Design
implementation 'androidx.compose.material:material:1.1.1'
// Animations
implementation 'androidx.compose.animation:animation:1.1.1'
// Tooling support (Previews, etc.)
implementation 'androidx.compose.ui:ui-tooling:1.1.1'
// Integration with ViewModels
implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.4.1'
// UI Tests
androidTestImplementation 'androidx.compose.ui:ui-test-junit4:1.1.1'
// Theme compatibility with XML
implementation "com.google.android.material:compose-theme-adapter-3:1.0.6"
So the compose-theme-adapter-3 should actually do the job (if I understood the documentation correctly).
I played around with different combinations and parameters for Mdc3Theme { ... }, but without success, the colors won't just load.
In the resources I have the colors defined as expected by Material 3:
<resources>
<!-- Base application theme. -->
<style name="Theme.MyApp" parent="Theme.Material3.Light.NoActionBar">
<item name="colorPrimary">#color/md_theme_light_primary</item>
<item name="colorOnPrimary">#color/md_theme_light_onPrimary</item>
<item name="colorPrimaryContainer">#color/md_theme_light_primaryContainer</item>
<item name="colorOnPrimaryContainer">#color/md_theme_light_onPrimaryContainer</item>
<item name="colorSecondary">#color/md_theme_light_secondary</item> ...
As I couldn't find other examples, I hope that it is correct to just basically load the Theme like this:
setContent {
// Use MdcTheme instead of MaterialTheme
// Colors, typography, and shape have been read from the
// View-based theme used in this Activity
Mdc3Theme {
About()
}
}
Playing around with compose-theme-adapter (for Material 2) also didn't help.
I'm really stuck here. Is there anyone who could help or give an example about how to get the Mdc3 Theme applied properly from XML?
EDIT:
For completion, here's also the About() Composable:
#Composable
fun About() {
val defaultPadding = 8.dp
val widePadding = 16.dp
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(
ImageVector.vectorResource(id = R.drawable.ic_babyfootsteps),
null,
modifier = Modifier
.padding(widePadding)
.size(100.dp, 100.dp)
.background(Color(0xFFFF0077))
)
Text(
stringResource(id = R.string.app_name),
fontSize = 24.sp,
modifier = Modifier.padding(defaultPadding),
)
Text(stringResource(id = R.string.about_app_version, BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE))
Text(stringResource(id = R.string.about_app_codename, BuildConfig.versionCodename))
Spacer(modifier = Modifier.padding(defaultPadding))
...
I wrote some Jetpack Compose Demo, but I found library bug about adapt dark mode, therefore I want to show light mode only in my App, however when I set <item name="android:forceDarkAllowed" tools:targetApi="q">false</item> and AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) , those do not work, any idea for show light mode only for Jetpack Compose?
The color we used for compose is not defined in xml, should be something like below:
#Composable
fun MyComposeTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: #Composable () -> Unit
) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colorScheme = colors,
content = content
)
}
As you can see, you can pass any color as you wish in MaterialTheme function call, just remove the dark mode check will do the trick.
Simply add an item in both res/theme.xml and res/theme.xml(night) file is <item name="android:windowBackground">#color/white</item> in both darkand light mode it will be white.
Thank you.
on theme.kt
change this
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
to this
val colors = LightColorPalette
What is the equivalent of layer-list in jetpack compose?
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/lightGray" />
<item android:drawable="#drawable/transp_01" />
</layer-list>
I want to get an image like the one shown to use as a background for all my screens
You can draw it easily in compose. With Box you can place any amount of images on top of each other same as layer list can do. So generally specking, you could use something like this:
Box {
// replace any color item from the layer list with box with background:
Box(
modifier = Modifier
.background(Color.LightGray)
.matchParentSize()
)
// replace drawable item with Image:
Image(
painter = painterResource(id = R.drawable.my_image),
contentDescription = "...",
)
}
But in your case, it looks like you only need one image, and you can set a background color for it. Since you need to reuse it in your application, you can move it to a separate view, for example like this:
#Composable
fun BackgroundView(modifier: Modifier) {
Image(
painter = painterResource(id = R.drawable.transp_01),
contentDescription = "...",
modifier = modifier.background(Color.LightGray)
)
}
Then set it as background to any screen like this:
#Composable
fun SomeScreen() {
Box(Modifier.fillMaxSize()) {
BackgroundView(Modifier.matchParentSize())
// screen content
}
}
How do I reference a resource style from Compose widget?
styles.xml
<style name="Style.Monet.TextView.HeaderSubtext" parent="Widget.AppCompat.TextView">
<item name="android:textColor">#737373</item>
<item name="android:textSize">12sp</item>
<item name="android:layout_marginStart">16dp</item>
<item name="android:layout_marginBottom">16dp</item>
<item name="android:layout_marginEnd">24dp</item>
</style>
MyComponent.kt
Text(text = "June 2021", style = TextStyle(R.style.Style_TextView_HeaderSubtext))
But this doesn't work. Is there a way to make this work?
You can't do that, because Compose Text is styled differently, and TextStyle it not responsible so all xml style is responsible. As an example, you cannot add margins.
You can create compose TextStyle:
val textStyle = TextStyle(
color = Color(0xFF737373),
fontSize = 12.sp,
)
And use it globally in your project or pass to your theme. This is a preferred way to use styles in compose, check out more about it in the theming documentation. Customize one of material available styles:
val typography = Typography(
body1 = TextStyle(
color = Color(0xFF737373),
fontSize = 12.sp,
)
)
Pass it to your theme:
#Composable
fun ComposePlaygroundTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: #Composable () -> Unit
) {
val colors = if (darkTheme) {
DarkThemeColors
} else {
LightThemeColors
}
MaterialTheme(
colors = colors,
typography = typography,
shapes = shapes,
content = content,
)
}
Apply Theme at the composable root:
setContent {
ComposePlaygroundTheme {
// your composables
}
}
After that you can use it like this:
Text("",
style = MaterialTheme.typography.body1,
)
To apply margins in compose you need to use padding modifier. Check out more about layout in compose in the layout documentation:
If you wanna reuse same styled text in compose, you can create your own composable with predefined style and padding:
#Composable
fun ProjectText(text: String, modifier: Modifier) {
// without material theme you can just define text style here and pass to text
// val textStyle = TextStyle(
// color = Color(0xFF737373),
// fontSize = 12.sp,
)
Text("",
style = MaterialTheme.typography.body1,
modifier = modifier
.padding(start = 16.dp, end = 24.dp, bottom = 16.dp)
)
}
Usage:
ProjectText("June 2021")
In Jetpack Compose, TopAppBar shows default background color irrespective of what we added to themes.xml.
So how can we change TopAppBar background color from themes.xml so it's applied globally to the App?
TopAppBar(
title = { Text("Activity") },
navigationIcon = {
IconButton(onClick = { onBackPressed() }) {
Icon(Icons.Filled.ArrowBack, contentDescription = null)
}
}
)
themes.xml
<style name="Theme.MyApplication" parent="Theme.MaterialComponents.DayNight">
<!-- Primary brand color. -->
<item name="colorPrimary">#android:color/black</item>
<item name="colorPrimaryVariant">#android:color/holo_orange_dark</item>
<item name="colorOnPrimary">#android:color/white</item>
</style>
Note : we can change it through backgroundColor attribute of TopAppBar but here I want to achieve it globally.
The accepted answer explains what to do adequately. There is one thing you might need to keep in mind, though.
TopAppBar uses MaterialTheme.colors.primarySurface as the background color, and it's defined as the following.
[androidx/compose/material/Colors.kt]
val Colors.primarySurface: Color get() = if (isLight) primary else surface
In other words, if the device is in the light mode, it uses primary, and in the dark mode, it uses surface.
Suppose I have a theme with everything as default values.
private val DarkColorPalette = darkColors()
private val LightColorPalette = lightColors()
#Composable
fun ComposeTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: #Composable () -> Unit) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
)
lightColors and darkColors have the following values by default.
fun lightColors(
primary: Color = Color(0xFF6200EE),
...
)
fun darkColors(
surface: Color = Color(0xFF121212),
...
)
When the device is in the light mode, primary (0xFF6200EE) will be TopAppBar's background color.
But when the device is in the dark mode, surface (0xFF121212) is not TopAppBar's background color. It's slightly lighter; 0xFF282828 to be exact.
The reason is TopAppBar has a built-in elevation, which is 4.dp by default.
[androidx/compose/material/AppBar.kt]
#Composable
fun TopAppBar(
...
elevation: Dp = AppBarDefaults.TopAppBarElevation // 4.dp
) {
This most likely won't cause a problem, but it might matter if you want to apply the exactly same background color to somewhere else, such as setting the same color for the status area's background.
val systemUiController = rememberSystemUiController()
systemUiController.setSystemBarsColor(color = Color(0xFF282828))
Note that for this particular case, it would be easier if you just go full screen and add padding at the top.
WindowCompat.setDecorFitsSystemWindows(window, false)
setContent {
MyAppTheme {
Surface(
modifier = Modifier.systemBarsPadding().fillMaxSize(), // <--
) {
...
}
}
}
For the TopAppBar and the other composables the basis of theming is the MaterialTheme composable and not the AppCompat/MaterialComponents XML themes.
The TopAppBar uses the backgroundColor attribute.
The default value is defined by MaterialTheme.colors.primarySurface.
You can change these colors globally defining your theme adding your Colors and passing them to a MaterialTheme:
private val LightColors = lightColors(
primary = Yellow500,
//...
)
Otherwise you can simply use :
TopAppBar(
title = { Text("Activity") },
backgroundColor = /*...*/,
/* ... */
)
If you want to use the AppCompat XML themes in Jetpack Compose you can use the AppCompat Compose Theme Adapter provided by the accompanist library.
When you create a new project in studio, you get a file named Theme.kt, in which there are color palettes named lightColors and darkColors. You should modify the parameters of those values to achieve the result globally in your app.