Text color is not set properly - android-jetpack-compose

Every time I want to set the text color, it doesn't work properly. For example, if I have a LazyColumn with some texts that have White color, some of them have white color, and some of them are set to Black.
Sometimes the text color is set properly but it changes by itself when I navigate through screens or when I swipe up or down.
code:
Text(
color = MaterialTheme.colors.textColor,
text = team.uppercase(Locale.getDefault()),
fontSize = 25.sp
)
val Colors.textColor
#Composable
get() = if(isSystemInDarkTheme()) Color.White else Color.DarkGray
Any help?

Related

How to set the cursor to any part of the text using TextFieldValue (w/ FocusRequester) on pressing/clicking the TextField

I tried to look around but I can't find a way to
force a focus,
set the cursor to the end of text
and still be able to set the cursor to any part of the text when
pressing/clicking.
With FocusRequester the cursor is set to the start of text, but with TextFieldValue(<text>, <range>) I'm able to place the cursor at the end, the problem is that with this approach the cursor is always forced to any specified selection = TextRange(<index>)(in my case its the end using the current length of the changing value onValueChange), I have no idea how to set the cursor in any part (selection) when I press/click the TextField.
My Implementation:
var textFieldValue by remember { mutableStateOf(TextFieldValue("Some Text")) }
Row (
modifier = Modifier
.height(150.dp)
.fillMaxWidth()
.clickable {
focusRequester.requestFocus()
textFieldValue = textFieldValue.copy(selection = TextRange("Some Text".length))
}
) {
BasicTextField(
modifier = Modifier.focusRequester(focusRequester),
value = textFieldValue,
onValueChange = {
textFieldValue =
textFieldValue.copy(text = it.text, selection = TextRange(it.text.length))
},
)
}
And what I'm trying to achieve (Large text area with text set and starts from top-left), its entire part should be clickable and triggers focus for the text field, the reason why I wrapped it in a Row with a clickable modifier.
I wasn't able to achieve this with a single text field with specified height, as TextAlign doesn't have a Top-Start alignment

How to set an icon's color to [default color] in jetpack compose?

An icon has a default color, and it could be different under different themes.
When meet the condition, I hope the icon's color become Color.RED, otherwise it used the default color (example, white on one theme and yellow on another theme)
But I don't know the grammar of how to set to default color. Please help, thanks a lot!
val judge = ... //a mutableStateOf Boolean
...
// how to set [default color]?
Icon(painterResource(R.drawable.ic_baseline_error_outline_24),
contentDescription = null,
tint = if (judge) Color.RED else [default color])
If you go to Icon file you see its value:
tint: Color = LocalContentColor.current.copy(alpha = LocalContentAlpha.current)
You can just set it again

while using ModalBottomSheetLayout, how to make background and status bar transparent in Jetpack compose

I am new to jetpack. My app is having ModalBottomSheetLayout in MainScreen. Now when I click on button of MainScreen, it shows BottomSheet. When bottom sheet is open, the background is transparent but status bar is not. How to make it transparent?
So far, you can use the System UI Controller in the accompanist library to control the statusBar Color and navigationBar color
implementation "com.google.accompanist:accompanist-systemuicontroller:0.18.0"
// Remember a SystemUiController
val systemUiController = rememberSystemUiController()
val useDarkIcons = MaterialTheme.colors.isLight
SideEffect {
// Update all of the system bar colors to be transparent, and use
// dark icons if we're in light theme
systemUiController.setSystemBarsColor(
color = Color.Transparent,
darkIcons = useDarkIcons
)
// setStatusBarsColor() and setNavigationBarsColor() also exist
}

How to change UIDocumentInteractionController text color?

My app has an option for a dark theme, and when that is the case, I do something like this:
UILabel.appearance().textColor = .white
The problem is, the app provides the ability to export some text via UIDocumentInteractionController. When I do presentPreview it displays white text on a white background, which makes the text completely invisible. There doesn't seem to be any way to change the text color or background color of the UIDocumentInteractionController.
I tried this
UILabel.appearance(whenContainedInInstancesOf: [UIDocumentInteractionController.self]).textColor = .black
but that just gives Cannot convert value of type 'UIDocumentInteractionController.Type' to expected element type 'UIAppearanceContainer.Type'
I've also tried setting UILabel.appearance().textColor = .black before I create the UIDocumentInteractionController, but that doesn't help either - the text still appears white.
What's extra annoying, this works to change the nav bar title color:
let navBarTitleTextAttributes = [
NSAttributedString.Key.foregroundColor: UIColor.black,
]
UINavigationBar.appearance().titleTextAttributes = navBarTitleTextAttributes
self.dic = UIDocumentInteractionController()
...
But the label appearance is not responsive.

