content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.retrofit_mvvm_v001.model
data class Post(val id:Int, val body:String)
| retrofit_mvvm_simple_example/app/src/main/java/com/example/retrofit_mvvm_v001/model/Post.kt | 441011298 |
package com.example.retrofit_mvvm_v001.view
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.retrofit_mvvm_v001.api.RetrofitInstance
import com.example.retrofit_mvvm_v001.repository.PostRepository
import com.example.retrofit_mvvm_v001.ui.theme.Retrofit_MVVM_v001Theme
import com.example.retrofit_mvvm_v001.viewmodel.PostViewModel
import com.example.retrofit_mvvm_v001.viewmodel.PostViewModelFactory
class MainActivity : ComponentActivity() {
private val TAG = "==> MainActivity "
private lateinit var postViewModel: PostViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val apiService = RetrofitInstance
val postRepository = PostRepository(apiService)
val postViewModelFactory = PostViewModelFactory(postRepository)
postViewModel = ViewModelProvider(this, postViewModelFactory).get(PostViewModel::class.java)
postViewModel.post.observe(this, Observer {
Log.d(TAG, "onCreate: Post "+it.body)
})
postViewModel.isLoading.observe(this, Observer {
Log.d(TAG, "onCreate: is Loading ....$it")
})
postViewModel.error.observe(this, Observer {
Log.d(TAG, "onCreate: Error $it")
})
postViewModel.loadPost()
setContent { content() }
}
}
@Composable
fun content(){
Retrofit_MVVM_v001Theme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Greeting("Android")
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
Retrofit_MVVM_v001Theme {
Greeting("Android")
}
} | retrofit_mvvm_simple_example/app/src/main/java/com/example/retrofit_mvvm_v001/view/MainActivity.kt | 1688764150 |
package com.example.retrofit_mvvm_v001.api
import com.example.retrofit_mvvm_v001.util.Constant
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitInstance {
private val retrofit by lazy {
Retrofit
.Builder()
.baseUrl(Constant.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
val api: SimpleApi by lazy {
retrofit.create(SimpleApi::class.java)
}
} | retrofit_mvvm_simple_example/app/src/main/java/com/example/retrofit_mvvm_v001/api/RetrofitInstance.kt | 239835271 |
package com.example.retrofit_mvvm_v001.api
import com.example.retrofit_mvvm_v001.model.Post
import retrofit2.Response
import retrofit2.http.GET
interface SimpleApi {
@GET("posts/1")
suspend fun getPost():Response<Post>
} | retrofit_mvvm_simple_example/app/src/main/java/com/example/retrofit_mvvm_v001/api/SimpleApi.kt | 4059562152 |
import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.res.loadImageBitmap
import androidx.compose.ui.res.useResource
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import androidx.compose.ui.window.rememberWindowState
import androidx.compose.ui.window.singleWindowApplication
fun main() = application {
val windowState = rememberWindowState(size = DpSize(1200.dp,800.dp))
Window(
onCloseRequest = ::exitApplication,
title = "Ventanas",
state = windowState
){
MainWindow()
}
}
@Composable
@Preview
fun MainWindow(){
val icon = BitmapPainter(useResource(""))
singleWindowApplication(icon = icon) {
Text("Ventana Principal")
}
} | EjerciciosCompose1/src/main/kotlin/VentanaEjercicio.kt | 1833754926 |
package Tutoriales
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.loadImageBitmap
import androidx.compose.ui.res.loadSvgPainter
import androidx.compose.ui.res.loadXmlImageVector
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.singleWindowApplication
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.xml.sax.InputSource
import java.io.File
import java.io.IOException
import java.net.URL
fun main() = singleWindowApplication {
val density = LocalDensity.current
Column {
if (File("src\\main\\resources\\sample.png").isFile){
AsyncImage(
load = { loadImageBitmap(File("src\\main\\resources\\sample.png")) },
painterFor = { remember { BitmapPainter(it) } },
contentDescription = "Sample",
modifier = Modifier.width(200.dp)
)
AsyncImage(
load = { loadSvgPainter("https://github.com/JetBrains/compose-multiplatform/raw/master/artwork/idea-logo.svg", density) },
painterFor = { it },
contentDescription = "Idea logo",
contentScale = ContentScale.FillWidth,
modifier = Modifier.width(200.dp)
)
AsyncImage(
load = { loadXmlImageVector(File("src\\main\\resources\\compose-logo.xml"), density) },
painterFor = { rememberVectorPainter(it) },
contentDescription = "Compose logo",
contentScale = ContentScale.FillWidth,
modifier = Modifier.width(200.dp)
)
}
}
}
@Composable
fun <T> AsyncImage(
load: suspend () -> T,
painterFor: @Composable (T) -> Painter,
contentDescription: String,
modifier: Modifier = Modifier,
contentScale: ContentScale = ContentScale.Fit,
) {
val image: T? by produceState<T?>(null) {
value = withContext(Dispatchers.IO) {
try {
load()
} catch (e: IOException) {
// instead of printing to console, you can also write this to log,
// or show some error placeholder
e.printStackTrace()
null
}
}
}
if (image != null) {
Image(
painter = painterFor(image!!),
contentDescription = contentDescription,
contentScale = contentScale,
modifier = modifier
)
}
}
/* Loading from file with java.io API */
fun loadImageBitmap(file: File): ImageBitmap =
file.inputStream().buffered().use(::loadImageBitmap)
fun loadSvgPainter(file: File, density: Density): Painter =
file.inputStream().buffered().use { loadSvgPainter(it, density) }
fun loadXmlImageVector(file: File, density: Density): ImageVector =
file.inputStream().buffered().use { loadXmlImageVector(InputSource(it), density) }
/* Loading from network with java.net API */
fun loadImageBitmap(url: String): ImageBitmap =
URL(url).openStream().buffered().use(::loadImageBitmap)
fun loadSvgPainter(url: String, density: Density): Painter =
URL(url).openStream().buffered().use { loadSvgPainter(it, density) }
fun loadXmlImageVector(url: String, density: Density): ImageVector =
URL(url).openStream().buffered().use { loadXmlImageVector(InputSource(it), density) } | EjerciciosCompose1/src/main/kotlin/Tutoriales/Tutorial02ImagesAndIcon.kt | 2166779656 |
package Tutoriales
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import androidx.compose.ui.window.rememberWindowState
fun main() = application {
Window(
onCloseRequest = ::exitApplication,
title = "Compose for Desktop",
state = rememberWindowState(width = 300.dp, height = 300.dp)
) {
val count = remember { mutableStateOf(0) }
MaterialTheme {
Column(Modifier.fillMaxSize(), Arrangement.spacedBy(5.dp)) {
Button(modifier = Modifier.align(Alignment.CenterHorizontally),
onClick = {
count.value++
}) {
Text(if (count.value == 0) "Hello World" else "Clicked ${count.value}!")
}
Button(modifier = Modifier.align(Alignment.CenterHorizontally),
onClick = {
count.value = 0
}) {
Text("Reset")
}
}
}
}
} | EjerciciosCompose1/src/main/kotlin/Tutoriales/Tutorial01GettingStarted.kt | 3436273517 |
import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import androidx.compose.ui.window.rememberWindowState
@Composable
@Preview
fun MainScreen3() {
Surface(
color = Color.LightGray,
modifier = Modifier.fillMaxSize()
) {
StudentList()
}
}
@Composable
fun StudentList() {
val students = remember{mutableStateListOf("Juan", "Victor", "Esther", "Jaime")}
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
for (student in students) {
StudentText(name = student)
}
Button(
onClick = { students.add("Manueh") },
) {
Text(text = "Add new student")
}
}
}
@Composable
fun StudentText(name: String) {
Text(
text = name,
style = MaterialTheme.typography.h5,
modifier = Modifier.padding(10.dp)
)
}
fun main() = application {
val windowState = rememberWindowState(size = DpSize(1200.dp,800.dp))
Window(
onCloseRequest = ::exitApplication,
title = "Lista de estudiantes",
state = windowState
){
MainScreen3()
}
} | EjerciciosCompose1/src/main/kotlin/EjemploState.kt | 1564864017 |
import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.rememberWindowState
@Composable
@Preview
fun MainScreen() {
Surface(
color = Color.Yellow,
modifier = Modifier.fillMaxSize()
) {
Surface(
color = Color.Magenta,
modifier = Modifier.wrapContentSize(Alignment.Center)
) {
Text(
text = "Hola caracola!!",
style = MaterialTheme.typography.h5,
modifier = Modifier.padding(20.dp)
)
}
}
}
fun main() = application {
val windowState = rememberWindowState(size = DpSize(1200.dp,800.dp))
Window(
onCloseRequest = ::exitApplication,
title = "Ejemplos para practicar",
state = windowState
){
LoginScreen()
}
}
| EjerciciosCompose1/src/main/kotlin/Main.kt | 4071494951 |
package EjerciciosIniciales
import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import androidx.compose.ui.window.rememberWindowState
@Composable
@Preview
fun Ejercicio4() {
Row(
modifier = Modifier.fillMaxSize(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.Bottom
) {
Subrow1(color = Color.Red)
Spacer(modifier = Modifier.width(20.dp))
Subrow2(color = Color.Blue)
Spacer(modifier = Modifier.width(20.dp))
Subrow3(color = Color.Red)
Spacer(modifier = Modifier.width(20.dp))
Subrow4(color = Color.Blue)
}
}
@Composable
fun Subrow1(color: Color) {
Box(
modifier = Modifier
.width(100.dp)
.height(400.dp)
.border(2.dp, color = color),
contentAlignment = Alignment.TopCenter
) {
Text(text = "Ejemplo1")
}
}
@Composable
fun Subrow2(color: Color) {
Box(
modifier = Modifier
.width(100.dp)
.height(250.dp)
.border(2.dp, color = color),
contentAlignment = Alignment.TopCenter
) {
Text(text = "Ejemplo2")
}
}
@Composable
fun Subrow3(color: Color) {
Box(
modifier = Modifier
.width(100.dp)
.height(125.dp)
.border(2.dp, color = color),
contentAlignment = Alignment.TopCenter
) {
Text(text = "Ejemplo3")
}
}
@Composable
fun Subrow4(color: Color) {
Box(
modifier = Modifier
.width(100.dp)
.height(25.dp)
.border(2.dp, color = color),
contentAlignment = Alignment.TopCenter
) {
Text(text = "Ejemplo4")
}
}
fun main() = application {
val windowState = rememberWindowState(size = DpSize(500.dp,800.dp))
Window(
onCloseRequest = ::exitApplication,
title = "Ejercicio 4 Compose",
state = windowState
){
Ejercicio4()
}
} | EjerciciosCompose1/src/main/kotlin/EjerciciosIniciales/Ejercicio4.kt | 2030325991 |
package EjerciciosIniciales
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import androidx.compose.ui.window.rememberWindowState
@Composable
fun Ejercicio5() {
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Box(
modifier = Modifier
.width(1000.dp)
.height(150.dp)
.background(Color.Cyan )
) {
Text(
text = "BOX 1",
style = MaterialTheme.typography.h3,
modifier = Modifier.align(Alignment.Center)
)
}
Spacer(modifier = Modifier.height(50.dp))
Box(
modifier = Modifier
.width(1000.dp)
.height(150.dp)
.background(Color.Gray)
) {
Text(
text = "BOX 2",
style = MaterialTheme.typography.h3,
modifier = Modifier.align(Alignment.Center)
)
}
Spacer(modifier = Modifier.height(80.dp))
Box(
modifier = Modifier
.width(1000.dp)
.height(150.dp)
.background(Color.Green)
) {
Text(
text = "BOX 3",
style = MaterialTheme.typography.h3,
modifier = Modifier.align(Alignment.Center)
)
}
Spacer(modifier = Modifier.height(20.dp))
Box(
modifier = Modifier
.width(1000.dp)
.height(150.dp)
.background(Color.Magenta)
) {
Text(
text = "BOX 4",
style = MaterialTheme.typography.h3,
modifier = Modifier.align(Alignment.Center)
)
}
}
}
fun main() = application {
val windowState = rememberWindowState(size = DpSize(500.dp,800.dp))
Window(
onCloseRequest = ::exitApplication,
title = "Ejercicio 5 Compose",
state = windowState
){
Ejercicio5()
}
} | EjerciciosCompose1/src/main/kotlin/EjerciciosIniciales/Ejercicio5.kt | 2958879773 |
package EjerciciosIniciales
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import androidx.compose.ui.window.rememberWindowState
@Composable
fun Ejercicio1(){
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.White)
){
Box(
modifier = Modifier
.width(50.dp)
.height(50.dp)
.background(Color.Cyan)
.align(Alignment.Center)
)
}
}
fun main() = application {
val windowState = rememberWindowState(size = DpSize(500.dp,800.dp))
Window(
onCloseRequest = ::exitApplication,
title = "Ejercicio 1 Compose",
state = windowState
){
Ejercicio1()
}
} | EjerciciosCompose1/src/main/kotlin/EjerciciosIniciales/Ejercicio1.kt | 3396021301 |
package EjerciciosIniciales
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import androidx.compose.ui.window.rememberWindowState
@Composable
fun Ejercicio2(){
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.White)
){
Box(
modifier = Modifier
.width(325.dp)
.height(200.dp)
.background(Color.Cyan)
.align(Alignment.Center)
){
Text(
text = "Esto es un EJEMPLO del uso de Box",
style = MaterialTheme.typography.h6,
modifier = Modifier.align(Alignment.BottomCenter)
)
}
}
}
fun main() = application {
val windowState = rememberWindowState(size = DpSize(500.dp,800.dp))
Window(
onCloseRequest = ::exitApplication,
title = "Ejercicio 2 Compose",
state = windowState
){
Ejercicio2()
}
} | EjerciciosCompose1/src/main/kotlin/EjerciciosIniciales/Ejercicio2.kt | 907342703 |
package EjerciciosIniciales
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import androidx.compose.ui.window.rememberWindowState
@Composable
fun Ejercicio3() {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Top,
horizontalAlignment = Alignment.CenterHorizontally
) {
Subcolumna1(color = Color.Red)
Subcolumna2(color = Color.Gray)
Subcolumna3(color = Color.Cyan)
Subcolumna4(color = Color.Green)
}
}
@Composable
fun Subcolumna1(color: Color) {
Box(
modifier = Modifier
.width(100.dp)
.height(150.dp)
.background(color),
contentAlignment = Alignment.TopCenter
){
Text("Ejemplo1")
}
}
@Composable
fun Subcolumna2(color: Color) {
Box(
modifier = Modifier
.width(100.dp)
.height(250.dp)
.background(color),
contentAlignment = Alignment.TopCenter
){
Text("Ejemplo2")
}
}
@Composable
fun Subcolumna3(color: Color) {
Box(
modifier = Modifier
.width(100.dp)
.height(250.dp)
.background(color),
contentAlignment = Alignment.TopCenter
){
Text("Ejemplo3")
}
}
@Composable
fun Subcolumna4(color: Color) {
Box(
modifier = Modifier
.width(100.dp)
.height(150.dp)
.background(color),
contentAlignment = Alignment.TopCenter
){
Text("Ejemplo4")
}
}
fun main() = application {
val windowState = rememberWindowState(size = DpSize(500.dp,800.dp))
Window(
onCloseRequest = ::exitApplication,
title = "Ejercicio 3 Compose",
state = windowState
){
Ejercicio3()
}
} | EjerciciosCompose1/src/main/kotlin/EjerciciosIniciales/Ejercicio3.kt | 4138103475 |
import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
@Composable
@Preview
fun LoginScreen() {
var user by remember { mutableStateOf("") }
var password by remember { mutableStateOf("") }
val buttonEnabled = user.isNotBlank() && password.isNotBlank()
MaterialTheme {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(10.dp, alignment = Alignment.CenterVertically),
modifier = Modifier.fillMaxSize()
) {
Usuario(user){ user = it }
Password(password){ password = it }
Button(
onClick = {
user = ""
password = ""
},
enabled = buttonEnabled
) {
Text(text = "Login")
}
}
}
}
@Composable
fun Usuario(user:String, onUserChange:(String)-> Unit){
OutlinedTextField(
value = user,
label = { Text(text = "Nombre del usuario")},
onValueChange = onUserChange
)
}
@Composable
fun Password(password:String, onPasswordChange:(String)-> Unit){
var passVisible by remember { mutableStateOf(false) }
OutlinedTextField(
value = password,
onValueChange = onPasswordChange,
label = { Text("Contraseña") },
visualTransformation = if (passVisible) VisualTransformation.None else PasswordVisualTransformation(),
trailingIcon = {
IconToggleButton(
checked = passVisible,
onCheckedChange = { passVisible = it }
) {
Icon(
imageVector = if (passVisible) Icons.Default.VisibilityOff else Icons.Default.Visibility,
contentDescription = null
)
}
}
)
}
fun Boton(){} | EjerciciosCompose1/src/main/kotlin/LoginCompose.kt | 4266851419 |
package com.example.musichub
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.musichub", appContext.packageName)
}
} | Music-hub/app/src/androidTest/java/com/example/musichub/ExampleInstrumentedTest.kt | 976942740 |
package com.example.musichub
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | Music-hub/app/src/test/java/com/example/musichub/ExampleUnitTest.kt | 3353623945 |
package com.example.musichub
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.musichub.adapter.CategoryAdapter
import com.example.musichub.databinding.ActivityMainBinding
import com.example.musichub.models.CategoryModel
import com.google.firebase.firestore.FirebaseFirestore
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
lateinit var categoryAdapter: CategoryAdapter
override fun onCreate(savedInstanceState: Bundle?) {
binding= ActivityMainBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding.root)
getCategories()
}
fun getCategories(){
FirebaseFirestore.getInstance().collection("category")
.get().addOnSuccessListener{
val categoryList=it.toObjects(CategoryModel::class.java)
setupCategoryRecyclerView(categoryList)
}
}
private fun setupCategoryRecyclerView(categoryList: List<CategoryModel>) {
categoryAdapter= CategoryAdapter(categoryList)
binding.categoriesRecyclerview.layoutManager=LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false)
binding.categoriesRecyclerview.adapter=categoryAdapter
}
} | Music-hub/app/src/main/java/com/example/musichub/MainActivity.kt | 2584178108 |
package com.example.musichub
import android.content.Context
import androidx.media3.common.MediaItem
import androidx.media3.exoplayer.ExoPlayer
import com.example.musichub.models.songModel
object MexoPlayer {
private var exoPlayer:ExoPlayer?=null
private var currentSong:songModel?=null
fun getCurrentSong():songModel?{
return currentSong
}
fun getInstance():ExoPlayer?{
return exoPlayer
}
fun startPlaying(context: Context,song:songModel){
if (exoPlayer==null)
exoPlayer=ExoPlayer.Builder(context).build()
if(currentSong!=song){
currentSong=song
currentSong?.url?.apply {
val madiaItem=MediaItem.fromUri(this)
exoPlayer?.setMediaItem(madiaItem)
exoPlayer?.prepare()
exoPlayer?.play()
}
}
}
} | Music-hub/app/src/main/java/com/example/musichub/MexoPlayer.kt | 3984978810 |
package com.example.musichub
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import com.bumptech.glide.Glide
import com.example.musichub.databinding.ActivityPlayerBinding
class playerActivity : AppCompatActivity() {
lateinit var binding: ActivityPlayerBinding
lateinit var exoPlayer: ExoPlayer
var playerListener=object :Player.Listener{
override fun onIsPlayingChanged(isPlaying: Boolean) {
super.onIsPlayingChanged(isPlaying)
showGif(isPlaying)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding= ActivityPlayerBinding.inflate(layoutInflater)
setContentView(binding.root)
MexoPlayer.getCurrentSong()?.apply {
binding.songTitleTextView.text=title
binding.songSubtitleTetView.text=subtitle
Glide.with(binding.songCoverImgView).load(coverurl)
.circleCrop()
.into(binding.songCoverImgView)
Glide.with(binding.songGifImgView).load(R.drawable.giphy)
.circleCrop()
.into(binding.songGifImgView)
exoPlayer=MexoPlayer.getInstance()!!
binding.playerView.player=exoPlayer
binding.playerView.showController()
exoPlayer.addListener(playerListener)
}
}
override fun onDestroy() {
super.onDestroy()
exoPlayer?.removeListener(playerListener)
}
fun showGif(show:Boolean){
if (show){
binding.songGifImgView.visibility=View.VISIBLE
}else{
binding.songGifImgView.visibility=View.INVISIBLE
}
}
} | Music-hub/app/src/main/java/com/example/musichub/playerActivity.kt | 3926967996 |
package com.example.musichub.models
data class CategoryModel(
val name:String,
val coverUrl:String,
val songs:List<String>
) {
constructor() : this("","", listOf())
}
| Music-hub/app/src/main/java/com/example/musichub/models/CategoryModel.kt | 175044363 |
package com.example.musichub.models
import android.icu.text.CaseMap.Title
data class songModel(
val id:String,
val title: String,
val subtitle:String,
val url:String,
val coverurl:String
)
{
constructor():this("","","","","")
}
| Music-hub/app/src/main/java/com/example/musichub/models/songModel.kt | 288781619 |
package com.example.musichub.adapter
import android.annotation.SuppressLint
import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.example.musichub.MexoPlayer
import com.example.musichub.databinding.SongListItemRecyclerRowBinding
import com.example.musichub.models.songModel
import com.example.musichub.playerActivity
import com.google.firebase.firestore.FirebaseFirestore
class Songs_list_adapter(private val songIdList:List<String>):
RecyclerView.Adapter<Songs_list_adapter.MyViewHolder>() {
class MyViewHolder(private var binding:SongListItemRecyclerRowBinding):
RecyclerView.ViewHolder(binding.root){
@SuppressLint("SuspiciousIndentation")
fun bindData(songId:String){
FirebaseFirestore.getInstance().collection("songs")
.document(songId).get()
.addOnSuccessListener {
val song=it.toObject(songModel::class.java)
song?.apply {
binding.songTitleTextView.text=song.title
binding.songSubtitleTetView.text=song.subtitle
Glide.with(binding.songCoverImgView).load(coverurl).apply(
RequestOptions().transform(RoundedCorners(32))
).into(binding.songCoverImgView)
binding.root.setOnClickListener {
MexoPlayer.startPlaying(binding.root.context,song)
it.context.startActivity(Intent(it.context,playerActivity::class.java))
}
}
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val binding=SongListItemRecyclerRowBinding.inflate(LayoutInflater.from(parent.context),parent,false)
return MyViewHolder(binding)
}
override fun getItemCount(): Int {
return songIdList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bindData(songIdList[position])
}
} | Music-hub/app/src/main/java/com/example/musichub/adapter/Songs_list_adapter.kt | 2745658008 |
package com.example.musichub.adapter
import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.view.RoundedCorner
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.example.musichub.R
import com.example.musichub.databinding.CategoryItemRecyclerRowBinding
import com.example.musichub.models.CategoryModel
import com.example.musichub.songsListActivity
class CategoryAdapter(private val categoryList:List<CategoryModel>):
RecyclerView.Adapter<CategoryAdapter.MyViewHolder>() {
class MyViewHolder(private val binding: CategoryItemRecyclerRowBinding) :
RecyclerView.ViewHolder(binding.root){
fun bindData(category:CategoryModel){
binding.nameTv.text=category.name
Glide.with(binding.coverImgView).load(category.coverUrl)
.apply {
RequestOptions().transform(RoundedCorners(42))
}
.into(binding.coverImgView)
Log.i("songs",category.songs.size.toString())
//start song list activity
val context=binding.root.context
binding.root.setOnClickListener {
songsListActivity.category=category
context.startActivity(Intent(context,songsListActivity::class.java))
}
}
}
//here binding . root means the views of CategoryItemRecyclerRowBinding.xml layout
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val binding=CategoryItemRecyclerRowBinding.inflate(LayoutInflater.from(parent.context),parent,false)
return MyViewHolder(binding)
}
override fun getItemCount(): Int {
return categoryList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bindData(categoryList[position])
}
} | Music-hub/app/src/main/java/com/example/musichub/adapter/CategoryAdapter.kt | 4009966497 |
package com.example.musichub
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.example.musichub.adapter.Songs_list_adapter
import com.example.musichub.databinding.ActivityMainBinding
import com.example.musichub.databinding.ActivitySongsListBinding
import com.example.musichub.models.CategoryModel
class songsListActivity : AppCompatActivity() {
lateinit var binding: ActivitySongsListBinding
lateinit var songsListAdapter: Songs_list_adapter
companion object{
lateinit var category: CategoryModel
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding= ActivitySongsListBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.nameTv.text= category.name
Glide.with(binding.coverImgView).load(category.coverUrl)
.apply {
RequestOptions().transform(RoundedCorners(32))
}
.into(binding.coverImgView)
setUpSongListRecyclerView()
}
fun setUpSongListRecyclerView(){
songsListAdapter= Songs_list_adapter(category.songs)
binding.songListRecyclerView.layoutManager=LinearLayoutManager(this)
binding.songListRecyclerView.adapter=songsListAdapter
}
} | Music-hub/app/src/main/java/com/example/musichub/songsListActivity.kt | 3606322303 |
data class Product(
val name: String,
val price: Int) | lesson3.2ispravlen/src/main/kotlin/Product.kt | 1792604006 |
interface Buyable {
fun buy(productId: Int, buyer: User)
} | lesson3.2ispravlen/src/main/kotlin/Buyable.kt | 3506895080 |
import java.util.*
fun main(args: Array<String>) {
val store = Store()
val user = User("Erjan", "Kara-Balta").apply {
balance += 1000
}
val scanner = Scanner(System.`in`)
with(store) {
store.displayProducts()
print("Введите ID товара, который вы хотите купить: ")
val productId = scanner.nextInt()
store.buy(productId, user)
printProductNames()
}
with(user) {
println("Баланс пользователя после покупки: $balance рублей")
}
}
| lesson3.2ispravlen/src/main/kotlin/Main.kt | 3210073958 |
class Store: Buyable {
private val products = mutableMapOf<Int, Product>()
init {
addProduct(1, Product("Товар 1", 100))
addProduct(2, Product("Товар 2", 150))
addProduct(3, Product("Товар 3", 200))
}
private fun addProduct(id: Int, product: Product) {
products[id] = product
}
override fun buy(productId: Int, buyer: User) {
when (productId) {
1, 2, 3 -> {
val product = products[productId]
product?.apply {
val amount = price
println("Покупатель: ${buyer.name}")
println("Товар: $name")
println("Стоимость товара: $amount рублей")
println("Адрес доставки: ${buyer.address}")
buyer.balance -= amount
println("Списано с баланса: $amount рублей")
buyer.also {
println("Оставшийся баланс: ${it.balance} рублей")
}
}
}
else -> println("Вы ввели неверный id товара")
}
}
fun printProductNames() {
println("Названия товаров в магазине:")
products.values.forEach { product ->
println(product.name)
}
}
fun displayProducts() {
println("Товары в магазине:")
for ((id, product) in products) {
println("ID: $id, Название: ${product.name}, Цена: ${product.price}")
}
}
} | lesson3.2ispravlen/src/main/kotlin/Store.kt | 2088769897 |
data class User(
val name: String,
val address: String) {
var balance: Int = 0
set(value) {
if (value in 0..100000) {
field = value
} else {
throw IllegalArgumentException("За раз можно пополнить баланс только на сумму не выше 100000")
}
}
get() = field
} | lesson3.2ispravlen/src/main/kotlin/User.kt | 2331133221 |
package net.fukumaisaba.moneygive.listener
import net.fukumaisaba.moneygive.MoneyGive
import net.fukumaisaba.moneygive.util.message.ConfigMessage
import net.fukumaisaba.moneygive.util.message.ConfigMessageType
import org.bukkit.Bukkit
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerJoinEvent
import kotlin.math.ceil
class PlayerJoinListener: Listener {
private val plugin = MoneyGive.plugin
private val message = MoneyGive.message
@EventHandler
fun onPlayerJoin(event: PlayerJoinEvent) {
val api = MoneyGive.api
val vaultHook = MoneyGive.vaultHook
val player = event.player
val nowGiveAmount = api.getGiveBalance(player)
if (nowGiveAmount > 0.0) {
api.deletePlayerData(player)
Bukkit.getScheduler().runTaskLater(plugin, Runnable {
vaultHook.depositPlayer(player, nowGiveAmount)
// 演出
val replaceTexts = HashMap<String, String>()
replaceTexts["%player%"] = player.name
replaceTexts["%money%"] = message.formatMoney(nowGiveAmount).toString()
replaceTexts["%moneyUnit%"] = ConfigMessage().getMessage(ConfigMessageType.MONEY_UNIT)
message.sendMessage(player, true,
message.getReplaced(ConfigMessage().getMessage(ConfigMessageType.MONEY_GET_OFFLINE), replaceTexts))
}, plugin.config.getLong("config.giveMoneyWaitTick", 20L))
}
}
} | MoneyGive/src/main/java/net/fukumaisaba/moneygive/listener/PlayerJoinListener.kt | 4257408757 |
package net.fukumaisaba.moneygive.listener
import net.fukumaisaba.moneygive.MoneyGive
import net.fukumaisaba.moneygive.util.VaultHook
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.server.PluginEnableEvent
class HookPluginListener(
private val listenerHandler: ListenerHandler,
private val instance: MoneyGive,
): Listener {
@EventHandler
fun onPluginEnable(event: PluginEnableEvent) {
val moneyGivePlugin = MoneyGive.plugin
val plugin = event.plugin
var isHook = false
when (plugin.name) {
"iConomy" -> {
moneyGivePlugin.logger.info("iConomyと連携しました!")
listenerHandler.registerIConomyListeners()
isHook = true
}
}
if (isHook) instance.setVaultHook(VaultHook())
}
} | MoneyGive/src/main/java/net/fukumaisaba/moneygive/listener/HookPluginListener.kt | 858574682 |
package net.fukumaisaba.moneygive.listener.moneyGive
import net.fukumaisaba.moneygive.MoneyGive
import net.fukumaisaba.moneygive.api.event.EconomyTransactionEvent
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
class EconomyTransactionListener: Listener {
@EventHandler
fun onEconomyTransaction(event: EconomyTransactionEvent) {
val api = MoneyGive.api
val player = event.player
val amount = event.amount
// (恐らく)Towny系の請求であれば(町や国への請求であれば)スルー
if (player.name?.startsWith("towny-") == true) return
if (player.name?.startsWith("town-") == true) return
if (player.name?.startsWith("nation-") == true) return
// オフラインの場合
if (!player.isOnline) {
event.isCancelled = true
api.addGiveBalance(player, amount)
}
}
} | MoneyGive/src/main/java/net/fukumaisaba/moneygive/listener/moneyGive/EconomyTransactionListener.kt | 2341282496 |
package net.fukumaisaba.moneygive.listener
import net.fukumaisaba.moneygive.MoneyGive
import net.fukumaisaba.moneygive.listener.iConomy5.IConomyTransactionListener
import net.fukumaisaba.moneygive.listener.moneyGive.EconomyTransactionListener
import org.bukkit.event.Listener
import org.bukkit.plugin.Plugin
class ListenerHandler(private val plugin: Plugin, private val instance: MoneyGive) {
val iConomyListeners: MutableList<Listener> = mutableListOf()
fun registerBasicListeners() {
/**
* SpigotAPI
*/
registerListener(PlayerJoinListener())
registerListener(HookPluginListener(this, instance))
/**
* MoneyGive
*/
registerListener(EconomyTransactionListener())
}
fun registerIConomyListeners() {
iConomyListeners.add(IConomyTransactionListener())
registerListeners(iConomyListeners)
}
fun registerListener(listener: Listener) {
plugin.server.pluginManager.registerEvents(listener, plugin)
}
fun registerListeners(listeners: MutableList<Listener>) {
for (listener in listeners) registerListener(listener)
}
} | MoneyGive/src/main/java/net/fukumaisaba/moneygive/listener/ListenerHandler.kt | 3396792793 |
package net.fukumaisaba.moneygive.listener.iConomy5
import com.iConomy.events.AccountUpdateEvent
import net.fukumaisaba.moneygive.MoneyGive
import net.fukumaisaba.moneygive.api.event.EconomyTransactionEvent
import org.bukkit.Bukkit
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
class IConomyTransactionListener: Listener {
private val plugin = MoneyGive.plugin
@EventHandler
fun onAccountUpdate(event: AccountUpdateEvent) {
val player = Bukkit.getOfflinePlayer(event.accountName)
val amount = event.amount
val ecoEvent = EconomyTransactionEvent(player, amount)
plugin.server.pluginManager.callEvent(ecoEvent)
if (ecoEvent.isCancelled) event.isCancelled = true
}
} | MoneyGive/src/main/java/net/fukumaisaba/moneygive/listener/iConomy5/IConomyTransactionListener.kt | 350194784 |
package net.fukumaisaba.moneygive.util
import net.fukumaisaba.moneygive.MoneyGive
import net.milkbowl.vault.economy.Economy
import net.milkbowl.vault.economy.EconomyResponse
import org.bukkit.OfflinePlayer
class VaultHook {
private lateinit var vaultEconomy: Economy
private val plugin = MoneyGive.plugin
init {
setupEconomy()
}
private fun setupEconomy(): Boolean {
if (plugin.server.pluginManager.getPlugin("Vault") == null) {
return false
}
val rsp = plugin.server.servicesManager.getRegistration(
Economy::class.java
) ?: return false
vaultEconomy = rsp.provider
return true
}
fun getBalance(player: OfflinePlayer): Double { return vaultEconomy.getBalance(player) }
fun giveMoney(player: OfflinePlayer, amount: Double): EconomyResponse {
if (amount < 0) return withdrawPlayer(player, -amount)
return depositPlayer(player, amount)
}
fun depositPlayer(player: OfflinePlayer, amount: Double): EconomyResponse {
return vaultEconomy.depositPlayer(player, amount)
}
fun withdrawPlayer(player: OfflinePlayer, amount: Double): EconomyResponse {
return vaultEconomy.withdrawPlayer(player, amount)
}
} | MoneyGive/src/main/java/net/fukumaisaba/moneygive/util/VaultHook.kt | 3847952217 |
package net.fukumaisaba.moneygive.util.message
enum class ConfigMessageType {
MONEY_UNIT,
MONEY_GIVE_SUCCESS,
MONEY_GET,
MONEY_GET_OFFLINE,
} | MoneyGive/src/main/java/net/fukumaisaba/moneygive/util/message/ConfigMessageType.kt | 1448861720 |
package net.fukumaisaba.moneygive.util.message
import net.fukumaisaba.moneygive.MoneyGive
class ConfigMessage {
private val plugin = MoneyGive.plugin
private val message = MoneyGive.message
private val config = plugin.config
fun getMessage(type: ConfigMessageType): String {
return message.getColored(config.getString("messages.${type.name}", "")!!)
}
} | MoneyGive/src/main/java/net/fukumaisaba/moneygive/util/message/ConfigMessage.kt | 2607747945 |
package net.fukumaisaba.moneygive.util.message
import org.bukkit.ChatColor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
import kotlin.math.ceil
class Message {
var prefix = getColored("&6[MoneyGive]&f")
set(newPrefix) {
field = getColored("${newPrefix}&f")
}
fun getColored(string: String): String {
return ChatColor.translateAlternateColorCodes('&', string)
}
fun getReplaced(string: String, replaceTexts: HashMap<String, String>): String {
var replacedText = string
replaceTexts.forEach { (key, value) ->
replacedText = replacedText.replace(key, value)
}
return replacedText
}
fun formatMoney(amount: Double): Double {
return (ceil(amount *1000.0) / 1000.0)
}
fun sendMessage(sender: CommandSender, needPrefix: Boolean, msg: String) {
var prefix_ = ""
if (needPrefix) prefix_ = "$prefix "
sender.sendMessage(getColored("${prefix_}${msg}"))
}
fun sendMessage(player: Player, needPrefix: Boolean, msg: String) {
var prefix_ = ""
if (needPrefix) prefix_ = "$prefix "
player.sendMessage(getColored("${prefix_}${msg}"))
}
} | MoneyGive/src/main/java/net/fukumaisaba/moneygive/util/message/Message.kt | 2760352348 |
package net.fukumaisaba.moneygive.util
import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import net.fukumaisaba.moneygive.MoneyGive
import java.io.File
import java.sql.SQLException
import java.util.UUID
class DatabaseHelper {
private var hikari: HikariDataSource? = null
private val plugin = MoneyGive.plugin
private val userDataTableName = "mg_userdata"
init {
// 設定など
val dbPath = "${plugin.dataFolder.path}/sqlite.db"
File(dbPath).parentFile.mkdirs()
val config = HikariConfig()
config.driverClassName = "org.sqlite.JDBC"
config.jdbcUrl = "jdbc:sqlite:$dbPath"
config.maximumPoolSize = 50
config.connectionInitSql = "SELECT 1"
// 接続
hikari = HikariDataSource(config)
// テーブル作成
createTable()
}
private fun createTable() {
try {
val con = hikari!!.connection
val prestate = con.prepareStatement("CREATE TABLE IF NOT EXISTS `${userDataTableName}` (`id` INTEGER NOT NULL, `uuid` VARCHAR(100) NOT NULL DEFAULT '', `amount` DOUBLE DEFAULT 0.0, `updated_at` TIMESTAMP DEFAULT(DATETIME('now', 'localtime')), PRIMARY KEY (`id`));")
prestate.executeUpdate()
con.close()
prestate.close()
}catch (e: SQLException) {
e.printStackTrace()
}
}
private fun getPlayerData(uuid: UUID): PlayerData? {
try {
val con = hikari!!.connection
val prestate = con.prepareStatement("SELECT * FROM `$userDataTableName` WHERE uuid = ?")
prestate.setString(1, uuid.toString())
val result = prestate.executeQuery()
val playerData = PlayerData(
result.next(),
result.getInt("id"),
uuid,
result.getDouble("amount"),
result.getTimestamp("updated_at")
)
con.close()
result.close()
return playerData
} catch (e: SQLException) {
e.printStackTrace()
}
return null
}
fun deletePlayerData(uuid: UUID) {
try {
val con = hikari!!.connection
val prestate = con.prepareStatement("DELETE FROM `$userDataTableName` WHERE uuid = ?")
prestate.setString(1, uuid.toString())
prestate.executeUpdate()
con.close()
prestate.close()
}catch (e: SQLException) {
e.printStackTrace()
}
}
fun getPlayerGiveMoney(uuid: UUID): Double {
val playerData = getPlayerData(uuid) ?: return 0.0
return if (playerData.exists) {
playerData.amount
}else 0.0
}
fun setPlayerGiveMoney(uuid: UUID, amount: Double) {
try {
val playerData = getPlayerData(uuid)
val con = hikari!!.connection
if (playerData!!.exists) {
val prestate = con.prepareStatement("UPDATE `$userDataTableName` SET `amount` = ? WHERE `uuid` = ?")
prestate.setDouble(1, amount)
prestate.setString(2, uuid.toString())
prestate.executeUpdate()
prestate.close()
}else {
val prestate = con.prepareStatement("INSERT INTO `$userDataTableName` (`uuid`, `amount`) VALUES (?, ?)")
prestate.setString(1, uuid.toString())
prestate.setDouble(2, amount)
prestate.executeUpdate()
prestate.close()
}
con.close()
}catch (e: SQLException) {
e.printStackTrace()
}
}
fun depositPlayer(uuid: UUID, amount: Double) {
// 現段階での付与予定の金額
val nowGiveMoney = getPlayerGiveMoney(uuid)
// 設定
setPlayerGiveMoney(uuid, nowGiveMoney + amount)
}
fun withdrawPlayer(uuid: UUID, amount: Double) {
// 現段階での付与予定の金額
val nowGiveMoney = getPlayerGiveMoney(uuid)
// 設定
setPlayerGiveMoney(uuid, nowGiveMoney - amount)
}
} | MoneyGive/src/main/java/net/fukumaisaba/moneygive/util/DatabaseHelper.kt | 3961305453 |
package net.fukumaisaba.moneygive.util
import java.sql.Timestamp
import java.util.UUID
class PlayerData(
val exists: Boolean,
val id: Int?,
val uuid: UUID,
var amount: Double,
var updatedAt: Timestamp?,
) {
} | MoneyGive/src/main/java/net/fukumaisaba/moneygive/util/PlayerData.kt | 925627048 |
package net.fukumaisaba.moneygive.api
import net.fukumaisaba.moneygive.util.DatabaseHelper
import org.bukkit.OfflinePlayer
class MoneyGiveApiImpl(private val dbHelper: DatabaseHelper): MoneyGiveApi {
override fun getGiveBalance(player: OfflinePlayer): Double {
return dbHelper.getPlayerGiveMoney(player.uniqueId)
}
override fun setGiveBalance(player: OfflinePlayer, amount: Double) {
dbHelper.setPlayerGiveMoney(player.uniqueId, amount)
}
override fun addGiveBalance(player: OfflinePlayer, amount: Double) {
val nowGiveBalance = getGiveBalance(player)
setGiveBalance(player, (nowGiveBalance + amount))
}
override fun depositPlayer(player: OfflinePlayer, amount: Double) {
dbHelper.depositPlayer(player.uniqueId, amount)
}
override fun withdrawPlayer(player: OfflinePlayer, amount: Double) {
dbHelper.withdrawPlayer(player.uniqueId, amount)
}
override fun deletePlayerData(player: OfflinePlayer) {
dbHelper.deletePlayerData(player.uniqueId)
}
} | MoneyGive/src/main/java/net/fukumaisaba/moneygive/api/MoneyGiveApiImpl.kt | 2091005845 |
package net.fukumaisaba.moneygive.api
import org.bukkit.OfflinePlayer
interface MoneyGiveApi {
fun getGiveBalance(player: OfflinePlayer): Double
fun setGiveBalance(player: OfflinePlayer, amount: Double)
fun addGiveBalance(player: OfflinePlayer, amount: Double)
fun depositPlayer(player: OfflinePlayer, amount: Double)
fun withdrawPlayer(player: OfflinePlayer, amount: Double)
fun deletePlayerData(player: OfflinePlayer)
} | MoneyGive/src/main/java/net/fukumaisaba/moneygive/api/MoneyGiveApi.kt | 130265327 |
package net.fukumaisaba.moneygive.api.event
import org.bukkit.OfflinePlayer
import org.bukkit.event.Event
import org.bukkit.event.HandlerList
class EconomyTransactionEvent(
val player: OfflinePlayer,
val amount: Double,
): Event() {
companion object {
private val handlers = HandlerList()
@JvmStatic
fun getHandlerList(): HandlerList { return handlers }
}
override fun getHandlers(): HandlerList { return getHandlerList() }
var isCancelled: Boolean = false
} | MoneyGive/src/main/java/net/fukumaisaba/moneygive/api/event/EconomyTransactionEvent.kt | 4270013216 |
package net.fukumaisaba.moneygive.command
import dev.jorel.commandapi.CommandAPICommand
import dev.jorel.commandapi.executors.CommandExecutor
import net.fukumaisaba.moneygive.MoneyGive
import net.fukumaisaba.moneygive.util.message.Message
class MoneyGiveReloadCommand {
private val message = MoneyGive.message
fun register() {
CommandAPICommand("moneygivereload")
.withPermission("moneygive.commands.reload")
.executes(CommandExecutor { sender, _ ->
MoneyGive.reload()
message.sendMessage(sender, true, "&a設定を再読込しました!")
})
.register()
}
} | MoneyGive/src/main/java/net/fukumaisaba/moneygive/command/MoneyGiveReloadCommand.kt | 2308044328 |
package net.fukumaisaba.moneygive.command
import dev.jorel.commandapi.CommandAPICommand
import dev.jorel.commandapi.arguments.DoubleArgument
import dev.jorel.commandapi.arguments.OfflinePlayerArgument
import dev.jorel.commandapi.executors.CommandExecutor
import net.fukumaisaba.moneygive.MoneyGive
import net.fukumaisaba.moneygive.util.DatabaseHelper
import net.fukumaisaba.moneygive.util.message.ConfigMessage
import net.fukumaisaba.moneygive.util.message.ConfigMessageType
import org.bukkit.OfflinePlayer
class MoneyGiveCommand {
private val vaultHook = MoneyGive.vaultHook
private val message = MoneyGive.message
private val api = MoneyGive.api
fun register() {
CommandAPICommand("moneygive")
.withPermission("moneygive.commands.moneygive")
.withArguments(OfflinePlayerArgument("player"))
.withArguments(DoubleArgument("amount"))
.executes(CommandExecutor { sender, args ->
val player = args.get(0) as OfflinePlayer // 付与したいプレイヤー
val amount = args.get(1) as Double // 付与したい金額
if (player.name == null) {
message.sendMessage(sender, true, "&cそのプレイヤーは存在しません!")
return@CommandExecutor
}
// 演出
val replaceTexts = HashMap<String, String>()
replaceTexts["%player%"] = player.name!!
replaceTexts["rimitter"] = sender.name
replaceTexts["%money%"] = message.formatMoney(amount).toString()
replaceTexts["%moneyUnit%"] = ConfigMessage().getMessage(ConfigMessageType.MONEY_UNIT)
message.sendMessage(sender, true,
message.getReplaced(ConfigMessage().getMessage(ConfigMessageType.MONEY_GIVE_SUCCESS), replaceTexts))
// プレイヤーがオンラインか
if (player.isOnline) {
vaultHook.depositPlayer(player, amount)
// 演出
message.sendMessage(player.player!!, true,
message.getReplaced(ConfigMessage().getMessage(ConfigMessageType.MONEY_GET), replaceTexts))
}else {
api.depositPlayer(player, amount)
}
})
.register()
}
} | MoneyGive/src/main/java/net/fukumaisaba/moneygive/command/MoneyGiveCommand.kt | 971144023 |
package net.fukumaisaba.moneygive
import dev.jorel.commandapi.CommandAPI
import dev.jorel.commandapi.CommandAPIBukkitConfig
import net.fukumaisaba.moneygive.api.MoneyGiveApi
import net.fukumaisaba.moneygive.api.MoneyGiveApiImpl
import net.fukumaisaba.moneygive.command.MoneyGiveCommand
import net.fukumaisaba.moneygive.command.MoneyGiveReloadCommand
import net.fukumaisaba.moneygive.listener.ListenerHandler
import net.fukumaisaba.moneygive.util.DatabaseHelper
import net.fukumaisaba.moneygive.util.VaultHook
import net.fukumaisaba.moneygive.util.message.Message
import org.bukkit.plugin.Plugin
import org.bukkit.plugin.java.JavaPlugin
import kotlin.system.measureTimeMillis
class MoneyGive : JavaPlugin() {
companion object {
lateinit var plugin: Plugin private set
lateinit var vaultHook: VaultHook private set
lateinit var message: Message private set
lateinit var api: MoneyGiveApi private set
private lateinit var dbHelper: DatabaseHelper
private lateinit var listenerHandler: ListenerHandler
private lateinit var instance: MoneyGive
fun reload() {
plugin.saveDefaultConfig()
plugin.reloadConfig()
message.prefix = plugin.config.getString("messages.PREFIX", "&6[MoneyGive]&f")!!
}
}
override fun onEnable() {
// 起動処理
plugin = this
instance = this
val time = measureTimeMillis {
// 設定ファイル
saveDefaultConfig()
// メッセージ関連
message = Message()
// データベース関連
dbHelper = DatabaseHelper()
// 連携
vaultHook = VaultHook()
// API
api = MoneyGiveApiImpl(dbHelper)
// CommandAPI 連携
CommandAPI.onLoad(CommandAPIBukkitConfig(this))
CommandAPI.onEnable()
// コマンド登録
MoneyGiveCommand().register()
MoneyGiveReloadCommand().register()
// イベントリスナ関係
listenerHandler = ListenerHandler(this, this)
listenerHandler.registerBasicListeners()
hookOtherPlugins()
}
logger.info("MoneyGiveが起動しました (${time}ms)")
}
fun hookOtherPlugins() {
// Vault
if (server.pluginManager.isPluginEnabled("Vault")) {
logger.info("Vaultと連携しました!")
}
// iConomy
if (server.pluginManager.isPluginEnabled("iConomy")) {
logger.info("iConomyと連携しました!")
listenerHandler.registerIConomyListeners()
}
}
fun setVaultHook(newVaultHook: VaultHook) { vaultHook = newVaultHook }
override fun onDisable() {
// 停止処理
}
}
| MoneyGive/src/main/java/net/fukumaisaba/moneygive/MoneyGive.kt | 3753601458 |
package com.jmf.kotlin_opencv
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.jmf.kotlin_opencv", appContext.packageName)
}
} | composercalculadora/app/src/androidTest/java/com/jmf/kotlin_opencv/ExampleInstrumentedTest.kt | 89393738 |
package com.jmf.kotlin_opencv
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | composercalculadora/app/src/test/java/com/jmf/kotlin_opencv/ExampleUnitTest.kt | 3808471039 |
package com.jmf.kotlin_opencv.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val White = Color(0xFFFFFFFF)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | composercalculadora/app/src/main/java/com/jmf/kotlin_opencv/ui/theme/Color.kt | 3550851717 |
package com.jmf.kotlin_opencv.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun KotlinopencvTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | composercalculadora/app/src/main/java/com/jmf/kotlin_opencv/ui/theme/Theme.kt | 1228179626 |
package com.jmf.kotlin_opencv.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | composercalculadora/app/src/main/java/com/jmf/kotlin_opencv/ui/theme/Type.kt | 2762894240 |
@file:OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3Api::class,
ExperimentalMaterial3Api::class
)
package com.jmf.kotlin_opencv
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldColors
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.jmf.kotlin_opencv.ui.theme.KotlinopencvTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
KotlinopencvTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = Color.White
) {
Box {
calculadora()
}
}
}
}
}
}
@Composable
fun calculadora(){
var number1 by rememberSaveable{ mutableStateOf("")}
var number2 by rememberSaveable{ mutableStateOf("")}
var resultado by rememberSaveable{ mutableStateOf(0.0)}
Column {
Row {
Text(text = "Calculadora Prueba 1", textAlign = TextAlign.Center,modifier = Modifier.fillMaxWidth())
}
Row(modifier = Modifier
.padding(horizontal = 5.dp)
.fillMaxWidth()) {
OutlinedTextField(
modifier = Modifier
.weight(1f)
.padding(end = 5.dp),
colors = TextFieldDefaults.textFieldColors(
containerColor = Color.White,
focusedIndicatorColor = Color.Black, // Color of the border when the field is in focus
unfocusedIndicatorColor = Color.Gray,
textColor = Color.Black,
focusedLabelColor = Color.Black, // Color of the border when the field is not in focus
),
keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number),
shape = RoundedCornerShape(8.dp),
value = number1,
onValueChange = { number1 = it },
label = { Text("Numero 1") },
)
OutlinedTextField(
modifier = Modifier
.padding(start = 5.dp)
.weight(1f),
colors = TextFieldDefaults.textFieldColors(
containerColor = Color.White,
focusedIndicatorColor = Color.Black, // Color of the border when the field is in focus
unfocusedIndicatorColor = Color.Gray,
textColor = Color.Black,
focusedLabelColor = Color.Black,
),
keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number),
shape = RoundedCornerShape(8.dp),
value = number2,
onValueChange = { number2 = it },
label = { Text("Numero 2") },
)
}
Row(modifier = Modifier
.padding(horizontal = 5.dp)
.padding(top = 10.dp)
.fillMaxWidth(),horizontalArrangement = Arrangement.SpaceEvenly) {
Button(onClick = { resultado =sumar(number1.toDouble(),number2.toDouble()) }) {
Text("+", fontSize = 30.sp)
}
Button(onClick = { resultado =restar(number1.toDouble(),number2.toDouble()) }) {
Text("-", fontSize = 30.sp)
}
Button(onClick = { resultado =multiplicar(number1.toDouble(),number2.toDouble()) }) {
Text("*", fontSize = 30.sp)
}
Button(onClick = { resultado = dividir(number1.toDouble(),number2.toDouble()) }) {
Text("/", fontSize = 30.sp)
}
}
if(resultado > 0.0){
Text(text = "El resultado es: $resultado", modifier = Modifier.padding(top = 15.dp).padding(horizontal = 10.dp).fillMaxHeight(), style = TextStyle(fontSize = 60.sp))
}
}
}
fun sumar(number: Double,number2: Double): Double{
return number+number2
}
fun restar(number: Double,number2: Double): Double{
return number-number2
}
fun multiplicar(number: Double,number2: Double): Double{
return number*number2
}
fun dividir(number: Double,number2: Double): Double{
return number/number2
}
@Preview(showBackground = true)
@Composable
fun Prew() {
KotlinopencvTheme {
calculadora()
}
} | composercalculadora/app/src/main/java/com/jmf/kotlin_opencv/MainActivity.kt | 41997802 |
package com.github.iwanabethatguy.oxcintellijplugin
import com.intellij.ide.highlighter.XmlFileType
import com.intellij.openapi.components.service
import com.intellij.psi.xml.XmlFile
import com.intellij.testFramework.TestDataPath
import com.intellij.testFramework.fixtures.BasePlatformTestCase
import com.intellij.util.PsiErrorElementUtil
import com.github.iwanabethatguy.oxcintellijplugin.services.MyProjectService
@TestDataPath("\$CONTENT_ROOT/src/test/testData")
class MyPluginTest : BasePlatformTestCase() {
fun testXMLFile() {
val psiFile = myFixture.configureByText(XmlFileType.INSTANCE, "<foo>bar</foo>")
val xmlFile = assertInstanceOf(psiFile, XmlFile::class.java)
assertFalse(PsiErrorElementUtil.hasErrors(project, xmlFile.virtualFile))
assertNotNull(xmlFile.rootTag)
xmlFile.rootTag?.let {
assertEquals("foo", it.name)
assertEquals("bar", it.value.text)
}
}
fun testRename() {
myFixture.testRename("foo.xml", "foo_after.xml", "a2")
}
fun testProjectService() {
val projectService = project.service<MyProjectService>()
assertNotSame(projectService.getRandomNumber(), projectService.getRandomNumber())
}
override fun getTestDataPath() = "src/test/testData/rename"
}
| oxc-intellij-plugin/src/test/kotlin/com/github/iwanabethatguy/oxcintellijplugin/MyPluginTest.kt | 526773993 |
package com.github.iwanabethatguy.oxcintellijplugin.settings
import com.intellij.openapi.options.Configurable
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.Nullable
import javax.swing.JComponent
import javax.swing.JPanel
class OxcSettingsConfigurable: Configurable {
private var settingsComponent: OxcSettingsComponent? = null
// A default constructor with no arguments is required because this implementation
// is registered in an applicationConfigurable EP
@Nls(capitalization = Nls.Capitalization.Title)
override fun getDisplayName(): String {
return "Oxc"
}
@Nullable
override fun createComponent(): JPanel? {
settingsComponent = OxcSettingsComponent()
return settingsComponent!!.getPanel()
}
override fun isModified(): Boolean {
val settings: OxcSettingsState = OxcSettingsState.instance
val modified: Boolean = !settingsComponent!!.getEnable().equals(settings.enable)
return modified
}
override fun apply() {
val settings: OxcSettingsState = OxcSettingsState.instance
settings.enable = settingsComponent!!.getEnable()
}
override fun reset() {
val settings: OxcSettingsState = OxcSettingsState.instance
settingsComponent!!.setEnable(settings.enable)
}
override fun disposeUIResources() {
settingsComponent = null
}
} | oxc-intellij-plugin/src/main/kotlin/com/github/iwanabethatguy/oxcintellijplugin/settings/OxcSettingsConfigurable.kt | 228427553 |
package com.github.iwanabethatguy.oxcintellijplugin.settings
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.util.xmlb.XmlSerializerUtil
import org.jetbrains.annotations.NotNull
/**
* Supports storing the application settings in a persistent way.
* The [State] and [Storage] annotations define the name of the data and the file name where
* these persistent application settings are stored.
*/
@State(name = "OxcSettings", storages = arrayOf(Storage("OxcSettings.xml")))
class OxcSettingsState : PersistentStateComponent<OxcSettingsState> {
var run: Run = Run.OnSave
var enable: Boolean = true
companion object {
val instance:OxcSettingsState by lazy {
OxcSettingsState()
}
}
override fun loadState(@NotNull state: OxcSettingsState) {
XmlSerializerUtil.copyBean(state, this)
}
override fun getState(): OxcSettingsState {
return this
}
}
enum class Run {
OnType, OnSave
}
| oxc-intellij-plugin/src/main/kotlin/com/github/iwanabethatguy/oxcintellijplugin/settings/OxcSettingsState.kt | 1819909077 |
package com.github.iwanabethatguy.oxcintellijplugin.settings
import com.intellij.ui.components.JBBox
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.JBList
import com.intellij.ui.components.JBRadioButton
import com.intellij.ui.components.JBTextField
import com.intellij.util.ui.FormBuilder
import org.jetbrains.annotations.NotNull
import javax.swing.JComponent
import javax.swing.JPanel
class OxcSettingsComponent {
private var mainPanel: JPanel? = null
// private val runWhenOnSave = JBRadioButton("onSave")
// private val runWhenOnType = jBGROUP("onType")
private val enableCheckBox = JBCheckBox("Enable oxc language server: ")
fun AppSettingsComponent() {
mainPanel = FormBuilder.createFormBuilder()
.addComponent(enableCheckBox)
.addComponentFillVertically(JPanel(), 0)
.getPanel()
}
fun getPanel(): JPanel? {
return mainPanel
}
@NotNull
fun getEnable(): Boolean {
return enableCheckBox.isEnabled
}
fun setEnable(@NotNull newValue: Boolean) {
enableCheckBox.isEnabled = newValue
}
} | oxc-intellij-plugin/src/main/kotlin/com/github/iwanabethatguy/oxcintellijplugin/settings/OxcSettingsComponent.kt | 3875676249 |
package com.github.iwanabethatguy.oxcintellijplugin.lsp
import com.intellij.execution.ExecutionException
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.platform.lsp.api.ProjectWideLspServerDescriptor
import com.intellij.openapi.fileTypes.FileType
import com.intellij.platform.lsp.api.customization.LspDiagnosticsSupport
import com.intellij.platform.lsp.api.requests.LspRequest
import org.eclipse.lsp4j.ConfigurationItem
import org.eclipse.lsp4j.InitializeParams
class OxcLspServerDescriptor(project: Project) : ProjectWideLspServerDescriptor(project, "Oxc") {
override fun isSupportedFile(file: VirtualFile): Boolean {
thisLogger().warn("file.extension " + file.extension.toString())
return file.extension == "js" || file.extension == "jsx" || file.extension == "ts" || file.extension == "tsx"
}
override fun createCommandLine(): GeneralCommandLine {
thisLogger().warn("Start oxc language server")
return GeneralCommandLine("oxc_language_server").apply {
}
}
override fun createInitializationOptions(): Any? {
val options = super.createInitializationOptions()
thisLogger().warn("get oxc configuration" + options.toString())
return options
}
override val lspGoToDefinitionSupport = false
override val lspCompletionSupport = null
override val lspFormattingSupport = null
override val lspHoverSupport = false
} | oxc-intellij-plugin/src/main/kotlin/com/github/iwanabethatguy/oxcintellijplugin/lsp/OxcLspServerDescriptor.kt | 3240840458 |
package com.github.iwanabethatguy.oxcintellijplugin.lsp
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.platform.lsp.api.LspServerSupportProvider
class OxcLspServerSupportProvider: LspServerSupportProvider {
override fun fileOpened(project: Project, file: VirtualFile, serverStarter: LspServerSupportProvider.LspServerStarter) {
if (!(file.extension == "js" || file.extension == "jsx" || file.extension == "ts" || file.extension == "tsx")) return
serverStarter.ensureServerStarted(OxcLspServerDescriptor(project))
}
}
| oxc-intellij-plugin/src/main/kotlin/com/github/iwanabethatguy/oxcintellijplugin/lsp/OxcLspServerSupportProvider.kt | 3143470529 |
package com.github.iwanabethatguy.oxcintellijplugin
import com.intellij.DynamicBundle
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
@NonNls
private const val BUNDLE = "messages.MyBundle"
object MyBundle : DynamicBundle(BUNDLE) {
@JvmStatic
fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any) =
getMessage(key, *params)
@Suppress("unused")
@JvmStatic
fun messagePointer(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any) =
getLazyMessage(key, *params)
}
| oxc-intellij-plugin/src/main/kotlin/com/github/iwanabethatguy/oxcintellijplugin/MyBundle.kt | 1732204658 |
package com.github.iwanabethatguy.oxcintellijplugin.listeners
import com.intellij.openapi.application.ApplicationActivationListener
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.wm.IdeFrame
internal class MyApplicationActivationListener : ApplicationActivationListener {
override fun applicationActivated(ideFrame: IdeFrame) {
thisLogger().warn("Don't forget to remove all non-needed sample code files with their corresponding registration entries in `plugin.xml`.")
}
}
| oxc-intellij-plugin/src/main/kotlin/com/github/iwanabethatguy/oxcintellijplugin/listeners/MyApplicationActivationListener.kt | 1259826 |
package com.github.iwanabethatguy.oxcintellijplugin.services
import com.intellij.openapi.components.Service
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.project.Project
import com.github.iwanabethatguy.oxcintellijplugin.MyBundle
@Service(Service.Level.PROJECT)
class MyProjectService(project: Project) {
init {
thisLogger().info(MyBundle.message("projectService", project.name))
thisLogger().warn("Don't forget to remove all non-needed sample code files with their corresponding registration entries in `plugin.xml`.")
}
fun getRandomNumber() = (1..100).random()
}
| oxc-intellij-plugin/src/main/kotlin/com/github/iwanabethatguy/oxcintellijplugin/services/MyProjectService.kt | 164712506 |
package com.example.myapplication
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.myapplication", appContext.packageName)
}
} | mobilki1/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt | 1188990709 |
package com.example.myapplication
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | mobilki1/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt | 2019423820 |
package com.example.myapplication
import android.media.AsyncPlayer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.ImageButton
import android.widget.TextView
import java.util.Random
class MainActivity : AppCompatActivity() {
private val elements = arrayOf("камень", "ножницы", "бумага", "ящерица", "Спок")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val buttonPaper: ImageButton = findViewById(R.id.imageButtonPaper)
val buttonNoz: ImageButton = findViewById(R.id.imageButtonNoz)
val buttonKamen: ImageButton = findViewById(R.id.imageButtonKamen)
val buttonYacher: ImageButton = findViewById(R.id.imageButtonYacher)
val buttonSpok: ImageButton = findViewById(R.id.imageButtonSpok)
buttonKamen.setOnClickListener({ playerChoise(0) })
buttonNoz.setOnClickListener({ playerChoise(1) })
buttonPaper.setOnClickListener({ playerChoise(2) })
buttonYacher.setOnClickListener({ playerChoise(3) })
buttonSpok.setOnClickListener({ playerChoise(4) })
}
fun playerChoise(playerGame: Int) {
val computerChoice = Random().nextInt(5)
val playerV: TextView = findViewById(R.id.textView)
val compV: TextView = findViewById(R.id.textView2)
val resultV: TextView = findViewById(R.id.textView3)
playerV.text = "Ваш выбор: ${elements[playerGame]}"
compV.text = "Выбор компьютера: ${elements[computerChoice]}"
val result = determineWinner(playerGame, computerChoice)
resultV.text = "Результат: $result"
}
private fun determineWinner(playerGame: Int, computerChoice: Int): String {
if (playerGame == computerChoice) {
return "Ничья"
} else if (
(playerGame == 0 && (computerChoice == 1 || computerChoice == 3)) ||
(playerGame == 1 && (computerChoice == 2 || computerChoice == 3)) ||
(playerGame == 2 && (computerChoice == 0 || computerChoice == 4)) ||
(playerGame == 3 && (computerChoice == 2 || computerChoice == 4)) ||
(playerGame == 4 && (computerChoice == 0 || computerChoice == 1))
) {
return "Вы выиграли"
} else {
return "Компьютер выиграл"
}
}
} | mobilki1/app/src/main/java/com/example/myapplication/MainActivity.kt | 4031998692 |
package com.example.animemoi_app
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.animemoi_app", appContext.packageName)
}
} | AnimeMoiApp/app/src/androidTest/java/com/example/animemoi_app/ExampleInstrumentedTest.kt | 578328778 |
package com.example.animemoi_app
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | AnimeMoiApp/app/src/test/java/com/example/animemoi_app/ExampleUnitTest.kt | 72553101 |
package com.example.animemoi_app.viewmodel
class HomeViewModel {
} | AnimeMoiApp/app/src/main/java/com/example/animemoi_app/viewmodel/HomeViewModel.kt | 3965487991 |
package com.example.animemoi_app.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0f, 0f, 0f, 0.5f)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | AnimeMoiApp/app/src/main/java/com/example/animemoi_app/ui/theme/Color.kt | 2871964792 |
package com.example.animemoi_app.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = Purple80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple80,
secondary = Purple80,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun AnimeMoi_AppTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | AnimeMoiApp/app/src/main/java/com/example/animemoi_app/ui/theme/Theme.kt | 2079286562 |
package com.example.animemoi_app.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | AnimeMoiApp/app/src/main/java/com/example/animemoi_app/ui/theme/Type.kt | 2285294545 |
package com.example.animemoi_app
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.rememberNavController
import com.example.animemoi_app.common.navigation.AppNavigation
import com.example.animemoi_app.screen.CategoryScreen
import com.example.animemoi_app.ui.theme.AnimeMoi_AppTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
AnimeMoi_AppTheme {
AppNavigation()
}
}
}
}
| AnimeMoiApp/app/src/main/java/com/example/animemoi_app/MainActivity.kt | 1601859725 |
package com.example.animemoi_app.di
class AppModule {
} | AnimeMoiApp/app/src/main/java/com/example/animemoi_app/di/AppModule.kt | 1881069656 |
package com.example.animemoi_app.common
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import com.example.animemoi_app.R
import com.example.animemoi_app.common.navigation.Screens
@Composable
fun Bar(navController: NavHostController, modifier: Modifier = Modifier) {
Row(
modifier = modifier
.fillMaxWidth()
.background(Color.Black)
.height(40.dp),
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
text = stringResource(R.string.app_name),
modifier = modifier
.padding(16.dp, 8.dp, 0.dp, 8.dp)
.align(Alignment.CenterVertically),
fontWeight = FontWeight.Bold,
color = Color.White,
fontSize = 19.5.sp
)
Icon(
painter = painterResource(id = R.drawable.bell),
modifier = modifier
.padding(0.dp, 8.dp, 16.dp, 8.dp)
.clickable {
navController.navigate(Screens.NotificationScreen.name)
},
contentDescription = "Notification",
tint = Color.White,
)
}
}
| AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/Bar.kt | 3615735322 |
package com.example.animemoi_app.common
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountBox
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun ButtonCommon(
modifier: Modifier = Modifier,
text: String,
onClick: () -> Unit,
contentColor: Color = Color.White,
backgroundColor: Color = Color(0xFFFF6666),
iconButton: ImageVector? = null,
) {
Button(
onClick = onClick,
modifier = modifier
.background(color = backgroundColor, shape = CircleShape),
colors = ButtonDefaults.textButtonColors(
contentColor = contentColor
)
) {
Text(
text = text,
fontSize = 16.sp,
fontWeight = FontWeight.Bold,
)
if (iconButton != null) {
Icon(
imageVector = iconButton,
contentDescription = "",
Modifier.size(24.dp)
.padding(8.dp, 0.dp, 0.dp, 0.dp)
)
}
}
}
@Preview
@Composable
fun ButtonCommonPreview() {
ButtonCommon(
text = "Click me",
onClick = { /* TODO: Handle button click */ },
iconButton = Icons.Default.AccountBox
)
}
| AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/Button.kt | 2383493834 |
package com.example.animemoi_app.common
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.animemoi_app.data.SourceData
import com.example.animemoi_app.model.SourceComic
@JvmName("ListSourceComicForSourceComic")
@Composable
fun ListSourceComic(sources: List<SourceComic>) {
var selectedSourceIndex by remember { mutableIntStateOf(0) }
LazyRow(
Modifier
.background(Color.Black)
.fillMaxWidth()
.height(50.dp)
) {
items(sources) { item ->
Source(
source = item.name,
isSelect = selectedSourceIndex == sources.indexOf(item)
) {
selectedSourceIndex = sources.indexOf(item)
}
}
}
}
@JvmName("ListSourceComicForString")
@Composable
fun ListSourceComic(sources: List<String>) {
var selectedSourceIndex by remember { mutableIntStateOf(0) }
LazyRow(
Modifier
.background(Color.Black)
.fillMaxWidth()
.height(50.dp)
) {
items(sources) { item ->
Source(
source = item,
isSelect = selectedSourceIndex == sources.indexOf(item)
) {
selectedSourceIndex = sources.indexOf(item)
}
}
}
}
@Composable
fun Source(source: String, isSelect: Boolean, onClick: () -> Unit) {
Surface(
onClick = onClick,
color = Color.Transparent,
modifier = Modifier
.fillMaxHeight()
.padding(15.dp)
.drawBehind {
drawLine(
color = if (isSelect) Color(0xFFFF6666) else Color.Transparent,
start = Offset(0f, size.height),
end = Offset(size.width, size.height),
strokeWidth = 3.dp.toPx()
)
},
) {
Text(
text = source,
color = if (isSelect) Color(0xFFFF6666) else Color.White,
fontSize = 14.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier.fillMaxSize(),
)
}
}
@Preview
@Composable
fun PreviewListSourceComic() {
val sources = SourceData().loadSourceData()
ListSourceComic(sources)
}
| AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/ListSourceComic.kt | 2738192455 |
package com.example.animemoi_app.common.category_card
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.animemoi_app.data.CategoryData
import com.example.animemoi_app.data.ComicRepo
import com.example.animemoi_app.model.Category
import com.example.animemoi_app.model.ComicTest
@Composable
fun CardsComic(
comic: ComicTest,
selectedComic: (Int) -> Unit
){
Card(
modifier = Modifier
.width(150.dp)
.height(300.dp)
.clickable(onClick = {
selectedComic(comic.comicId)
}),
elevation = CardDefaults.cardElevation(16.dp),
colors = CardDefaults.cardColors(
containerColor = Color.Transparent
)
) {
Image(
painter = painterResource(id = comic.imageResourceId),
contentDescription = stringResource(id = comic.stringResourceId),
modifier = Modifier
.width(150.dp)
.height(230.dp)
.clip(RoundedCornerShape(10.dp)), // Round corners
contentScale = ContentScale.Crop // Scale the image content,
)
Text(
text = stringResource(id = comic.stringResourceId),
fontWeight = FontWeight.Light,
fontFamily = FontFamily.Monospace,
color = Color.White,
fontSize = 16.sp,
modifier = Modifier
.padding(18.dp),
maxLines = 1, // Chỉ hiển thị một dòng
overflow = TextOverflow.Ellipsis // Thêm dấu "..." khi văn bản quá dài
)
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun GridComic(
modifier: Modifier = Modifier,
selectedComic: (Int) -> Unit
) {
//val comics = ComicData().loadComicCard()
val categories = CategoryData().loadCategory()
val scrollState = rememberLazyListState()
val context = LocalContext.current
val comics: List<ComicTest> = ComicRepo.getComicsList(context)
LazyColumn(
verticalArrangement = Arrangement.spacedBy(1.dp),
state = scrollState
//modifier = Modifier.padding(horizontal = 25.dp, vertical = 15.dp)
) {
categories.forEach { category ->
// Lọc các bộ truyện thuộc vào danh mục này
val comicsInCategory =
comics.filter { it.categoryResourceId == category.stringResourceId }
// Nếu có bộ truyện thuộc danh mục này, hiển thị tiêu đề danh mục và danh sách bộ truyện
if (comicsInCategory.isNotEmpty()) {
item {
CategoryHeader(category = category)
}
item {
FlowRow(
maxItemsInEachRow = 2,
modifier = modifier
.padding(horizontal = 35.dp)
.fillMaxSize(),
horizontalArrangement = Arrangement.SpaceBetween
) {
for (comic in comicsInCategory) {
CardsComic(
comic = comic,
selectedComic = selectedComic
)
}
}
}
}
}
}
}
@Composable
fun CategoryHeader(category: Category) {
Text(
text = stringResource(id = category.stringResourceId),
fontWeight = FontWeight.Bold,
fontFamily = FontFamily.Monospace,
color = Color.White,
fontSize = 18.sp,
modifier = Modifier.padding(start = 18.dp, bottom = 25.dp),
maxLines = 1, // Chỉ hiển thị một dòng
)
}
@Preview
@Composable
fun CardsPreview() {
//GridComic()
} | AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/category_card/Card.kt | 1426388656 |
package com.example.animemoi_app.common.navigation
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.example.animemoi_app.common.navigation.AppDestinations.COMIC_DETAIL_ID_KEY
import com.example.animemoi_app.screen.*
private object AppDestinations {
const val COMIC_DETAIL_ID_KEY = "ComicDetailId"
}
@Composable
fun AppNavigation() {
val navController: NavHostController = rememberNavController()
val actions = remember(navController) { AppActions(navController) }
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentDestination = navBackStackEntry?.destination
val shouldShowNavBar = listOfRoutesToShowNavBar.contains(currentDestination?.route)
Scaffold(bottomBar = {
if (shouldShowNavBar) {
NavigationBar(containerColor = Color.Black, modifier = Modifier
.background(Color.Black)
.graphicsLayer {
shape = RoundedCornerShape(
topEnd = 10.dp, topStart = 10.dp
)
clip = true
}) {
listOfNavItem.forEach { navItem ->
NavigationBarItem(selected = currentDestination?.hierarchy?.any { it.route == navItem.route } == true,
onClick = {
navController.navigate(navItem.route) {
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
launchSingleTop = true
restoreState = true
}
},
icon = {
Icon(
imageVector = navItem.icon,
contentDescription = null,
modifier = Modifier
.padding(2.dp)
.size(30.dp)// Thêm padding cho biểu tượng
)
},
colors = NavigationBarItemDefaults.colors(
selectedIconColor = Color(0xFFFF6666),
unselectedIconColor = Color.White,
indicatorColor = Color.Transparent
)
)
}
}
}
}) { paddingValues: PaddingValues ->
NavHost(
navController = navController,
startDestination = Screens.HomeScreen.name,
modifier = Modifier.padding(paddingValues)
) {
composable(route = Screens.HomeScreen.name) {
HomeScreen(navController, selectedComic = actions.selectedComic)
}
composable(route = Screens.SearchScreen.name) {
SearchScreen(navController)
}
composable(route = Screens.HistoryScreen.name) {
HistoryScreen(navController, selectedComic = actions.selectedComic)
}
composable(route = Screens.SettingScreen.name) {
SettingScreen(navController)
}
composable(route = Screens.NotificationScreen.name) {
NotificationScreen(navController, selectedComic = actions.selectedComic)
}
composable(route = Screens.CategoryScreen.name) {
CategoryScreen(navController, selectedComic = actions.selectedComic)
}
composable(
route = "${Screens.DetailComicScreen.name}/{${COMIC_DETAIL_ID_KEY}}",
arguments = listOf(navArgument(COMIC_DETAIL_ID_KEY) {
type = NavType.IntType
})
) { backStackEntry ->
val arguments = requireNotNull(backStackEntry.arguments)
DetailScreen(
comicId = arguments.getInt(COMIC_DETAIL_ID_KEY), navigateUp = actions.navigateUp, navController
)
}
composable(
route = "${Screens.MoreComicScreen.name}/{TitleScreen}",
) {
val backStackEntry = navController.currentBackStackEntry
// Handle potential null case gracefully
val title = backStackEntry?.arguments?.getString("TitleScreen") ?: ""
MoreComicScreen(title, navController = navController, selectedComic = actions.selectedComic)
}
composable(
route = Screens.LoginScreen.name
) {
LoginScreen(navController = navController)
}
composable(
route = Screens.RegisterScreen.name
) {
RegisterScreen(navController = navController)
}
composable(
route = "${Screens.ReadingScreen.name}/{TitleComic}",
) {
val backStackEntry = navController.currentBackStackEntry
// Handle potential null case gracefully
val title = backStackEntry?.arguments?.getString("TitleComic") ?: ""
ReadingScreen(navController = navController, title = title)
}
composable(
route = "${Screens.CommentScreen.name}/{TitleComic}",
) {
val backStackEntry = navController.currentBackStackEntry
// Handle potential null case gracefully
val title = backStackEntry?.arguments?.getString("TitleComic") ?: ""
CommentScreen(navController = navController, title = title)
}
composable(
route = Screens.SourceComicScreen.name
) {
SourceComicScreen(navController = navController)
}
}
}
}
private class AppActions(
navController: NavHostController
) {
val selectedComic: (Int) -> Unit = { comicId: Int ->
navController.navigate("${Screens.DetailComicScreen.name}/$comicId")
}
val navigateUp: () -> Unit = {
navController.navigateUp()
}
}
@Preview
@Composable
fun AppNavigationPreview() {
AppNavigation()
}
| AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/navigation/AppNavigation.kt | 372081289 |
package com.example.animemoi_app.common.navigation
enum class Screens {
HomeScreen,
HistoryScreen,
SearchScreen,
SettingScreen,
CategoryScreen,
NotificationScreen,
DetailComicScreen,
MoreComicScreen,
LoginScreen,
RegisterScreen,
ReadingScreen,
CommentScreen,
SourceComicScreen,
}
// Define the routes where you want the NavigationBar to be visible
val listOfRoutesToShowNavBar = listOf(
Screens.HomeScreen.name,
Screens.SearchScreen.name,
Screens.HistoryScreen.name,
Screens.SettingScreen.name,
Screens.NotificationScreen.name,
Screens.CategoryScreen.name
) | AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/navigation/Screens.kt | 2015611780 |
package com.example.animemoi_app.common.navigation
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountBox
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Settings
import androidx.compose.ui.graphics.vector.ImageVector
data class NavItem(
val label: String, val icon: ImageVector, val route: String
)
val listOfNavItem: List<NavItem> = listOf(
NavItem(
label = "Home", icon = Icons.Default.Home, route = Screens.HomeScreen.name
),
NavItem(
label = "Category", icon = Icons.Default.AccountBox, route = Screens.CategoryScreen.name
),
NavItem(
label = "Search", icon = Icons.Default.Search, route = Screens.SearchScreen.name
),
NavItem(
label = "History", icon = Icons.Default.Refresh, route = Screens.HistoryScreen.name
),
NavItem(
label = "Settings", icon = Icons.Default.Settings, route = Screens.SettingScreen.name
),
)
| AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/navigation/NavBar.kt | 3874102764 |
package com.example.animemoi_app.common.comic
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.animemoi_app.R
import com.example.animemoi_app.model.Comic
import com.example.animemoi_app.model.ComicTest
@Composable
fun ComicColumn(
comic: ComicTest,
showStatus: Boolean,
showLastTimeUpdate: Boolean,
selectedComic: (Int) -> Unit
) {
Card(
modifier = Modifier
.fillMaxWidth()
.height(90.dp)
.padding(horizontal = 15.dp)
.clickable {
selectedComic(comic.comicId)
},
elevation = CardDefaults.cardElevation(10.dp),
colors = CardDefaults.cardColors(containerColor = Color.Black),
shape = RoundedCornerShape(5.dp)
) {
Row {
Image(
painter = painterResource(id = comic.imageResourceId),
contentDescription = null,
modifier = Modifier
.fillMaxHeight()
.clip(RoundedCornerShape(8.dp)), // Round corners
contentScale = ContentScale.Crop // Scale the image content,
)
Column(
modifier = Modifier
.padding(start = 5.dp)
.fillMaxHeight(),
verticalArrangement = Arrangement.SpaceBetween
) {
Text(
text = stringResource(id = comic.stringResourceId),
color = Color.White,
fontSize = 16.sp,
fontWeight = FontWeight.Bold,
fontFamily = FontFamily.Monospace,
maxLines = 1, // Chỉ hiển thị một dòng
overflow = TextOverflow.Ellipsis
)
Text(
text = stringResource(R.string.chapter) + " " + comic.lastChapter,
color = Color.White,
fontWeight = FontWeight.Light,
fontFamily = FontFamily.Monospace,
fontSize = 13.sp
)
if (showStatus) {
Text(
text = stringResource(R.string.status) + ": " + stringResource(id = comic.status),
color = Color.White,
fontWeight = FontWeight.Light,
fontFamily = FontFamily.Monospace,
fontSize = 13.sp
)
}
if (showLastTimeUpdate) {
Text(
text = stringResource(R.string.update) + ": " + comic.timeUpdate,
color = Color.White,
fontWeight = FontWeight.Light,
fontFamily = FontFamily.Monospace,
fontSize = 13.sp
)
}
}
}
}
}
| AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/comic/ComicColumn.kt | 2010960967 |
package com.example.animemoi_app.common.comic
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.RemoveRedEye
import androidx.compose.material.icons.filled.Star
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.animemoi_app.model.Comic
@Composable
fun Comic(
moreInfo: Boolean,
star: Float = 4.5F,
views: Int = 0,
follow: Int = 0,
comic: Comic,
selectedComic: (Int) -> Unit
) {
Column(
modifier = Modifier
.width(150.dp)
.padding(horizontal = 8.dp),
) {
Card(
colors = CardDefaults.cardColors(
containerColor = Color.Transparent,
contentColor = Color.White
),
modifier = Modifier
.fillMaxWidth()
.clickable {
selectedComic(comic.comicId)
}
) {
Box(
modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.BottomCenter
) {
Image(
painterResource(comic.imageResourceId), contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.width(150.dp)
)
if (moreInfo) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.background(
Color.Black.copy(0.5f)
)
.width(150.dp),
) {
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.padding(0.dp, 8.dp)
) {
Icon(
Icons.Default.Star,
contentDescription = null,
tint = Color.White,
modifier = Modifier
.size(16.dp)
)
Text(
star.toString(),
fontSize = 10.sp,
color = Color.White
)
Icon(
Icons.Default.RemoveRedEye,
contentDescription = null,
tint = Color.White,
modifier = Modifier
.size(16.dp)
)
Text(
views.toString(),
fontSize = 10.sp,
color = Color.White
)
Icon(
Icons.Default.Favorite,
contentDescription = null,
tint = Color.White,
modifier = Modifier
.size(16.dp)
)
Text(
follow.toString(),
fontSize = 10.sp,
color = Color.White
)
}
}
}
}
}
Text(
text = stringResource(comic.stringResourceId),
color = Color.White,
modifier = Modifier
.background(Color.Transparent)
.align(Alignment.CenterHorizontally)
.padding(top = 10.dp),
overflow = TextOverflow.Ellipsis,
maxLines = 1,
)
}
}
| AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/comic/Comic.kt | 4055280150 |
package com.example.animemoi_app.common.comic
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.example.animemoi_app.data.ComicData
@Composable
fun ComicRow(
selectedComic: (Int) -> Unit
) {
val listComic = ComicData().loadComicCard()
LazyRow(
modifier = Modifier.padding(16.dp)
) {
items(listComic) { comic ->
Comic(
moreInfo = true,
comic = comic,
selectedComic = selectedComic
)
}
}
}
| AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/comic/ComicRow.kt | 805526236 |
package com.example.animemoi_app.common.comic
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowForward
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.example.animemoi_app.common.navigation.Screens
@Composable
fun ComicRowWithTitle(
title: String,
modifier: Modifier = Modifier,
navController: NavHostController,
selectedComic: (Int) -> Unit
) {
Column {
Row(
modifier = modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
text = title,
color = Color.White,
modifier = modifier
.padding(start = 16.dp, top = 8.dp, end = 0.dp, bottom = 8.dp)
)
Icon(
Icons.Default.ArrowForward,
tint = Color.White,
contentDescription = null,
modifier = modifier
.padding(start = 0.dp, top = 8.dp, end = 16.dp, bottom = 8.dp)
.clickable {
navController.navigate("${Screens.MoreComicScreen.name}/${title}")
}
)
}
ComicRow(selectedComic)
}
}
@Preview
@Composable
fun ComicRowWithTitlePreview() {
//ComicRowWithTitle(title = "Truyện mới đăng",navController = { })
} | AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/comic/ComicRowWithTitle.kt | 2843479246 |
package com.example.animemoi_app.common.comic
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.animemoi_app.data.ComicData
@Composable
fun ComicGrid(
selectedComic: (Int) -> Unit
) {
val comics = ComicData().loadComicCard()
LazyVerticalGrid(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(12.dp),
columns = GridCells.Adaptive(minSize = 128.dp),
) {
items(comics) { comic ->
Box(modifier = Modifier.padding(8.dp)) {
Comic(
moreInfo = true,
comic = comic,
selectedComic = selectedComic
)
}
}
}
}
| AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/comic/ComicGrid.kt | 358571238 |
package com.example.animemoi_app.common
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.Icon
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.SearchBar
import androidx.compose.material3.SearchBarDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
@ExperimentalMaterial3Api
@Composable
fun SearchBar() {
//This is the text users enter
var queryString by remember {
mutableStateOf("")
}
//if the search bar is active or not
var isActive by remember {
mutableStateOf(false)
}
val contextForToast = LocalContext.current.applicationContext
//previous search terms
val historyItems = remember {
mutableStateListOf("Toàn chức pháp sư", "Tu tiên truyện", "Xuyên không về thời cổ đại")
}
SearchBar(
modifier = Modifier
.fillMaxWidth()
.padding(1.dp)
.background(Color.Black)
.border(
0.5.dp,
if (isActive) Color.Transparent else Color.Gray,
CircleShape
),
query = queryString,
onQueryChange = { newQueryString ->
queryString = newQueryString
},
onSearch = {
isActive = false
Toast.makeText(contextForToast, "Bạn đã tìm: $queryString", Toast.LENGTH_SHORT)
.show()
historyItems.add(queryString)
},
active = isActive,
onActiveChange = { activeChange ->
isActive = activeChange
},
placeholder = {
Text(text = "Tìm kiếm...", color = Color.White)
},
leadingIcon = {
Icon(imageVector = Icons.Default.Search, contentDescription = null, tint = Color.White)
},
trailingIcon = {
if (isActive) {
Icon(
modifier = Modifier.clickable {
if (queryString.isNotEmpty()) {
queryString = ""
} else {
isActive = false
}
},
imageVector = Icons.Default.Close,
contentDescription = "Close Icon"
)
}
},
colors = SearchBarDefaults.colors(
containerColor = Color.Black,
dividerColor = Color(0xFFFF6666),
inputFieldColors = TextFieldDefaults.colors(
focusedTextColor = Color.White,
unfocusedTextColor = Color.White,
cursorColor = Color(0xFFFF6666)
)
),
tonalElevation = 500.dp,
content = {
//this is a column scope
//all the items are displayed vertically
historyItems.forEach { historyItem ->
Row(modifier = Modifier.padding(all = 16.dp)) {
Icon(
modifier = Modifier.padding(end = 12.dp),
imageVector = Icons.Default.Refresh, contentDescription = null,
tint = Color.White
)
Text(text = historyItem, color = Color.White)
}
}
}
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Composable
fun SearchBarPreview() {
SearchBar()
} | AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/SearchBar.kt | 465833283 |
package com.example.animemoi_app.common.comic_detail
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreHoriz
import androidx.compose.material.icons.filled.RemoveRedEye
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChapterListDetail() {
//Chapter List
var text by remember {
mutableStateOf("")
}
Card(
modifier = Modifier
.height(500.dp)
.padding(5.dp, 15.dp, 5.dp, 5.dp),
colors = CardDefaults.cardColors(Color(0xFF444242))
) {
Row(
modifier = Modifier
.padding(8.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
OutlinedTextField(
value = text,
onValueChange = { text = it },
label = null,
placeholder = {
Text(text = "Nhập để tìm chương, vi du 1124", fontSize = 7.sp)
},
colors = TextFieldDefaults.outlinedTextFieldColors(
containerColor = Color.Black,
focusedTextColor = Color.White,
unfocusedTextColor = Color.White
),
modifier = Modifier
.fillMaxWidth(0.9f)
.height(40.dp),
shape = RoundedCornerShape(30.dp),
maxLines = 1,
textStyle = TextStyle(fontSize = 7.sp)
)
Icon(
imageVector = Icons.Default.MoreHoriz,
contentDescription = "Xem thêm",
tint = Color.White
)
}
Row(
modifier = Modifier
.padding(8.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(text = "Chương", color = Color.White)
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(text = "Mới nhất", color = Color(0xFFFF6666))
Text(text = "Cũ nhất", color = Color.White)
}
}
Divider(
modifier = Modifier.padding(horizontal = 10.dp)
)
//ListChapterDetail
LazyColumn {
item () {
ListChapterDetail()
ListChapterDetail()
ListChapterDetail()
ListChapterDetail()
ListChapterDetail()
ListChapterDetail()
ListChapterDetail()
ListChapterDetail()
ListChapterDetail()
ListChapterDetail()
ListChapterDetail()
ListChapterDetail()
ListChapterDetail()
ListChapterDetail()
ListChapterDetail()
ListChapterDetail()
ListChapterDetail()
ListChapterDetail()
ListChapterDetail()
}
}
}
}
@Composable
fun ListChapterDetail() {
Row(
modifier = Modifier
.padding(10.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Row (
horizontalArrangement = Arrangement.spacedBy(5.dp)
){
Text(text = "Chuơng 1",color = Color.White, fontSize = 12.sp)
Text(text = "Tên chương(Nếu có)", color = Color.White, fontSize = 12.sp)
}
Row (verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(5.dp)
){
Text(text = "12 Giờ trước", color = Color.White, fontSize = 12.sp)
Row (verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(2.dp)){
Icon(
imageVector = Icons.Default.RemoveRedEye,
contentDescription = null, tint = Color.White,
modifier = Modifier.size(15.dp)
)
Text(text = "4.5k", color = Color.White, fontSize = 12.sp)
}
}
}
}
@Preview
@Composable
fun PreviewChapterListDetail() {
ChapterListDetail()
} | AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/comic_detail/ChapterListDetail.kt | 4025763408 |
package com.example.animemoi_app.common.comic_detail
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Bookmark
import androidx.compose.material.icons.filled.MenuBook
import androidx.compose.material.icons.filled.SaveAlt
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.example.animemoi_app.common.ButtonCommon
import com.example.animemoi_app.common.ListSourceComic
@Composable
fun NavComicDetail(titleComic:String, navController: NavHostController) {
Column {
//Nav comic
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 15.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
ButtonCommon(
onClick = { navController.navigate("ReadingScreen/${titleComic}") },
text = "Đọc",
iconButton = Icons.Default.MenuBook
)
Row(
horizontalArrangement = Arrangement.spacedBy(5.dp)
) {
Icon(
imageVector = Icons.Default.Bookmark,
contentDescription = null,
tint = Color(0xFFFF6666)
)
Icon(
imageVector = Icons.Default.SaveAlt,
contentDescription = null,
tint = Color(0xFFFF6666)
)
Icon(
imageVector = Icons.Default.Share,
contentDescription = null,
tint = Color(0xFFFF6666)
)
}
}
//Nav
Box(modifier = Modifier.padding(vertical = 15.dp)) {
ListSourceComic(listOf("Mô tả", "Thể loại", "Truyện liên quan", "Bình luận"))
}
}
}
| AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/comic_detail/NavComicDetail.kt | 4131381354 |
package com.example.animemoi_app.common.comic_detail
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.StarRate
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun VoteComicDetail() {
//Vote comic
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 15.dp, vertical = 15.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(text = "Đánh giá cho truyện nhé", color = Color.White, fontSize = 18.sp)
Row {
Icon(
imageVector = Icons.Default.StarRate,
contentDescription = null,
tint = Color.Yellow
)
Icon(
imageVector = Icons.Default.StarRate,
contentDescription = null,
tint = Color.Yellow
)
Icon(
imageVector = Icons.Default.StarRate,
contentDescription = null,
tint = Color.Yellow
)
Icon(
imageVector = Icons.Default.StarRate,
contentDescription = null,
tint = Color.Yellow
)
Icon(
imageVector = Icons.Default.StarRate,
contentDescription = null,
tint = Color.Gray
)
}
}
}
@Preview
@Composable
fun PreviewVoteComicDetail() {
VoteComicDetail()
} | AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/comic_detail/VoteComicDetail.kt | 1893527973 |
package com.example.animemoi_app.common.comic_detail
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.PermIdentity
import androidx.compose.material.icons.filled.RemoveRedEye
import androidx.compose.material.icons.filled.Scanner
import androidx.compose.material.icons.filled.Star
import androidx.compose.material3.Card
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.BlurredEdgeTreatment
import androidx.compose.ui.draw.blur
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun TitleDetail(
comicImage: Int,
comicTitle: Int,
navigateUp: () -> Unit
) {
//Card title
Card(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(0.3f),
shape = RoundedCornerShape(bottomEnd = 20.dp, bottomStart = 20.dp)
) {
Box(modifier = Modifier.fillMaxSize()) {
Image(
painter = painterResource(id = comicImage),
contentDescription = null,
modifier = Modifier
.fillMaxSize(),
contentScale = ContentScale.Crop
)
Box(
modifier = Modifier
.fillMaxSize()
.background(
Brush.verticalGradient(
colors = listOf(
Color.Transparent,
Color.Gray
)
)
)
)
Column(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 15.dp),
verticalArrangement = Arrangement.SpaceBetween
) {
Icon(
imageVector = Icons.Default.ArrowBack,
contentDescription = null,
tint = Color.White,
modifier = Modifier
.size(40.dp)
.clickable {
navigateUp()
}
)
Column(
modifier = Modifier.padding(bottom = 15.dp),
verticalArrangement = Arrangement.spacedBy(5.dp)
) {
Text(
text = stringResource(id = comicTitle),
color = Color.White,
fontSize = 18.sp,
fontWeight = FontWeight.Bold,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
Row(
modifier = Modifier
.fillMaxWidth()
.wrapContentSize(Alignment.BottomStart, true),
horizontalArrangement = Arrangement.Start
) {
//icon1
Row(
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
imageVector = Icons.Default.Scanner,
contentDescription = "Đang cập nhật",
tint = Color.White
)
Text(text = "Đang cập nhật", color = Color.White)
}
Spacer(modifier = Modifier.width(8.dp))
//icon2
Row(
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
imageVector = Icons.Default.PermIdentity,
contentDescription = "Tác giả",
tint = Color.White
)
Text(text = "Gumayushi", color = Color.White)
}
Spacer(modifier = Modifier.width(8.dp))
//icon3
Row(
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
imageVector = Icons.Default.Star,
contentDescription = "Đánh giá",
tint = Color.White
)
Text(text = "4.6", color = Color.White)
}
Spacer(modifier = Modifier.width(8.dp))
//icon4
Row(
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
imageVector = Icons.Default.RemoveRedEye,
contentDescription = "Số lượt xem",
tint = Color.White
)
Text(text = "46k", color = Color.White)
}
}
}
}
}
}
}
| AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/comic_detail/TilteDetail.kt | 1528515685 |
package com.example.animemoi_app.common.comic_detail
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.AbsoluteAlignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
@Composable
fun InformationComicDetail() {
//Information card
Card(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(0.3f)
.padding(horizontal = 5.dp),
colors = CardDefaults.cardColors(Color(0xFF444242))
) {
Column(
modifier = Modifier.padding(10.dp),
horizontalAlignment = AbsoluteAlignment.Left,
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
Text(
text = "Tên khác: Unagi Oni; Lươn Quỷ",
maxLines = 1,
overflow = TextOverflow.Ellipsis,
color = Color.White
)
Text(
text = "Đại Y Lăng Điền Vô Cùng Phiền Phức là một tiểu thuyết Trung Quốc nổi tiếng thuộc thể loại lịch sử võ hiệp, được viết bởi nhà văn Trung Quốc Hồ Điệp Khê. Truyện kể về cuộc sống và cuộc phiêu lưu của nhân vật chính trong thời kỳ những cuộc tranh đấu giữa các môn phái võ thuật ở Trung Quốc cổ đại",
maxLines = 5,
overflow = TextOverflow.Ellipsis,
color = Color.White
)
}
}
}
@Preview
@Composable
fun PreviewInformationComicDetail() {
InformationComicDetail()
} | AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/comic_detail/InfomationComicDetail.kt | 233869869 |
package com.example.animemoi_app.common
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Icon
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
@Composable
fun ComeBack(title: String, navController : NavController) {
Row(
modifier = Modifier
.fillMaxWidth()
.height(40.dp)
.background(Color.Black),
verticalAlignment = Alignment.CenterVertically
) {
Surface(
modifier = Modifier
.width(40.dp)
.fillMaxHeight(),
contentColor = Color.White,
onClick = {
navController.popBackStack()
}
) {
Icon(
Icons.Default.ArrowBack,
contentDescription = title,
modifier = Modifier
.background(Color.Black),
)
}
Text(
text = title,
color = Color.White,
fontSize = 22.sp,
fontWeight = FontWeight.Medium,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.padding(0.dp, 0.dp, 40.dp, 0.dp)
)
}
}
@Preview
@Composable
fun ComeBackPreview() {
ComeBack(title = "Tìm kiếm", navController = rememberNavController())
} | AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/ComeBack.kt | 765985286 |
@file:OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3Api::class)
package com.example.animemoi_app.common.history
import android.annotation.SuppressLint
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.DismissDirection
import androidx.compose.material3.DismissState
import androidx.compose.material3.DismissValue
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.SwipeToDismiss
import androidx.compose.material3.rememberDismissState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.animemoi_app.common.comic.ComicColumn
import com.example.animemoi_app.data.ComicRepo
import com.example.animemoi_app.model.ComicTest
import kotlinx.coroutines.delay
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
import kotlin.time.DurationUnit
import kotlin.time.toDuration
@SuppressLint("UnrememberedMutableState", "MutableCollectionMutableState")
@Composable
fun GridHistoryCard(
showStatus: Boolean,
showLastTimeUpdate: Boolean,
selectedComic: (Int) -> Unit
) {
val context = LocalContext.current
var comics by remember { mutableStateOf(ComicRepo.getComicsList(context).toMutableList()) }
LazyColumn(
verticalArrangement = Arrangement.spacedBy(20.dp),
//horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.padding(horizontal = 20.dp),
) {
items(
items = comics,
key = {it.comicId}
) { comic ->
SwipeToDeleteContainer(
item = comic,
onDelete = {
comics = comics.filter { it.comicId != comic.comicId }.toMutableList()
}
) {
ComicColumn(
comic,
showStatus,
showLastTimeUpdate,
selectedComic
)
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun <T> SwipeToDeleteContainer(
item: T,
onDelete: (T) -> Unit,
animationDurarion: Int = 500,
content: @Composable (T) -> Unit
) {
var isRemove by remember {
mutableStateOf(false)
}
val state = rememberDismissState(
confirmValueChange = { value ->
if (value == DismissValue.DismissedToStart) {
isRemove = true
true
} else {
false
}
}
)
LaunchedEffect(key1 = isRemove) {
if (isRemove) {
delay(animationDurarion.toDuration(DurationUnit.MILLISECONDS))
onDelete(item)
}
}
AnimatedVisibility(
visible = !isRemove,
exit = shrinkVertically(
animationSpec = tween(durationMillis = animationDurarion),
shrinkTowards = Alignment.Top
) + fadeOut()
) {
SwipeToDismiss(
state = state,
background = {
DeleteBackGround(swipeDismissState = state)
},
dismissContent = {
content(item)
},
directions = setOf(DismissDirection.EndToStart)
)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DeleteBackGround(
swipeDismissState: DismissState
) {
val color = if (
swipeDismissState.dismissDirection == DismissDirection.EndToStart
) {
Color.Red
} else Color.Transparent
Box(
modifier = Modifier
.fillMaxSize()
.background(color)
.padding(16.dp),
contentAlignment = Alignment.CenterEnd
) {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = null,
tint = Color.White
)
}
}
@Preview
@Composable
fun HistoryCardPreview() {
// GridHistoryCard(showStatus = true, showLastTimeUpdate = false)
}
| AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/history/GridHistoryCard.kt | 25472527 |
package com.example.animemoi_app.common.setting
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun InputIcon(text: String, icon: Painter) {
Row(
modifier = Modifier
.padding(0.dp, 8.dp)
.fillMaxWidth()
.height(40.dp)
.background(Color(0f, 0f, 0f, 0.5f), CircleShape),
) {
Row(
modifier = Modifier
.padding(8.dp, 4.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Column(
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxHeight()
) {
Text(
text = text,
color = Color.White,
fontSize = 12.sp
)
}
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.End,
verticalArrangement = Arrangement.Center
) {
Image(
icon,
contentDescription = "Icon",
modifier = Modifier
.size(40.dp)
.clickable { }
)
}
}
}
} | AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/setting/InputIcon.kt | 3435152586 |
package com.example.animemoi_app.common.setting
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun InputListChoose(title: String, listChoose: String, icon: ImageVector, background: Boolean){
Row(
modifier = Modifier
.padding(0.dp, 8.dp)
.fillMaxWidth()
.height(40.dp)
.background(if(background) Color(0f, 0f, 0f, 0.5f) else Color.Transparent, CircleShape),
) {
Row(
modifier = Modifier
.padding(8.dp, 4.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Column(
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxHeight()
) {
Text(
text = title,
color = Color.White,
fontSize = 12.sp
)
}
Column(
modifier = Modifier.fillMaxWidth(0.8f),
horizontalAlignment = Alignment.End,
verticalArrangement = Arrangement.Center
) {
Text(
text = listChoose,
color = Color.White,
fontSize = 12.sp
)
}
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.End,
verticalArrangement = Arrangement.Center
) {
Icon(
icon,
tint = Color.White,
contentDescription = "Icon",
modifier = Modifier
.size(40.dp)
.clickable { }
)
}
}
}
} | AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/setting/InputListChoose.kt | 23025848 |
package com.example.animemoi_app.common.setting
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun TitleWithIcon(title: String, icon: ImageVector, modifier: Modifier = Modifier) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp, 0.dp), verticalAlignment = Alignment.CenterVertically
) {
Text(
text = title,
fontSize = 12.sp,
fontWeight = FontWeight.Bold,
color = Color.White,
modifier = modifier.fillMaxWidth(0.9f)
)
Icon(
icon, contentDescription = "Icon", tint = Color.White, modifier = modifier.fillMaxWidth()
)
}
}
| AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/setting/TittleWithIcon.kt | 3526927001 |
package com.example.animemoi_app.common.setting
import android.widget.Switch
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun Input(text: String, background: Boolean) {
var checked by remember { mutableStateOf(false) }
Row(
modifier = Modifier
.padding(0.dp, 8.dp)
.fillMaxWidth()
.height(40.dp)
.background(if(background) Color(0f, 0f, 0f, 0.5f) else Color.Transparent, CircleShape),
verticalAlignment = Alignment.CenterVertically
) {
Row(
modifier = Modifier
.padding(8.dp, 4.dp)
.fillMaxWidth(),
) {
Column(
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxHeight()
) {
Text(
text = text,
color = Color.White,
fontSize = 12.sp
)
}
Column (
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.End
) {
Switch(
checked = checked,
onCheckedChange = {checked = !checked},
colors = SwitchDefaults.colors(
checkedThumbColor = Color.White,
checkedTrackColor = Color(0xFFFF6666),
uncheckedThumbColor = Color.Gray,
uncheckedTrackColor = Color.Black,
uncheckedBorderColor = Color.Gray
)
)
}
}
}
}
| AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/setting/InputHideAndVisible.kt | 3762514565 |
package com.example.animemoi_app.common.comic_reading
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavHostController
import com.example.animemoi_app.data.ComicDetailData
import com.example.animemoi_app.model.ComicDetail
import com.example.animemoi_app.model.ModeReader
@Composable
fun ComicImage(
comicDetail: ComicDetail,
modifier: Modifier = Modifier
) {
Image(
painterResource(id = comicDetail.imageResourceId),
null,
modifier = modifier.fillMaxWidth(),
contentScale = ContentScale.Crop
)
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun ImagesComicList(
modeReader: ModeReader = ModeReader.Vertical,
navController: NavHostController,
title: String
) {
val imageList = ComicDetailData().loadComicDetail()
if (modeReader == ModeReader.Vertical) {
LazyVerticalGrid(
columns = GridCells.Fixed(1),
//horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
items(imageList) { img ->
ComicImage(comicDetail = img)
}
item {
CommentDetailComic(navController, title)
}
}
}
if (modeReader == ModeReader.Horizontal) {
val pagerState = rememberPagerState(pageCount = {
imageList.size
})
HorizontalPager(state = pagerState) { page ->
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
ComicImage(
comicDetail = imageList[page],
Modifier.fillMaxSize()
)
}
}
}
}
| AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/comic_reading/ImagesList.kt | 3749465794 |
package com.example.animemoi_app.common.comic_reading
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.ArrowBackIos
import androidx.compose.material.icons.filled.ArrowForwardIos
import androidx.compose.material.icons.filled.Minimize
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.SyncAlt
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
@Composable
fun NavDetailComic() {
Row(
modifier = Modifier
.fillMaxSize()
.padding(15.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.Bottom
) {
Icon(imageVector = Icons.Default.ArrowBack, contentDescription = null, tint = Color.White)
Icon(imageVector = Icons.Default.SyncAlt, contentDescription = null, tint = Color.White)
Row {
Icon(
imageVector = Icons.Default.ArrowBackIos, contentDescription = null, tint = Color.White
)
Text(text = "1", color = Color.White)
Icon(
imageVector = Icons.Default.Minimize, contentDescription = null, tint = Color.White
)
Text(text = "10", color = Color.White)
Icon(
imageVector = Icons.Default.ArrowForwardIos, contentDescription = null, tint = Color.White
)
}
Icon(imageVector = Icons.Default.Warning, contentDescription = null, tint = Color.White)
Icon(imageVector = Icons.Default.Settings, contentDescription = null, tint = Color.White)
}
}
@Preview
@Composable
fun PreviewNavDetail() {
NavDetailComic()
} | AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/comic_reading/Nav.kt | 375604934 |
package com.example.animemoi_app.common.comic_reading
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Bookmark
import androidx.compose.material.icons.filled.Comment
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Send
import androidx.compose.material.icons.filled.ThumbUp
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import com.example.animemoi_app.R
@Composable
fun CommentCard() {
Card {
Row {
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CommentDetailComic(navController: NavHostController, title: String) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
colors = CardDefaults.cardColors(Color(0xFF444242))
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(
horizontal = 50.dp,
vertical = 15.dp
),
horizontalArrangement = Arrangement.SpaceBetween,
) {
//Like
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
Icon(
imageVector = Icons.Default.ThumbUp,
contentDescription = null,
tint = Color.White
)
Text(text = "Thích", color = Color.White)
Text(text = "100", color = Color.White)
}
//Add to library
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
Icon(
imageVector = Icons.Default.Bookmark,
contentDescription = null,
tint = Color.White
)
Text(text = "Thêm vào thư viện", color = Color.White)
Text(text = "100", color = Color.White)
}
}
Divider(
modifier = Modifier
.padding(horizontal = 15.dp, vertical = 15.dp)
)
//Headline
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 15.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "Bình luận nổi bật",
color = Color.White,
fontSize = 18.sp
)
Text(
text = "Tổng 100 bình luận",
color = Color(0xFFFF6666),
textDecoration = TextDecoration.Underline,
modifier = Modifier
.clickable {
navController.navigate("CommentScreen/${title}")
}
)
}
//Comment Card
Card(
modifier = Modifier
.padding(15.dp),
colors = CardDefaults.cardColors(Color.Transparent)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(15.dp)
) {
Image(
painter = painterResource(id = R.drawable.deba),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.size(40.dp)
.clip(CircleShape)
.background(Color.Red)
)
Column(
verticalArrangement = Arrangement.spacedBy(5.dp)
) {
Text(
text = "Lê Tuấn Kha",
color = Color.White,
fontWeight = FontWeight.Bold
)
Text(
text = "Tập này hay quá",
color = Color.White,
fontWeight = FontWeight.Light,
)
Row(
modifier = Modifier
.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "22 giờ trước",
color = Color.White,
fontWeight = FontWeight.Light
)
Row(
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Icon(
imageVector = Icons.Default.MoreVert,
contentDescription = null,
tint = Color(0xFFC2C2C2)
)
Icon(
imageVector = Icons.Default.Comment,
contentDescription = null,
tint = Color(0xFFC2C2C2),
modifier = Modifier.padding(end = 5.dp)
)
Icon(
imageVector = Icons.Default.ThumbUp,
contentDescription = null,
tint = Color(0xFFC2C2C2)
)
}
}
}
}
}
Card(
modifier = Modifier
.padding(15.dp),
colors = CardDefaults.cardColors(Color.Transparent)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(15.dp)
) {
Image(
painter = painterResource(id = R.drawable.deba),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.size(40.dp)
.clip(CircleShape)
.background(Color.Red)
)
Column(
verticalArrangement = Arrangement.spacedBy(5.dp)
) {
Text(
text = "Lê Tuấn Kha",
color = Color.White,
fontWeight = FontWeight.Bold
)
Text(
text = "Tập này hay quá",
color = Color.White,
fontWeight = FontWeight.Light,
)
Row(
modifier = Modifier
.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "22 giờ trước",
color = Color.White,
fontWeight = FontWeight.Light
)
Row(
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Icon(
imageVector = Icons.Default.MoreVert,
contentDescription = null,
tint = Color(0xFFC2C2C2)
)
Icon(
imageVector = Icons.Default.Comment,
contentDescription = null,
tint = Color(0xFFC2C2C2),
modifier = Modifier.padding(end = 5.dp)
)
Icon(
imageVector = Icons.Default.ThumbUp,
contentDescription = null,
tint = Color(0xFFC2C2C2)
)
}
}
}
}
}
//Comment TextBox
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 15.dp, vertical = 20.dp),
verticalAlignment = Alignment.CenterVertically
) {
Image(
painter = painterResource(id = R.drawable.deba),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.size(40.dp)
.clip(CircleShape)
.background(Color.Red)
)
var text by remember {
mutableStateOf("")
}
OutlinedTextField(
value = text,
onValueChange = { text = it },
label = null,
placeholder = {
Text(text = "Viết gì đó", fontSize = 10.sp)
},
colors = TextFieldDefaults.outlinedTextFieldColors(
containerColor = Color.Black,
focusedTextColor = Color.White,
unfocusedTextColor = Color.White
),
modifier = Modifier
.padding(horizontal = 5.dp)
.fillMaxWidth(0.9f)
.height(45.dp),
shape = RoundedCornerShape(30.dp),
maxLines = 1,
textStyle = TextStyle(fontSize = 10.sp)
)
Icon(
imageVector = Icons.Default.Send,
contentDescription = null,
tint = Color.White,
modifier = Modifier.clickable { }
)
}
}
}
| AnimeMoiApp/app/src/main/java/com/example/animemoi_app/common/comic_reading/Comment.kt | 1723564278 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.