I was trying to use FlexBox layout with JetpackCompose. I assumed that I can use normal RecyclerView and use ComposeView to render my view.
So I started with the documentation and attempted all the steps given in Compose document to use it with RecyclerView.
But once I did that, I got following error:
java.lang.IllegalStateException: Cannot locate windowRecomposer; View androidx.compose.ui.platform.ComposeView{83fefc1 V.E...... ......I. 0,0-0,0} is not attached to a window
[1] Adapter Code
class SelectAisleAdapter : BaseRecyclerViewAdapter<Any, SelectAisleAdapter.SelectAisleViewHolder>() {
override fun getViewHolder(
inflater: LayoutInflater,
parent: ViewGroup,
viewType: Int
): SelectAisleViewHolder {
return SelectAisleViewHolder(ComposeView(parent.context))
}
override fun onViewRecycled(holder: BaseViewHolder<Any>) {
super.onViewRecycled(holder)
if (holder is SelectAisleViewHolder) {
holder.composeView.disposeComposition()
}
}
inner class SelectAisleViewHolder(val composeView: ComposeView) : BaseViewHolder<Any>(composeView) {
init {
composeView.setViewCompositionStrategy(
ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed
)
}
override fun bind(item: Any) {
composeView.setContent {
AisleChip(text = "Milk", /*modifier = Modifier.padding(8.dp),*/ selected = false)
}
}
}
}
[2] Compose Code
#Composable
fun AisleChip(
modifier: Modifier = Modifier,
text: String,
selected: Boolean = false,
) {
val backgroundColor = if (selected) colorResource(id = R.color.colorPrimary) else colorResource(id = R.color.colorBackground)
val borderColor = if (selected) colorResource(id = R.color.colorPrimary) else colorResource(id = R.color.colorBorder)
val textColor = if (selected) colorResource(id = R.color.white) else colorResource(id = R.color.colorBorder)
Text(
text = text,
fontSize = 18.sp,
fontWeight = FontWeight.Regular,
fontFamily = appFontFamily,
color = textColor,
modifier = modifier
.clip(RoundedCornerShape(8.dp))
.border(
width = 1.dp,
color = borderColor,
shape = RoundedCornerShape(8.dp)
)
.background(backgroundColor)
.padding(16.dp)
)
}
[3] Activity Code
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val rv = findViewById<RecyclerView>(R.id.rvMain)
val adapter = SelectAisleAdapter()
rv.layoutManager = FlexboxLayoutManager(this)
rv.adapter = adapter
adapter.replaceItems(listOf("1", "2", "3", "4", "5"))
}
}
Complete StackTrace
java.lang.IllegalStateException: Cannot locate windowRecomposer; View androidx.compose.ui.platform.ComposeView{83fefc1 V.E...... ......I. 0,0-0,0} is not attached to a window
at androidx.compose.ui.platform.WindowRecomposer_androidKt.getWindowRecomposer(WindowRecomposer.android.kt:225)
at androidx.compose.ui.platform.AbstractComposeView.resolveParentCompositionContext(ComposeView.android.kt:220)
at androidx.compose.ui.platform.AbstractComposeView.ensureCompositionCreated(ComposeView.android.kt:227)
at androidx.compose.ui.platform.AbstractComposeView.onMeasure(ComposeView.android.kt:264)
at android.view.View.measure(View.java:24530)
at com.google.android.flexbox.FlexboxHelper.calculateFlexLines(FlexboxHelper.java:477)
at com.google.android.flexbox.FlexboxHelper.calculateHorizontalFlexLines(FlexboxHelper.java:249)
at com.google.android.flexbox.FlexboxLayoutManager.updateFlexLines(FlexboxLayoutManager.java:960)
at com.google.android.flexbox.FlexboxLayoutManager.onLayoutChildren(FlexboxLayoutManager.java:737)
at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3851)
at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4404)
at android.view.View.layout(View.java:21912)
at android.view.ViewGroup.layout(ViewGroup.java:6260)
at androidx.constraintlayout.widget.ConstraintLayout.onLayout(ConstraintLayout.java:1873)
at android.view.View.layout(View.java:21912)
at android.view.ViewGroup.layout(ViewGroup.java:6260)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
at android.view.View.layout(View.java:21912)
at android.view.ViewGroup.layout(ViewGroup.java:6260)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1829)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1673)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1582)
at android.view.View.layout(View.java:21912)
at android.view.ViewGroup.layout(ViewGroup.java:6260)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
at android.view.View.layout(View.java:21912)
at android.view.ViewGroup.layout(ViewGroup.java:6260)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1829)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1673)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1582)
at android.view.View.layout(View.java:21912)
at android.view.ViewGroup.layout(ViewGroup.java:6260)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
at com.android.internal.policy.DecorView.onLayout(DecorView.java:779)
at android.view.View.layout(View.java:21912)
at android.view.ViewGroup.layout(ViewGroup.java:6260)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:3080)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2590)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1721)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7598)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:966)
at android.view.Choreographer.doCallbacks(Choreographer.java:790)
at android.view.Choreographer.doFrame(Choreographer.java:725)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:951)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2021-09-28 16:14:51.363 21103-21103/com.alphastack.shoppy I/Process: Sending signal. PID: 21103 SIG: 9
Related
Not sure what is wrong, I have my navController that im passing to CreateScheduledItemScreen to use it from there. But I cant navigate to anyscreen BUT Home screen from CreateScheduledItemScreen, if I do the app crashes.
The screens works and can be navigated to from the bottomBar.
#Composable
fun MotivationApp(
modifier: Modifier = Modifier,
viewModel: MotivationViewModel = MotivationViewModel(),
navController: NavHostController = rememberNavController()
) {
viewModel.fillPhotoArray()
// Get current back stack entry
val backStackEntry by navController.currentBackStackEntryAsState()
// Get the name of the current screen
val currentScreen = MotivateScreenNavHost.valueOf(
backStackEntry?.destination?.route ?: MotivateScreenNavHost.Home.name
)
Scaffold(bottomBar = {
BottomBar(navHostController = navController,
currentScreen = currentScreen,
canNavigateBack = navController.previousBackStackEntry != null,
navigateUp = { navController.navigateUp() })
}, topBar = {
MotivationTopAppBar(navHostController = navController,
currentScreen = currentScreen,
canNavigateBack = navController.previousBackStackEntry != null,
navigateUp = { navController.navigateUp() })
}) { innerPadding ->
NavHost(
navController = navController,
startDestination = MotivateScreenNavHost.Home.name,
modifier = modifier.padding(innerPadding)
) {
composable(route = MotivateScreenNavHost.Home.name) {
viewModel.setDates(homeScreen())
}
composable(route = MotivateScreenNavHost.Setting.name) {
val context = LocalContext.current
SettingsScreen()
}
composable(route = MotivateScreenNavHost.Profile.name) {
val context = LocalContext.current
ProfileScreen()
}
composable(route = MotivateScreenNavHost.AddScheduledItem.name) {
val context = LocalContext.current
CreateScheduledItemScreen(
viewModel.getPhotos(),
viewModel.getDates(),
navController,
viewModel
)
}
composable(route = MotivateScreenNavHost.CreateItemInputScreen.name) {
CreateItemInputScreen()
}
}
}
}
if I would change navController.navigate(MotivateScreenNavHost.CreateItemInputScreen.name) -> navController.navigate(MotivateScreenNavHost.Home.name) the app does not crash.
Any ideas?
#Composable
fun CreateScheduledItemScreen(
photo: ArrayList<Int>,
date: ArrayList<Int>,
navController: NavHostController,
viewModel: MotivationViewModel
) {
val mContext = LocalContext.current
LazyVerticalGrid(columns = GridCells.Adaptive(minSize = 185.dp), contentPadding = PaddingValues(
start = 12.dp, top = 16.dp, end = 12.dp, bottom = 16.dp
), content = {
items(photo.size) { index ->
Card(
backgroundColor = Color.Transparent,
modifier = Modifier
.padding(6.dp)
.fillMaxWidth(),
elevation = 0.dp,
) {
Column(verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.clickable {
val mCategory = when (photo[index]) {
R.drawable.training -> 1
R.drawable.travel -> 2
R.drawable.study -> 3
R.drawable.meetingjpg -> 4
R.drawable.party -> 5
R.drawable.doctor -> 6
R.drawable.dentist -> 7
R.drawable.groceries -> 8
else -> {
9
}
}
viewModel.setCategory(mCategory)
navController.navigate(MotivateScreenNavHost.CreateItemInputScreen.name)
}) {
Image(
painter = painterResource(photo[index]),
contentDescription = "Test",
modifier = Modifier
.size(150.dp)
.clip(CircleShape)
.border(
1.5.dp,
androidx.compose.material3.MaterialTheme.colorScheme.primary,
CircleShape
)
)
Text(
text = when (photo[index]) {
R.drawable.training -> "Training"
R.drawable.travel -> "Travel"
R.drawable.study -> "Study"
R.drawable.meetingjpg -> "Meeting"
R.drawable.party -> "Party"
R.drawable.doctor -> "Doctor"
R.drawable.dentist -> "Dentist"
R.drawable.groceries -> "Groceries"
else -> {
"Other"
}
}
)
Text(text = "${date[0]} ${date[1]} ${date[2]}")
}
}
}
})
}
I have tried a lot. Kinda new to composable and this navigate through composable.
I am expecting that when I click the button the new screen shows.
Error:
2022-11-07 15:44:09.622 24752-24752/com.pocketqueens.chefforhire E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.pocketqueens.chefforhire, PID: 24752
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at com.pocketqueens.chefforhire.activity.CreateScheduledItemScreenKt$CreateScheduledItemScreen$1$1$1.invoke(CreateScheduledItemScreen.kt:92)
at com.pocketqueens.chefforhire.activity.CreateScheduledItemScreenKt$CreateScheduledItemScreen$1$1$1.invoke(CreateScheduledItemScreen.kt:45)
at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:107)
at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
at androidx.compose.runtime.RecomposeScopeImpl.compose(RecomposeScopeImpl.kt:145)
at androidx.compose.runtime.ComposerImpl.recomposeToGroupEnd(Composer.kt:2375)
at androidx.compose.runtime.ComposerImpl.skipToGroupEnd(Composer.kt:2666)
at androidx.compose.material.SurfaceKt.Surface-F-jzlyU(Surface.kt:137)
at androidx.compose.material.CardKt.Card-F-jzlyU(Card.kt:68)
at com.pocketqueens.chefforhire.activity.CreateScheduledItemScreenKt$CreateScheduledItemScreen$1$1.invoke(CreateScheduledItemScreen.kt:39)
at com.pocketqueens.chefforhire.activity.CreateScheduledItemScreenKt$CreateScheduledItemScreen$1$1.invoke(CreateScheduledItemScreen.kt:38)
at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:135)
at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
at androidx.compose.foundation.lazy.grid.LazyGridItemsSnapshot.Item(LazyGridItemProviderImpl.kt:97)
at androidx.compose.foundation.lazy.grid.LazyGridItemProviderImpl.Item(LazyGridItemProviderImpl.kt:119)
at androidx.compose.foundation.lazy.layout.LazyLayoutItemContentFactory$CachedItemContent$createContentLambda$1$1.invoke(LazyLayoutItemContentFactory.kt:119)
at androidx.compose.foundation.lazy.layout.LazyLayoutItemContentFactory$CachedItemContent$createContentLambda$1$1.invoke(LazyLayoutItemContentFactory.kt:118)
at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:107)
at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
at androidx.compose.runtime.CompositionLocalKt.CompositionLocalProvider(CompositionLocal.kt:228)
at androidx.compose.runtime.saveable.SaveableStateHolderImpl.SaveableStateProvider(SaveableStateHolder.kt:84)
at androidx.compose.foundation.lazy.layout.LazyLayoutItemContentFactory$CachedItemContent$createContentLambda$1.invoke(LazyLayoutItemContentFactory.kt:118)
at androidx.compose.foundation.lazy.layout.LazyLayoutItemContentFactory$CachedItemContent$createContentLambda$1.invoke(LazyLayoutItemContentFactory.kt:110)
at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:107)
at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
at androidx.compose.ui.layout.LayoutNodeSubcompositionsState$subcompose$2$1$1.invoke(SubcomposeLayout.kt:771)
at androidx.compose.ui.layout.LayoutNodeSubcompositionsState$subcompose$2$1$1.invoke(SubcomposeLayout.kt:448)
at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:107)
at androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
at androidx.compose.runtime.ActualJvm_jvmKt.invokeComposable(ActualJvm.jvm.kt:78)
at androidx.compose.runtime.ComposerImpl$doCompose$2$5.invoke(Composer.kt:3248)
at androidx.compose.runtime.ComposerImpl$doCompose$2$5.invoke(Composer.kt:3238)
at androidx.compose.runtime.SnapshotStateKt__DerivedStateKt.observeDerivedStateRecalculations(DerivedState.kt:341)
at androidx.compose.runtime.SnapshotStateKt.observeDerivedStateRecalculations(Unknown Source:1)
at androidx.compose.runtime.ComposerImpl.doCompose(Composer.kt:3238)
at androidx.compose.runtime.ComposerImpl.composeContent$runtime_release(Composer.kt:3173)
2022-11-07 15:44:09.623 24752-24752/com.pocketqueens.chefforhire E/AndroidRuntime: at androidx.compose.runtime.CompositionImpl.composeContent(Composition.kt:587)
at androidx.compose.runtime.Recomposer.composeInitial$runtime_release(Recomposer.kt:950)
at androidx.compose.runtime.ComposerImpl$CompositionContextImpl.composeInitial$runtime_release(Composer.kt:3848)
at androidx.compose.runtime.ComposerImpl$CompositionContextImpl.composeInitial$runtime_release(Composer.kt:3848)
at androidx.compose.runtime.CompositionImpl.setContent(Composition.kt:519)
at androidx.compose.ui.layout.LayoutNodeSubcompositionsState.subcomposeInto(SubcomposeLayout.kt:468)
at androidx.compose.ui.layout.LayoutNodeSubcompositionsState.subcompose(SubcomposeLayout.kt:441)
at androidx.compose.ui.layout.LayoutNodeSubcompositionsState.subcompose(SubcomposeLayout.kt:432)
at androidx.compose.ui.layout.LayoutNodeSubcompositionsState.subcompose(SubcomposeLayout.kt:421)
at androidx.compose.ui.layout.LayoutNodeSubcompositionsState$Scope.subcompose(SubcomposeLayout.kt:733)
at androidx.compose.foundation.lazy.layout.LazyLayoutMeasureScopeImpl.measure-0kLqBqw(LazyLayoutMeasureScope.kt:118)
at androidx.compose.foundation.lazy.grid.LazyMeasuredItemProvider.getAndMeasure-ednRnyU(LazyMeasuredItemProvider.kt:44)
at androidx.compose.foundation.lazy.grid.LazyMeasuredLineProvider.getAndMeasure-bKFJvoY(LazyMeasuredLineProvider.kt:70)
at androidx.compose.foundation.lazy.grid.LazyGridMeasureKt.measureLazyGrid-zIfe3eg(LazyGridMeasure.kt:141)
at androidx.compose.foundation.lazy.grid.LazyGridKt$rememberLazyGridMeasurePolicy$1$1.invoke-0kLqBqw(LazyGrid.kt:340)
at androidx.compose.foundation.lazy.grid.LazyGridKt$rememberLazyGridMeasurePolicy$1$1.invoke(LazyGrid.kt:190)
at androidx.compose.foundation.lazy.layout.LazyLayoutKt$LazyLayout$2$1.invoke-0kLqBqw(LazyLayout.kt:74)
at androidx.compose.foundation.lazy.layout.LazyLayoutKt$LazyLayout$2$1.invoke(LazyLayout.kt:70)
at androidx.compose.ui.layout.LayoutNodeSubcompositionsState$createMeasurePolicy$1.measure-3p2s80s(SubcomposeLayout.kt:591)
at androidx.compose.ui.node.InnerNodeCoordinator.measure-BRTryo0(InnerNodeCoordinator.kt:103)
at androidx.compose.ui.graphics.SimpleGraphicsLayerModifier.measure-3p2s80s(GraphicsLayerModifier.kt:405)
at androidx.compose.ui.node.BackwardsCompatNode.measure-3p2s80s(BackwardsCompatNode.kt:343)
at androidx.compose.ui.node.LayoutModifierNodeCoordinator.measure-BRTryo0(LayoutModifierNodeCoordinator.kt:155)
at androidx.compose.ui.node.LayoutNodeLayoutDelegate$performMeasure$2.invoke(LayoutNodeLayoutDelegate.kt:1077)
at androidx.compose.ui.node.LayoutNodeLayoutDelegate$performMeasure$2.invoke(LayoutNodeLayoutDelegate.kt:1073)
at androidx.compose.runtime.snapshots.Snapshot$Companion.observe(Snapshot.kt:2139)
at androidx.compose.runtime.snapshots.SnapshotStateObserver$observeReads$1$1.invoke(SnapshotStateObserver.kt:130)
at androidx.compose.runtime.snapshots.SnapshotStateObserver$observeReads$1$1.invoke(SnapshotStateObserver.kt:126)
at androidx.compose.runtime.SnapshotStateKt__DerivedStateKt.observeDerivedStateRecalculations(DerivedState.kt:341)
at androidx.compose.runtime.SnapshotStateKt.observeDerivedStateRecalculations(Unknown Source:1)
at androidx.compose.runtime.snapshots.SnapshotStateObserver.observeReads(SnapshotStateObserver.kt:126)
at androidx.compose.ui.node.OwnerSnapshotObserver.observeReads$ui_release(OwnerSnapshotObserver.kt:120)
at androidx.compose.ui.node.OwnerSnapshotObserver.observeMeasureSnapshotReads$ui_release(OwnerSnapshotObserver.kt:107)
at androidx.compose.ui.node.LayoutNodeLayoutDelegate.performMeasure-BRTryo0(LayoutNodeLayoutDelegate.kt:1073)
at androidx.compose.ui.node.LayoutNodeLayoutDelegate.access$performMeasure-BRTryo0(LayoutNodeLayoutDelegate.kt:36)
at androidx.compose.ui.node.LayoutNodeLayoutDelegate$MeasurePassDelegate.remeasure-BRTryo0(LayoutNodeLayoutDelegate.kt:341)
at androidx.compose.ui.node.LayoutNode.remeasure-_Sx5XlM$ui_release(LayoutNode.kt:1135)
2022-11-07 15:44:09.623 24752-24752/com.pocketqueens.chefforhire E/AndroidRuntime: at androidx.compose.ui.node.LayoutNode.remeasure-_Sx5XlM$ui_release$default(LayoutNode.kt:1126)
at androidx.compose.ui.node.MeasureAndLayoutDelegate.doRemeasure-sdFAvZA(MeasureAndLayoutDelegate.kt:309)
at androidx.compose.ui.node.MeasureAndLayoutDelegate.remeasureAndRelayoutIfNeeded(MeasureAndLayoutDelegate.kt:434)
at androidx.compose.ui.node.MeasureAndLayoutDelegate.access$remeasureAndRelayoutIfNeeded(MeasureAndLayoutDelegate.kt:39)
at androidx.compose.ui.node.MeasureAndLayoutDelegate.measureAndLayout(MeasureAndLayoutDelegate.kt:330)
at androidx.compose.ui.platform.AndroidComposeView.measureAndLayout(AndroidComposeView.android.kt:774)
at androidx.compose.ui.node.Owner.measureAndLayout$default(Owner.kt:216)
at androidx.compose.ui.platform.AndroidComposeView.dispatchDraw(AndroidComposeView.android.kt:999)
at android.view.View.draw(View.java:20210)
at android.view.View.updateDisplayListIfDirty(View.java:19082)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4317)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4290)
at android.view.View.updateDisplayListIfDirty(View.java:19042)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4317)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4290)
at android.view.View.updateDisplayListIfDirty(View.java:19042)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4317)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4290)
at android.view.View.updateDisplayListIfDirty(View.java:19042)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4317)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4290)
at android.view.View.updateDisplayListIfDirty(View.java:19042)
at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:686)
at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:692)
at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:801)
at android.view.ViewRootImpl.draw(ViewRootImpl.java:3311)
at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:3115)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2484)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1460)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7183)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:949)
at android.view.Choreographer.doCallbacks(Choreographer.java:761)
at android.view.Choreographer.doFrame(Choreographer.java:696)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2022-11-07 15:44:09.630 24752-24752/com.pocketqueens.chefforhire I/Process: Sending signal. PID: 24752 SIG: 9
I'm new in jetpack compose. I developed an app by XML and Kotlin and want to move it to jetpack compose. The problem is that I have one activity and one fragment that there are several CardViews in the activity and when clicking on them they send a specific key to the fragment and the fragment shows specific information related to that CardView (I just have used one fragment), now in jetpack compose I don't know how to implement it. Could anyone help me, please? I have no problem with navigation I want to know how to change an Image and some Texts. I wonder that how can I use
when (key) {"key" -> text = ... imageResource = ...} in compose or not?
this is my code for XML
class BaseFragment : Fragment() {
internal lateinit var view: View
private lateinit var imgMain : ImageView
private lateinit var txtIngredients : TextView
private lateinit var txtMaking : TextView
private lateinit var txtBeCareful : TextView
#Suppress("UNREACHABLE_CODE")
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
view = inflater.inflate(R.layout.base_fragment, container,
false)
setupViews()
return view
}
private fun setupViews() {
imgMain = view.findViewById(R.id.img_BaseFragment_mainImg)
txtIngredients =
view.findViewById(R.id.txt_BaseFragment_ingredients)
txtMaking = view.findViewById(R.id.txt_BaseFragment_making)
txtBeCareful =
view.findViewById(R.id.txt_BaseFragment_beCareFullText)
this.arguments?.let {
when (it.getString(key: "itemTitle", defaultVlue :"")) {
"mas1" -> {
makeContent(R.drawable.mas1,
R.string.mas1,
R.string.mas1_making,
R.string.mas1_text)
}
"mas2" -> {
makeContent(R.drawable.mas2,
R.string.mas2,
R.string.mas2_making,
R.string.mas2_text)
}
"mas3" -> {
makeContent(R.drawable.mas3,
R.string.mas3,
R.string.mas3_making,
R.string.mas3_text)
}
}
private fun makeContent(imgCont : Int, txtIngredientsCont : Int,
txtMakingCont : Int, txtBeCarCont : Int ){
imgMain.setImageResource(imgCont)
txtIngredients.setText(txtIngredientsCont)
txtMaking.setText(txtMakingCont)
txtBeCareful.setText(txtBeCarCont)
}
}
and this is my code in jetpack compose but it doesn't work
#SuppressLint("UnusedMaterialScaffoldPaddingParameter")
#Composable
fun FinalShowScreen(itemTitle: String? = null, navController:
NavController) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(3.dp)
.verticalScroll(rememberScrollState())
) {
var imageId: Int
var textIngredientsId: Int
var textMakingId: Int
var textBeCarefulId: Int
when (maskArg) {
"mas1" -> {
imageId = R.drawable.mas1
textIngredientsId = R.string.mas1
textMakingId = R.string.mas1making
textBeCarefulId = R.string.mas1_text
}
"mas2" -> {
imageId = R.drawable.mas2
textIngredientsId = R.string.mas2
textMakingId = R.string.mas2making
textBeCarefulId = R.string.mas2_text
}
"mas3" -> {
imageId = R.drawable.mas3
textIngredientsId = R.string.mas3
textMakingId = R.string.mas3making
textBeCarefulId = R.string.mas3_text
}
Image(
painter = painterResource(id =
imageId),
contentDescription = "",
modifier = Modifier
.padding(bottom = 8.dp)
.height(200.dp)
.fillMaxSize()
)
Text(
text = stringResource(id = textIngredientsId),
style = typography.h1,
color = MaterialTheme.colors.primary,
textAlign = TextAlign.Center,
modifier = Modifier
.padding(8.dp)
)
Text(
text = stringResource(id =
textMakingId),
style = typography.h2,
color = MaterialTheme.colors.primaryVariant,
textAlign = TextAlign.Start,
modifier = Modifier
.padding(start = 8.dp, end = 8.dp, bottom = 15.dp,
top = 8.dp)
)
Text(
text = stringResource(id =
textBeCarefulId),
style = typography.h2,
color = MaterialTheme.colors.primaryVariant,
textAlign = TextAlign.Start,
modifier = Modifier
.padding(8.dp)
)
}
}
Finally, my problem was solved when, I changed the variables to
#DrawableRes imageId: Int,
#StringRes textIngredientsId: Int,
#StringRes textMakingId: Int,
#StringRes textBeCarefulId: Int
and I changed the navigation method in the Navgragh to this
class MainActions(navController: NavController) {
val gotoFinalShow: (String) -> Unit = { maskArg ->
navController.navigate("${Screens.FinalShow.route}/$maskArg"){
launchSingleTop = true
restoreState = true
}
}
}
---> Full Code for more details https://github.com/BUdiAKmal/CaseApp
After passing URL from "RecyclerView" to Button on "DetailsActivity" , i try to forwarding and load the URL to "WebViewActivity" when user click the "Button on DeetailsActivity".
and finally i get this error :
FATAL EXCEPTION: main
Process: com.caseapp, PID: 5139
java.lang.StackOverflowError: stack size 8MB
at android.os.Parcel.-get0(Unknown Source:0)
at android.os.Parcel$ReadWriteHelper.writeString(Parcel.java:353)
at android.os.Parcel.writeString(Parcel.java:675)
at android.content.ComponentName.writeToParcel(ComponentName.java:320)
at android.content.ComponentName.writeToParcel(ComponentName.java:335)
at android.content.Intent.writeToParcel(Intent.java:9566)
at android.os.Parcel.writeParcelable(Parcel.java:1791)
at android.os.Parcel.writeValue(Parcel.java:1697)
at android.os.Parcel.writeArrayMapInternal(Parcel.java:838)
at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1542)
at android.os.Bundle.writeToParcel(Bundle.java:1232)
at android.os.Parcel.writeBundle(Parcel.java:878)
at android.content.Intent.writeToParcel(Intent.java:9599)
at com.caseapp.ui.activities.DetailsActivity.initView$lambda-2$lambda-1(DetailsActivity.kt:68)
at com.caseapp.ui.activities.DetailsActivity.$r8$lambda$JHNmedXwzuffRCNJln7AS9uz4NI(Unknown Source:0)
at com.caseapp.ui.activities.DetailsActivity$$ExternalSyntheticLambda0.onClick(Unknown Source:2)
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Start - full screen
val window = window
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
) // End - full screen
setUpTabs() // Setup TabLayout
} // End - OnCreate
// Start - TabLayout
private fun setUpTabs() {
val adapter = ViewPagerAdapter(supportFragmentManager)
adapter.addFragment(MainTabFragment1(), "MainTab1")
adapter.addFragment(MainTabFragment1(), "MainTab2")
viewPager_tabLayout.adapter = adapter
tabs.setupWithViewPager(viewPager_tabLayout)
} // End - TabLayout
} // End - Class
MainTabFragment1.kt
class MainTabFragment1 : Fragment() {
lateinit var mainTabFragment1Adapter: MainTabFragment1Adapter // Initialize Adapter
private val sLM = LinearLayoutManager(context) // Initialize layoutManager
val addMainTabFragment1ModelList: MutableList<MainTabFragment1Model> = ArrayList() // Initialize listModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment1_main_tab, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initViewMainTabFragment1() // SetUp initView listModel
actionMainTabFragment1() // SetUp actionMainTabFragment1
} // End - OnCreate
// Start - intView listModel
private fun initViewMainTabFragment1() {
rv_mainTabFragment1.layoutManager = sLM
mainTabFragment1Adapter = MainTabFragment1Adapter(requireActivity())
rv_mainTabFragment1.adapter = mainTabFragment1Adapter
addMainTabFragment1ModelList.add(
MainTabFragment1Model(
"https://images.unsplash.com/photo-1585435465945-bef5a93f8849",
"Title RVItemNo.1 MainTabFragment1",
"Desc RVItenNo.1 MainTabFragment1",
"https://google.com"
)
)
addMainTabFragment1ModelList.add(
MainTabFragment1Model(
"https://images.unsplash.com/photo-1487846698364-db1316e3d140",
"Title RVItemNo.2 MainTabFragment1",
"Desc RVItenNo.2 MainTabFragment1",
"https://youtube.com"
)
)
addMainTabFragment1ModelList.add(
MainTabFragment1Model(
"https://images.unsplash.com/photo-1512295767273-ac109ac3acfa",
"Title RVItemNo.3 MainTabFragment1",
"Desc RVItenNo.3 MainTabFragment1",
"https://gmail.com"
)
)
addMainTabFragment1ModelList.add(
MainTabFragment1Model(
"https://images.unsplash.com/photo-1525896969906-0a4806967ef0",
"Title RVItemNo.4 MainTabFragment1",
"Desc RVItenNo.4 MainTabFragment1",
"https://blgger.com"
)
)
mainTabFragment1Adapter.setMainTabFragment1(addMainTabFragment1ModelList)
} // End - intView listModel
// Start - putExtra
fun actionMainTabFragment1() {
mainTabFragment1Adapter.setOnClickItemListenerMainTabFragment1(object : OnItemClickListener {
override fun onItemClick(item: View, position: Int) {
val i = Intent(context, DetailsActivity::class.java)
i.putExtra(
"titleTextMainTabFragment1",
mainTabFragment1Adapter
.getMainTabFragment1()
.get(position)
.titleTextMainTabFragment1
)
i.putExtra(
"descTextMainTabFragment1",
mainTabFragment1Adapter
.getMainTabFragment1()
.get(position)
.descTextMainTabFragment1
)
i.putExtra(
"imgURLMainTabFragment1",
mainTabFragment1Adapter
.getMainTabFragment1()
.get(position)
.imgURLMainTabFragment1
)
i.putExtra(
"btnURLMainTabFragment1",
mainTabFragment1Adapter
.getMainTabFragment1()
.get(position)
.btnURLMainTabFragment1
)
startActivity(i)
}
})
} // End - putExtra
}
DetailsActivity.kt
class DetailsActivity : AppCompatActivity() {
var prodBundle: Bundle? = null // Initialize getString (bundle) from MainActivity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_details)
// Start - full screen
val window = window
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
) // End - full screen
initView() // Setup getString from RecyclerView Main Activity
} // End - OnCreate
// Start - getString from RecyclerView Main Activity
fun initView() {
prodBundle = intent.extras
tv_titleText.text = prodBundle?.getString("titleTextMainTabFragment1")
tv_descText.text = prodBundle?.getString("descTextMainTabFragment1")
prodBundle?.getString("imgURLMainTabFragment1").let {
Glide.with(this).asBitmap()
.load(it)
.into(iv_imgURL)
Glide.with(this).asBitmap()
.load(it)
.centerCrop()
.fitCenter()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
}
prodBundle?.getString("btnURLMainTabFragment1").let {
btn_wvURL.setOnClickListener {
val gotoWebView = Intent(this#DetailsActivity, WebViewActivity::class.java)
gotoWebView.putExtra("btnURLMainTabFragment1", gotoWebView)
startActivity(gotoWebView)
}
}
} // End - getString from RecyclerView Main Activity }
} // End - Class
MainTabFragment1Adapter.kt
class MainTabFragment1Adapter(private val context: Context) :
RecyclerView.Adapter<MainTabFragment1Adapter.MainTabFragment1ViewHolder>() {
private val MainTabFragment1Model: MutableList<MainTabFragment1Model> = mutableListOf() // Initialize listModel
private lateinit var onSelectedListenerMainTabFragment1: OnItemClickListener // Initialize onItemListener
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainTabFragment1ViewHolder {
return MainTabFragment1ViewHolder(
LayoutInflater.from(context).inflate(R.layout.item_maintab_fragment1_layout, parent, false)
)
} // End - onCreateViewHolder
override fun getItemCount(): Int {
return MainTabFragment1Model.size
} // End - getItem
override fun onBindViewHolder(holder: MainTabFragment1ViewHolder, position: Int) {
holder.maintabfragment1BindView(MainTabFragment1Model[position])
} // End - onBindViewHolder
// Start - setMainTabFragment1
fun setMainTabFragment1(data: List<MainTabFragment1Model>) {
MainTabFragment1Model.clear()
MainTabFragment1Model.addAll(data)
notifyDataSetChanged()
} // End - setMainTabFragment1
// Start - getMainTabFragment1
fun getMainTabFragment1(): MutableList<MainTabFragment1Model> {
return MainTabFragment1Model
} // End - getMainTabFragment1
// Start - MainTabFragment1ViewHolder
inner class MainTabFragment1ViewHolder(maintabfragment1view: View) : RecyclerView.ViewHolder(maintabfragment1view) {
val ivMainTabFragment1 = maintabfragment1view.findViewById<ImageView>(R.id.iv_RVItem_MainTabFragment1)
val tvTitleMainTabFragment1 = maintabfragment1view.findViewById<TextView>(R.id.tv_titleText_MainTabFragment1)
val cvMainTabFragment1: MaterialCardView = maintabfragment1view.findViewById(R.id.cv_RVItem_MainTabFragment1)
fun maintabfragment1BindView(MainTabFragment1Model: MainTabFragment1Model) {
MainTabFragment1Model.apply {
val image = MainTabFragment1Model.imgURLMainTabFragment1
image.let {
Glide.with(itemView.context)
.load(it)
.into(ivMainTabFragment1)
Glide.with(itemView.context)
.load(it)
.centerCrop()
.fitCenter()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
}
}
tvTitleMainTabFragment1.text = MainTabFragment1Model.titleTextMainTabFragment1
}
init {
cvMainTabFragment1.setOnClickListener { onSelectedListenerMainTabFragment1.onItemClick(it, layoutPosition) }
}
} // End - MainTabFragment1BindViewHolder
// Start - OnItemListener
fun setOnClickItemListenerMainTabFragment1(onItemClickListener: OnItemClickListener) {
this.onSelectedListenerMainTabFragment1 = onItemClickListener
} // End - OnItemListener
} // End - Class
MainTabFragment1Model.kt
data class MainTabFragment1Model
(var imgURLMainTabFragment1: String?,
var titleTextMainTabFragment1: String?,
var descTextMainTabFragment1: String?,
val btnURLMainTabFragment1: String?)
Listener.kt
interface OnItemClickListener {
fun onItemClick(item: View, position:Int)
}
WebViewActivity.kt
class WebViewActivity : AppCompatActivity() {
private lateinit var webView: WebView // Initialize WebView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_webview)
// Start - Assign Open New URL
val wBS = intent
val webSite = wBS.getStringExtra("btnURLMainTabFragment1")
// End - Assign Open New URL
// Start - full screen
val window = window
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
) // End - full screen
// Start - WebView
webView = findViewById(R.id.wv)
webView.setWebViewClient(object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
view?.visibility = View.INVISIBLE
if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null)
} else {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null)
}
}
override fun onPageFinished(view: WebView?, url: String?) {
swipe?.isRefreshing = false
super.onPageFinished(view, url)
view?.visibility = View.VISIBLE
}
// Start - Fix Whatsapp Acces
override fun shouldOverrideUrlLoading(wv: WebView, url: String): Boolean {
if (url.startsWith("tel:") || url.startsWith("whatsapp:")) {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(url)
startActivity(intent)
webView.goBack()
return true
}
return false
} // End - Fix Whatsapp Acces
}) // End - WebView
refreshApp() // SetUp SwipeRefresh
// Start - WebView Setting
if (webSite != null) {
webView.loadUrl(webSite)
}
val webSettings = webView.settings
webSettings.javaScriptEnabled = true // js active
webSettings.domStorageEnabled = true // componenet load
webSettings.allowContentAccess = true
webSettings.loadsImagesAutomatically = true
webSettings.cacheMode = WebSettings.LOAD_NO_CACHE
webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH)
webSettings.setEnableSmoothTransition(true)
// End - WebView Setting
}// End -OnCreate
// Start - BackPressed CurrentView
override fun onBackPressed() {
if (webView.canGoBack()) {
webView.goBack()
} else
super.onBackPressed()
} // End - BackPressed CurrentView
// Start - SwipeRefresh
private fun refreshApp() {
swipe.setOnRefreshListener {
webView?.reload()
Toast.makeText(this, "Refresh!", Toast.LENGTH_SHORT).show()
}
} // End- SwipeRefresh
} // finish MainActivity
I know there must be something wrong in my "DetailsActivity.kt",
especially on this line :
prodBundle?.getString("btnURLMainTabFragment1").let {
btn_wvURL.setOnClickListener {
val gotoWebView = Intent(this#DetailsActivity, WebViewActivity::class.java)
gotoWebView.putExtra("btnURLMainTabFragment1", gotoWebView)
startActivity(gotoWebView)
}
How to solve it?
I hope someone can solve this case. And thanks for taking your time.
Here you are sending the intent as an extra to the intent itself:
val gotoWebView = Intent(this#DetailsActivity, WebViewActivity::class.java)
>>> gotoWebView.putExtra("btnURLMainTabFragment1", gotoWebView)
You can try:
prodBundle?.getString("btnURLMainTabFragment1")?.let { url->
btn_wvURL.setOnClickListener {
val gotoWebView = Intent(this#DetailsActivity, WebViewActivity::class.java)
gotoWebView.putExtra("btnURLMainTabFragment1", url)
startActivity(gotoWebView)
}
This should work.
---> Full Code for more details https://github.com/BUdiAKmal/CaseApp
I've been successfully pass the data, but how about the URL?
i need to open URL contained in each item to WebView Activity but by pressing the button on "Activity Details"...
How to do it from this code?
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Start - full screen
val window = window
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
) // End - full screen
setUpTabs() // Setup TabLayout
} // End - OnCreate
// Start - TabLayout
private fun setUpTabs() {
val adapter = ViewPagerAdapter(supportFragmentManager)
adapter.addFragment(MainTabFragment1(), "MainTab1")
adapter.addFragment(MainTabFragment1(), "MainTab2")
viewPager_tabLayout.adapter = adapter
tabs.setupWithViewPager(viewPager_tabLayout)
} // End - TabLayout
} // End - Class
MainTabFragment
class MainTabFragment1 : Fragment() {
lateinit var mainTabFragment1Adapter: MainTabFragment1Adapter // Initialize Adapter
private val sLM = LinearLayoutManager(context) // Initialize layoutManager
val addMainTabFragment1ModelList: MutableList<MainTabFragment1Model> = ArrayList() // Initialize listModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment1_main_tab, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initViewMainTabFragment1() // SetUp initView listModel
actionMainTabFragment1() // SetUp actionMainTabFragment1
} // End - OnCreate
// Start - intView listModel
private fun initViewMainTabFragment1() {
rv_mainTabFragment1.layoutManager = sLM
mainTabFragment1Adapter = MainTabFragment1Adapter(requireActivity())
rv_mainTabFragment1.adapter = mainTabFragment1Adapter
addMainTabFragment1ModelList.add(
MainTabFragment1Model(
"https://images.unsplash.com/photo-1585435465945-bef5a93f8849",
"Title RVItemNo.1 MainTabFragment1",
"Desc RVItenNo.1 MainTabFragment1",
"https://google.com"
)
)
addMainTabFragment1ModelList.add(
MainTabFragment1Model(
"https://images.unsplash.com/photo-1487846698364-db1316e3d140",
"Title RVItemNo.2 MainTabFragment1",
"Desc RVItenNo.2 MainTabFragment1",
"https://youtube.com"
)
)
addMainTabFragment1ModelList.add(
MainTabFragment1Model(
"https://images.unsplash.com/photo-1512295767273-ac109ac3acfa",
"Title RVItemNo.3 MainTabFragment1",
"Desc RVItenNo.3 MainTabFragment1",
"https://gmail.com"
)
)
addMainTabFragment1ModelList.add(
MainTabFragment1Model(
"https://images.unsplash.com/photo-1525896969906-0a4806967ef0",
"Title RVItemNo.4 MainTabFragment1",
"Desc RVItenNo.4 MainTabFragment1",
"https://blgger.com"
)
)
mainTabFragment1Adapter.setMainTabFragment1(addMainTabFragment1ModelList)
} // End - intView listModel
// Start - putExtra
fun actionMainTabFragment1() {
mainTabFragment1Adapter.setOnClickItemListenerMainTabFragment1(object : OnItemClickListener {
override fun onItemClick(item: View, position: Int) {
val i = Intent(context, DetailsActivity::class.java)
i.putExtra(
"titleTextMainTabFragment1",
mainTabFragment1Adapter
.getMainTabFragment1()
.get(position)
.titleTextMainTabFragment1
)
i.putExtra(
"descTextMainTabFragment1",
mainTabFragment1Adapter
.getMainTabFragment1()
.get(position)
.descTextMainTabFragment1
)
i.putExtra(
"imgURLMainTabFragment1",
mainTabFragment1Adapter
.getMainTabFragment1()
.get(position)
.imgURLMainTabFragment1
)
i.putExtra(
"btnURLMainTabFragment1",
mainTabFragment1Adapter
.getMainTabFragment1()
.get(position)
.btnURLMainTabFragment1
)
startActivity(i)
}
})
} // End - putExtra
}
MainTabFragment1Adapter
class MainTabFragment1Adapter(private val context: Context) :
RecyclerView.Adapter<MainTabFragment1Adapter.MainTabFragment1ViewHolder>() {
private val MainTabFragment1Model: MutableList<MainTabFragment1Model> = mutableListOf() // Initialize listModel
private lateinit var onSelectedListenerMainTabFragment1: OnItemClickListener // Initialize onItemListener
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainTabFragment1ViewHolder {
return MainTabFragment1ViewHolder(
LayoutInflater.from(context).inflate(R.layout.item_maintab_fragment1_layout, parent, false)
)
} // End - onCreateViewHolder
override fun getItemCount(): Int {
return MainTabFragment1Model.size
} // End - getItem
override fun onBindViewHolder(holder: MainTabFragment1ViewHolder, position: Int) {
holder.maintabfragment1BindView(MainTabFragment1Model[position])
} // End - onBindViewHolder
// Start - setMainTabFragment1
fun setMainTabFragment1(data: List<MainTabFragment1Model>) {
MainTabFragment1Model.clear()
MainTabFragment1Model.addAll(data)
notifyDataSetChanged()
} // End - setMainTabFragment1
// Start - getMainTabFragment1
fun getMainTabFragment1(): MutableList<MainTabFragment1Model> {
return MainTabFragment1Model
} // End - getMainTabFragment1
// Start - MainTabFragment1ViewHolder
inner class MainTabFragment1ViewHolder(maintabfragment1view: View) : RecyclerView.ViewHolder(maintabfragment1view) {
val ivMainTabFragment1 = maintabfragment1view.findViewById<ImageView>(R.id.iv_RVItem_MainTabFragment1)
val tvTitleMainTabFragment1 = maintabfragment1view.findViewById<TextView>(R.id.tv_titleText_MainTabFragment1)
val cvMainTabFragment1: MaterialCardView = maintabfragment1view.findViewById(R.id.cv_RVItem_MainTabFragment1)
fun maintabfragment1BindView(MainTabFragment1Model: MainTabFragment1Model) {
MainTabFragment1Model.apply {
val image = MainTabFragment1Model.imgURLMainTabFragment1
image.let {
Glide.with(itemView.context)
.load(it)
.into(ivMainTabFragment1)
Glide.with(itemView.context)
.load(it)
.centerCrop()
.fitCenter()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
}
}
tvTitleMainTabFragment1.text = MainTabFragment1Model.titleTextMainTabFragment1
}
init {
cvMainTabFragment1.setOnClickListener { onSelectedListenerMainTabFragment1.onItemClick(it, layoutPosition) }
}
} // End - MainTabFragment1BindViewHolder
// Start - OnItemListener
fun setOnClickItemListenerMainTabFragment1(onItemClickListener: OnItemClickListener) {
this.onSelectedListenerMainTabFragment1 = onItemClickListener
} // End - OnItemListener
} // End - Class
MainTabFragment1Model
data class MainTabFragment1Model
(var imgURLMainTabFragment1: String?,
var titleTextMainTabFragment1: String?,
var descTextMainTabFragment1: String?,
val btnURLMainTabFragment1: String?)
Listener
interface OnItemClickListener {
fun onItemClick(item: View, position:Int)
}
WebViewActivity
class WebViewActivity : AppCompatActivity() {
private lateinit var webView: WebView // Initialize WebView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_webview)
// Start - Assign Open New URL
val wBS = intent
val webSite = wBS.getStringExtra("btnURLMainTabFragment1")
// End - Assign Open New URL
// Start - full screen
val window = window
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
) // End - full screen
// Start - WebView
webView = findViewById(R.id.wv)
webView.setWebViewClient(object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
view?.visibility = View.INVISIBLE
if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null)
} else {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null)
}
}
override fun onPageFinished(view: WebView?, url: String?) {
swipe?.isRefreshing = false
super.onPageFinished(view, url)
view?.visibility = View.VISIBLE
}
// Start - Fix Whatsapp Acces
override fun shouldOverrideUrlLoading(wv: WebView, url: String): Boolean {
if (url.startsWith("tel:") || url.startsWith("whatsapp:")) {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(url)
startActivity(intent)
webView.goBack()
return true
}
return false
} // End - Fix Whatsapp Acces
}) // End - WebView
refreshApp() // SetUp SwipeRefresh
// Start - WebView Setting
if (webSite != null) {
webView.loadUrl(webSite)
}
val webSettings = webView.settings
webSettings.javaScriptEnabled = true // js active
webSettings.domStorageEnabled = true // componenet load
webSettings.allowContentAccess = true
webSettings.loadsImagesAutomatically = true
webSettings.cacheMode = WebSettings.LOAD_NO_CACHE
webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH)
webSettings.setEnableSmoothTransition(true)
// End - WebView Setting
}// End -OnCreate
// Start - BackPressed CurrentView
override fun onBackPressed() {
if (webView.canGoBack()) {
webView.goBack()
} else
super.onBackPressed()
} // End - BackPressed CurrentView
// Start - SwipeRefresh
private fun refreshApp() {
swipe.setOnRefreshListener {
webView?.reload()
Toast.makeText(this, "Refresh!", Toast.LENGTH_SHORT).show()
}
} // End- SwipeRefresh
} // finish MainActivity
I hope someone can solve this case. thanks :)
I'm having troubles to change the colors of my material theme, this is what I have:
Surface(
modifier = Modifier
.fillMaxWidth()
.height(400.dp)
.constrainAs(surface) {
bottom.linkTo(parent.bottom)
},
color = MaterialTheme.colors.Background,
shape = RoundedCornerShape(topEndPercent = 8, topStartPercent = 8)
)
additionally I have this:
private val LightColorPalette = lightColors(
primary = Purple500,
primaryVariant = Purple700,
secondary = Teal200,
background = Background
)
and this
val Purple200 = Color(0xFFBB86FC)
val Purple500 = Color(0xFF6200EE)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
val Background =Color(red = 252, green = 237, blue = 203)
but when I see the app the background is white and I don't know why, what would be the problem?
You have to wrap your content with MaterialTheme composable that is using your color palette, like this:
MaterialTheme(
colors = LightColorPalette,
) {
Surface(
...
)
}
It's described here: https://developer.android.com/jetpack/compose/themes/material
as Jan Bina said the problem was that I wasn't using my MatherialTheme so in the MainActivity I made this change:
From this:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
LoginScreen()
}
}
}
To this:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
OrderForYouTheme {
LoginScreen()
}
}
}
}