How to change Text color based on background Image - Flutter

I want to change text (and Icon) colors based on the background image for visibility.
I've tried:
Using palette_generator package, to check the Dominant Color of the background Image and useWhiteForgroundForColor function (returns a bool) from flutter_statusbarcolor package to select black or white color for the my text (and Icon) colors.
The Problem: Sometimes dominant color turns out null. In my tests, this happens with black and white colors and I don't know of any ways to find out which one.
Future<bool> useWhiteTextColor(String imageUrl) async {
PaletteGenerator paletteGenerator =
await PaletteGenerator.fromImageProvider(
NetworkImage(imageUrl),
// Images are square
size: Size(300, 300),
// I want the dominant color of the top left section of the image
region: Offset.zero & Size(40, 40),
);
Color dominantColor = paletteGenerator.dominantColor?.color;
// Here's the problem
// Sometimes dominantColor returns null
// With black and white background colors in my tests
if (dominantColor == null) print('Dominant Color null');
return useWhiteForeground(dominantColor);
}
I found other methods for other languages, but I don't know a way to implement the same method in dart.
Additional note:
My actual code includes some additional complications. I am using a SliverAppBar and here I want to determine the title and icons colors for when the flexibleSpace is expanded. I change their colors when collapsed with the help of the community based on this.
the color class already has a method to calculate luminance, called computeLuminance()
Color textColor = color.computeLuminance() > 0.5 ? Colors.black : Colors.white;
i use the below method to find out which one to be used (either black or white).
Color getTextColor(Color color) {
int d = 0;
// Counting the perceptive luminance - human eye favors green color...
double luminance =
(0.299 * color.red + 0.587 * color.green + 0.114 * color.blue) / 255;
if (luminance > 0.5)
d = 0; // bright colors - black font
else
d = 255; // dark colors - white font
return Color.fromARGB(color.alpha, d, d, d); }
There are Two ways of getting Text Color based upon the BG Color of Card or Button or Tags.
First One is :
Color txColor = color.computeLuminance() < 0.5 ? Colors.white : Colors.black;
The Second is using Theme , Where user may have dark theme or light theme of device.
import 'dart:math';
import 'package:flutter/material.dart';
class ColorEstimationPage extends StatelessWidget {
Color _randomBackgroundColor() {
List<Color> colors = [Colors.red, Colors.green, Colors.amber, Colors.black];
return colors[Random().nextInt(colors.length)];
}
/// With this you can get the Color either black or white
Color _textColorForBackground(Color backgroundColor) {
if (ThemeData.estimateBrightnessForColor(backgroundColor) ==
Brightness.dark) {
return Colors.white;
}
return Colors.black;
}
#override
Widget build(BuildContext context) {
Color bgColor = _randomBackgroundColor();
return Scaffold(
backgroundColor: bgColor,
body: Center(
child: Text(
"I'm the correct text color!",
style: TextStyle(color: _textColorForBackground(bgColor)),
),
),
);
}
}
You should create the palette generator like this
PaletteGenerator paletteGenerator =
await PaletteGenerator.fromImageProvider(
NetworkImage(imageUrl),
filters: [],
// Images are square
size: Size(300, 300),
// I want the dominant color of the top left section of the image
region: Offset.zero & Size(40, 40),
);
notice the empty list in the filters parameter
Colorful colors
If you have font/background colors that aren't only black and white, you should use some thing else:
final colorDifference = newBackgroundColor.computeLuminance() -
textColor.computeLuminance();
if (colorDifference.abs() < 0.2) {
textColor = textColor.computeLuminance() > 0.5
? Colors.black
: Colors.white;
}
With this, you will only change the font color if necessary (the luminance difference is so less that the colors don't really stand out).
For buttons you can use. this will auto change button color based on background
buttonTheme: ButtonThemeData(
buttonColor: Colors.teal[500],
textTheme: ButtonTextTheme.primary
)

Resources