content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.yunyan.snake
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)
}
}
|
final-test1/app/src/test/java/com/yunyan/snake/ExampleUnitTest.kt
|
411985913
|
package com.yunyan.snake.ui.widget
/**
* @author: YunYan
* @description: 按键数据提供接口
* @date:2021/8/12
*/
interface IKeyData {
/**
* 获取游戏状态
*/
fun gameState(gameState: GameStateEnum)
/**
* 获取蛇头方向
*/
fun direction(directionState: DirectionStateEnum)
}
|
final-test1/app/src/main/java/com/yunyan/snake/ui/widget/IKeyData.kt
|
3501768374
|
package com.yunyan.snake.ui.widget
/**
* @author: YunYan
* @description: 方向
* @date:2021/8/12
*/
enum class DirectionStateEnum {
UP,
DOWN,
LEFT,
RIGHT
}
|
final-test1/app/src/main/java/com/yunyan/snake/ui/widget/DirectionStateEnum.kt
|
435637311
|
package com.yunyan.snake.ui.widget
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.Button
import android.widget.FrameLayout
import com.yunyan.snake.R
/**
* @author: YunYan
* @description: 按键视图: 方向,开始/暂停
* @date:2021/8/12
*/
class KeyView(context: Context, attributeSet: AttributeSet) :
FrameLayout(context, attributeSet), View.OnClickListener {
private lateinit var mBtnUp: Button
private lateinit var mBtnDown: Button
private lateinit var mBtnLeft: Button
private lateinit var mBtnRight: Button
private lateinit var mBtnSwitch: Button
private var mDirection = DirectionStateEnum.RIGHT
private var mGameState = GameStateEnum.STOP
private lateinit var mIKeyData: IKeyData
init {
init()
}
private fun init() {
val inflate = inflate(context, R.layout.view_key, this)
mBtnUp = inflate.findViewById(R.id.keyView_btn_up)
mBtnDown = inflate.findViewById(R.id.keyView_btn_down)
mBtnLeft = inflate.findViewById(R.id.keyView_btn_left)
mBtnRight = inflate.findViewById(R.id.keyView_btn_right)
mBtnSwitch = inflate.findViewById(R.id.keyView_btn_switch)
mBtnUp.setOnClickListener(this)
mBtnDown.setOnClickListener(this)
mBtnLeft.setOnClickListener(this)
mBtnRight.setOnClickListener(this)
mBtnSwitch.setOnClickListener(this)
}
fun setIKeyData(iKeyData: IKeyData) {
this.mIKeyData = iKeyData
}
/**
* 游戏失败
*/
fun gameOver() {
mBtnSwitch.setBackgroundResource(R.drawable.select_pause)
mDirection = DirectionStateEnum.RIGHT
mGameState = GameStateEnum.STOP
}
override fun onClick(v: View?) {
val id = v?.id
if (mGameState == GameStateEnum.START) {
when (id) {
R.id.keyView_btn_up -> {
mDirection = DirectionStateEnum.UP
}
R.id.keyView_btn_down -> {
mDirection = DirectionStateEnum.DOWN
}
R.id.keyView_btn_left -> {
mDirection = DirectionStateEnum.LEFT
}
R.id.keyView_btn_right -> {
mDirection = DirectionStateEnum.RIGHT
}
}
}
if (id == R.id.keyView_btn_switch) {
if (mGameState == GameStateEnum.STOP || mGameState == GameStateEnum.PAUSE) {
mGameState = GameStateEnum.START
mBtnSwitch.setBackgroundResource(R.drawable.select_start)
} else {
mBtnSwitch.setBackgroundResource(R.drawable.select_pause)
mGameState = GameStateEnum.PAUSE
}
// 更新游戏状态
mIKeyData.gameState(mGameState)
}
// 将方向传到背景视图中
mIKeyData.direction(mDirection)
}
}
|
final-test1/app/src/main/java/com/yunyan/snake/ui/widget/KeyView.kt
|
4150673559
|
package com.yunyan.snake.ui.widget
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.os.Handler
import android.os.Message
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.FrameLayout
import androidx.appcompat.app.AlertDialog
import com.yunyan.snake.R
import com.yunyan.snake.dao.RankingDBManager
import com.yunyan.snake.dao.UserDao
import com.yunyan.snake.ui.activity.IScore
import java.util.*
/**
* @author: YunYan
* @description: 贪吃蛇背景
* @date:2021/8/12
*/
class BackgroundView(context: Context, attributeSet: AttributeSet) : View(context, attributeSet) {
private lateinit var mPaintHead: Paint
private lateinit var mPaintBody: Paint
private lateinit var mPaintFood: Paint
/**
* 默认蛇身长度
*/
private val DEFAULT_LENGTH = 2
/**
* 蛇整体长度
*/
private var mSnakeLength = DEFAULT_LENGTH
/**
* 最大蛇身长度
*/
private val MAX_LENGTH = 1000 + DEFAULT_LENGTH
private lateinit var mSnakeX: FloatArray
private lateinit var mSnakeY: FloatArray
private var mDirectionEnum = DirectionStateEnum.RIGHT
private var mGameState = GameStateEnum.STOP
private lateinit var mIKeyData: IKeyData
private var mFoodX = 0f
private var mFoodY = 0f
private lateinit var mIScore: IScore
// 得分
private var mScore = 0
init {
init()
}
private fun init() {
initPaint()
initData()
moveSnake()
}
/**
* 初始化画笔
*/
private fun initPaint() {
mPaintHead = Paint()
mPaintBody = Paint()
mPaintFood = Paint()
mPaintHead.isAntiAlias = true
mPaintBody.isAntiAlias = true
mPaintFood.isAntiAlias = true
mPaintHead.color = resources.getColor(R.color.head, null)
mPaintBody.color = resources.getColor(R.color.body, null)
mPaintFood.color = resources.getColor(R.color.food, null)
}
/**
* 初始化蛇与食物
*/
private fun initData() {
mSnakeX = FloatArray(MAX_LENGTH + 1)
mSnakeY = FloatArray(MAX_LENGTH + 1)
mSnakeX[0] = 750f
mSnakeY[0] = 500f
mFoodX = 25 * Random().nextInt(15).toFloat()
mFoodY = 25 * Random().nextInt(15).toFloat()
}
/**
* 移动蛇
*/
private fun moveSnake() {
@SuppressLint("HandlerLeak") val mHandler: Handler = object : Handler() {
override fun handleMessage(msg: Message) {
if (msg.what == 99 && mGameState === GameStateEnum.START) {
judgmentDirection()
invalidate()
}
}
}
// 定时器,每隔 0.1s向 handler 发送消息
Timer().schedule(object : TimerTask() {
override fun run() {
val message = Message()
message.what = 99
mHandler.sendMessage(message)
}
}, 0, 100)
}
fun setIKeyData(iKeyData: IKeyData) {
this.mIKeyData = iKeyData
}
fun setIScore(mIScore: IScore?) {
this.mIScore = mIScore!!
}
fun setGameState(gameStateEnum: GameStateEnum) {
this.mGameState = gameStateEnum
}
/**
* 游戏失败
*/
private fun gameOver(message: String) {
dialog("遊戲結束!", message)
gameEnd()
}
/**
* 游戏通关
*/
private fun gameClearance() {
dialog("遊戲通關!", "恭喜你,遊戲通關!")
gameEnd()
}
private fun gameEnd() {
mGameState = GameStateEnum.STOP
mDirectionEnum = DirectionStateEnum.RIGHT
mIKeyData.gameState(mGameState)
mSnakeLength = DEFAULT_LENGTH
mSnakeX[0] = 750f
mSnakeY[0] = 500f
initData()
invalidate()
}
private fun dialog(title: String, message: String) {
val builder = AlertDialog.Builder(
context
)
val edt = EditText(context)
edt.hint = "請輸入用戶名"
edt.isSingleLine = true
val container = FrameLayout(context)
val params = FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
params.setMargins(60, 0, 60, 0)
edt.layoutParams = params
container.addView(edt)
builder.setTitle(title)
.setMessage("$message\n本局得分:$mScore")
.setView(container)
.setPositiveButton(R.string.dialog_positive) { dialog, id ->
gameEnd()
RankingDBManager.getInstance(context).insert(UserDao(edt.text.toString(), mScore))
dialog.dismiss()
}
.show()
}
/**
* 设置蛇头方向
*/
fun setDirection(directionState: DirectionStateEnum) {
if (isDirectionContrary(directionState)) {
gameOver("方向相反,遊戲失敗!")
}
if (mGameState == GameStateEnum.START) {
this.mDirectionEnum = directionState
}
}
/**
* 判断按键方向是否与所前进方向相反
*/
private fun isDirectionContrary(directionState: DirectionStateEnum): Boolean {
when (directionState) {
DirectionStateEnum.UP -> {
if (this.mDirectionEnum == DirectionStateEnum.DOWN) return true
}
DirectionStateEnum.DOWN -> {
if (this.mDirectionEnum == DirectionStateEnum.UP) return true
}
DirectionStateEnum.LEFT -> {
if (this.mDirectionEnum == DirectionStateEnum.RIGHT) return true
}
DirectionStateEnum.RIGHT -> {
if (this.mDirectionEnum == DirectionStateEnum.LEFT) return true
}
}
return false
}
/**
* 判断蛇头方向
*/
private fun judgmentDirection() {
when (mDirectionEnum) {
DirectionStateEnum.UP -> {
// 超过屏幕上侧,从下恻出
mSnakeY[0] = mSnakeY[0] - 25
if (mSnakeY[1] <= 0) mSnakeY[0] = measuredHeight.toFloat()
}
DirectionStateEnum.DOWN -> {
// 超过屏幕下侧,从上恻出
mSnakeY[0] = mSnakeY[0] + 25
if (mSnakeY[0] > measuredHeight) mSnakeY[0] = 0f
}
DirectionStateEnum.LEFT -> {
// 超过屏幕左侧,从右恻出
mSnakeX[0] = mSnakeX[0] - 25
if (mSnakeX[1] <= 0) mSnakeX[0] = measuredWidth.toFloat()
}
DirectionStateEnum.RIGHT -> {
// 超过屏幕右侧,从左恻出
mSnakeX[0] = mSnakeX[0] + 25
if (mSnakeX[0] > measuredWidth) mSnakeX[0] = 0f
}
}
}
override fun onDraw(canvas: Canvas?) {
if (mGameState == GameStateEnum.START) {
// 判断是否吃到食物
if ((mSnakeX[0] in mFoodX - 15..mFoodX + 15) && (mSnakeY[0] in mFoodY - 15..mFoodY + 15)) {
mFoodX = 25 * Random().nextInt(measuredWidth / 25).toFloat()
mFoodY = 25 * Random().nextInt(measuredHeight / 25).toFloat()
mSnakeLength++
// 计分
mScore = mSnakeLength - DEFAULT_LENGTH
// 刷新分数
mIScore.refreshScore(mScore)
// 分数等于最大长度则游戏通关
if (mScore == MAX_LENGTH - DEFAULT_LENGTH) {
gameClearance()
}
}
// 绘制蛇身
for (i in mSnakeLength downTo 1) {
if (mSnakeX[0] == mSnakeX[i] && mSnakeY[0] == mSnakeY[i]) {
gameOver("咬到自己,遊戲失敗!")
}
mSnakeX[i] = mSnakeX[i - 1]
mSnakeY[i] = mSnakeY[i - 1]
canvas?.drawOval(
mSnakeX[i],
mSnakeY[i],
mSnakeX[i] + 25,
mSnakeY[i] + 25,
mPaintBody
)
}
} else {
canvas?.drawOval(
mSnakeX[0],
mSnakeY[0],
mSnakeX[0] - 25,
mSnakeY[0] + 25,
mPaintBody
)
}
// 绘制蛇头
canvas?.drawRect(mSnakeX[0], mSnakeY[0], mSnakeX[0] + 25, mSnakeY[0] + 25, mPaintHead)
// 绘制食物
canvas?.drawOval(mFoodX, mFoodY, mFoodX + 25, mFoodY + 25, mPaintFood)
}
}
|
final-test1/app/src/main/java/com/yunyan/snake/ui/widget/BackgroundView.kt
|
1145439939
|
package com.yunyan.snake.ui.widget
/**
* @author: YunYan
* @description: 游戏状态
* @date:2021/8/12
*/
enum class GameStateEnum {
START,
PAUSE,
STOP
}
|
final-test1/app/src/main/java/com/yunyan/snake/ui/widget/GameStateEnum.kt
|
17717933
|
package com.yunyan.snake.ui.activity
import android.os.Bundle
import android.view.View
import android.widget.CompoundButton
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SwitchCompat
import com.yunyan.snake.ui.widget.DirectionStateEnum
import com.yunyan.snake.ui.widget.GameStateEnum
import com.yunyan.snake.R
import com.yunyan.snake.utils.MusicUtils
import com.yunyan.snake.utils.SpUtils
import com.yunyan.snake.ui.widget.BackgroundView
import com.yunyan.snake.ui.widget.IKeyData
import com.yunyan.snake.ui.widget.KeyView
/**
* 游戏界面
*/
class GameActivity : AppCompatActivity(), IKeyData,
IScore {
private lateinit var mKeyView: KeyView
private lateinit var mBackgroundView: BackgroundView
private lateinit var mTvScore: TextView
private lateinit var switchMusic: SwitchCompat
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_game)
initView()
}
private fun initView() {
mKeyView = findViewById(R.id.atyMain_kv)
mBackgroundView = findViewById(R.id.atyMain_bgv)
mTvScore = findViewById(R.id.atyGame_tv_score)
switchMusic = findViewById(R.id.atyMain_switch_music)
mKeyView.setIKeyData(this)
mBackgroundView.setIKeyData(this)
mBackgroundView.setIScore(this)
setScore(0)
// playMusic()
}
private fun playMusic() {
val isPlay: Boolean = SpUtils.getInstance(this).getBoolean("isPlay", false)
switchMusic.isChecked = isPlay
if (isPlay) {
// MusicUtils.playSound(this, R.raw.music)
}
switchMusic.setOnCheckedChangeListener { buttonView: CompoundButton, isChecked: Boolean ->
if (isChecked) {
// MusicUtils.playSound(buttonView.context, R.raw.music)
} else {
MusicUtils.release()
}
SpUtils.getInstance(buttonView.context).put("isPlay", isChecked)
}
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus)
hideSystemUI()
}
/**
* 隐藏状态栏
*/
private fun hideSystemUI() {
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
}
private fun setScore(score: Int) {
val s = getString(R.string.game_tv_score, score.toString())
mTvScore.setText(s)
}
override fun gameState(gameState: GameStateEnum) {
if (gameState == GameStateEnum.STOP) {
mKeyView.gameOver()
setScore(0)
} else {
mBackgroundView.setGameState(gameState)
}
}
override fun direction(directionState: DirectionStateEnum) {
mBackgroundView.setDirection(directionState)
}
override fun refreshScore(score: Int) {
setScore(score)
}
override fun onPause() {
MusicUtils.pause()
super.onPause()
}
override fun onStart() {
MusicUtils.start()
super.onStart()
}
override fun onDestroy() {
MusicUtils.release()
super.onDestroy()
}
}
|
final-test1/app/src/main/java/com/yunyan/snake/ui/activity/GameActivity.kt
|
3080473733
|
package com.yunyan.snake.ui.activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.yunyan.snake.R
/**
* 主界面
*/
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btnStart = findViewById<Button>(R.id.atyMain_btn_start)
val btnRanking = findViewById<Button>(R.id.atyMain_btn_ranking)
btnStart.setOnClickListener { v: View? ->
toActivity(
GameActivity::class.java
)
}
btnRanking.setOnClickListener { v: View? ->
toActivity(
RankingActivity::class.java
)
}
}
private fun toActivity(cls: Class<out AppCompatActivity?>) {
val intent = Intent(this, cls)
startActivity(intent)
}
}
|
final-test1/app/src/main/java/com/yunyan/snake/ui/activity/MainActivity.kt
|
322766783
|
package com.yunyan.snake.ui.activity
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.yunyan.snake.R
import com.yunyan.snake.adapter.RankingAdapter
import com.yunyan.snake.dao.RankingDBManager
import com.yunyan.snake.dao.UserDao
/**
* 排行榜界面
*/
class RankingActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_ranking)
val ranking = findViewById<RecyclerView>(R.id.atyRanking_rv)
val list: List<UserDao> = RankingDBManager.getInstance(this).query()
val rankingAdapter = RankingAdapter(list)
ranking.layoutManager = LinearLayoutManager(this)
ranking.adapter = rankingAdapter
}
}
|
final-test1/app/src/main/java/com/yunyan/snake/ui/activity/RankingActivity.kt
|
1408535854
|
package com.yunyan.snake.dao
import android.content.Context
/**
* 数据库工具类
*/
class RankingDBManager private constructor() {
companion object {
private val instance = RankingDBManager()
private var mDB: MyDBOpenHelper? = null
fun getInstance(context: Context?): RankingDBManager {
if (mDB == null) {
mDB = MyDBOpenHelper(context)
}
return instance
}
}
/**
* 插入数据
*/
fun insert(userDao: UserDao) {
val db = mDB!!.writableDatabase
val sql = "INSERT INTO ranking(name,score) VALUES(?,?)"
db.execSQL(
sql, arrayOf<Any>(userDao.name, userDao.score)
)
db.close()
}
/**
* 查询数据
*/
fun query(): List<UserDao> {
val db = mDB!!.readableDatabase
// 进行数据查询并按照分数降序排序
val sql = "SELECT * FROM ranking ORDER BY score DESC"
val cursor = db.rawQuery(sql, null)
val list: MutableList<UserDao> = ArrayList()
if (cursor.count > 0) {
cursor.moveToFirst()
for (i in 0 until cursor.count) {
val name = cursor.getString(cursor.getColumnIndexOrThrow("name"))
val score = cursor.getInt(cursor.getColumnIndexOrThrow("score"))
list.add(UserDao(name, score))
cursor.moveToNext()
}
}
cursor.close()
db.close()
return list
}
}
|
final-test1/app/src/main/java/com/yunyan/snake/dao/RankingDBManager.kt
|
1927054275
|
package com.yunyan.snake.dao
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
/**
* 数据库帮助类
*/
class MyDBOpenHelper(context: Context?) :
SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
companion object {
private const val DATABASE_NAME = "snake.db"
private const val DATABASE_VERSION = 1
}
override fun onCreate(db: SQLiteDatabase) {
val sql =
"CREATE TABLE ranking(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,name VARCHAR(20) NOT NULL,score INTEGER NOT NULL)"
db.execSQL(sql)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {}
}
|
final-test1/app/src/main/java/com/yunyan/snake/dao/MyDBOpenHelper.kt
|
1463061702
|
package com.yunyan.snake.dao
data class UserDao(var name: String, var score: Int)
|
final-test1/app/src/main/java/com/yunyan/snake/dao/UserDao.kt
|
1957263961
|
package com.yunyan.snake.utils
import android.content.Context
import android.widget.Toast
/**
* Toast 工具类
*/
object ToastUtils {
private var toast: Toast? = null
fun showToast(context: Context?, text: String?) {
if (toast != null) {
toast!!.cancel()
toast = null
}
toast = Toast.makeText(context, text, Toast.LENGTH_SHORT)
toast!!.show()
}
}
|
final-test1/app/src/main/java/com/yunyan/snake/utils/ToastUtils.kt
|
94037881
|
package com.yunyan.snake.utils
import android.content.Context
import android.media.MediaPlayer
/**
* 音乐播放工具类
*/
object MusicUtils {
private var mPlayer: MediaPlayer? = null
private var isPause = false
fun playSound(context: Context?, rawResId: Int) {
release()
mPlayer = MediaPlayer.create(context, rawResId)
mPlayer!!.start()
}
fun pause() {
if (mPlayer != null && mPlayer!!.isPlaying) {
mPlayer!!.pause()
isPause = true
}
}
fun start() {
if (mPlayer != null && isPause) {
mPlayer!!.start()
isPause = false
}
}
fun release() {
if (mPlayer != null) {
mPlayer!!.release()
mPlayer = null
}
}
}
|
final-test1/app/src/main/java/com/yunyan/snake/utils/MusicUtils.kt
|
3757473008
|
package com.yunyan.snake.utils
import android.content.Context
import android.content.SharedPreferences
/**
* SharedPreferences 工具类
*/
class SpUtils private constructor() {
companion object {
private const val SP = "data"
private val instance = SpUtils()
private var mSp: SharedPreferences? = null
fun getInstance(context: Context): SpUtils {
if (mSp == null) {
mSp = context.getSharedPreferences(SP, Context.MODE_PRIVATE)
}
return instance
}
}
fun put(key: String?, value: Any?) {
val edit = mSp!!.edit()
if (value is String) {
edit.putString(key, value as String?)
} else if (value is Boolean) {
edit.putBoolean(key, (value as Boolean?)!!)
} else if (value is Int) {
edit.putInt(key, (value as Int?)!!)
}
edit.apply()
}
fun getString(key: String?, defValue: String?): String? {
return mSp!!.getString(key, defValue)
}
fun getBoolean(key: String?, defValue: Boolean): Boolean {
return mSp!!.getBoolean(key, defValue)
}
fun getInt(key: String?, defValue: Int): Int {
return mSp!!.getInt(key, defValue)
}
}
|
final-test1/app/src/main/java/com/yunyan/snake/utils/SpUtils.kt
|
3462735765
|
package com.yunyan.snake.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.yunyan.snake.R
import com.yunyan.snake.dao.UserDao
/**
* 排行榜 RecyclerView 适配器
*/
class RankingAdapter(mList: List<UserDao>) : RecyclerView.Adapter<RankingAdapter.ViewHolder?>() {
private val mList: List<UserDao>
init {
this.mList = mList
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view: View = LayoutInflater.from(parent.context)
.inflate(R.layout.item_rv_ranking, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.tvName.text = mList[position].name
holder.tvScore.text = mList[position].score.toString()
val score = position + 1
holder.tvRanking.text = score.toString()
}
override fun getItemCount(): Int {
return mList.size
}
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val tvName: TextView
val tvScore: TextView
val tvRanking: TextView
init {
tvName = view.findViewById<View>(R.id.itemRv_ranking_name) as TextView
tvScore = view.findViewById<View>(R.id.itemRv_ranking_score) as TextView
tvRanking = view.findViewById<View>(R.id.itemRv_ranking_ranking) as TextView
}
}
}
|
final-test1/app/src/main/java/com/yunyan/snake/adapter/RankingAdapter.kt
|
2979935457
|
package jlin2.examples.localtesting
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("jlin2.examples.localtesting", appContext.packageName)
}
}
|
LocalTesting/app/src/androidTest/java/jlin2/examples/localtesting/ExampleInstrumentedTest.kt
|
62473925
|
package jlin2.examples.localtesting
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)
}
}
|
LocalTesting/app/src/test/java/jlin2/examples/localtesting/ExampleUnitTest.kt
|
197662779
|
package jlin2.examples.localtesting
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
}
}
|
LocalTesting/app/src/main/java/jlin2/examples/localtesting/MainActivity.kt
|
1576874082
|
package jlin2.examples.localtesting
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class EmailValidatorTest {
@Test
fun testValidEmail() {
assertTrue(EmailValidator.isValidEmail("[email protected]"))
assertTrue(EmailValidator.isValidEmail("[email protected]"))
}
@Test
fun testInvalidEmail() {
assertFalse(EmailValidator.isValidEmail("123@abc"))
assertFalse(EmailValidator.isValidEmail("[email protected]"))
assertFalse(EmailValidator.isValidEmail("@abc.com"))
assertFalse(EmailValidator.isValidEmail("testing123"))
assertFalse(EmailValidator.isValidEmail(""))
assertFalse(EmailValidator.isValidEmail(null))
}
}
|
LocalTesting/app/src/main/java/jlin2/examples/localtesting/EmailValidatorTest.kt
|
4092516058
|
package jlin2.examples.localtesting
import android.text.Editable
import android.text.TextWatcher
import java.util.regex.Pattern
/**
* An Email format validator for [android.widget.EditText].
*/
class EmailValidator : TextWatcher {
internal var isValid = false
override fun afterTextChanged(editableText: Editable) {
isValid = isValidEmail(editableText)
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) = Unit
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) = Unit
companion object {
/**
* Email validation pattern.
*/
private val EMAIL_PATTERN = Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\@" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+"
)
/**
* Validates if the given input is a valid email address.
*
* @param email The email to validate.
* @return `true` if the input is a valid email, `false` otherwise.
*/
fun isValidEmail(email: CharSequence?): Boolean {
println(email != null && EMAIL_PATTERN.matcher(email).matches())
return email != null && EMAIL_PATTERN.matcher(email).matches()
}
}
}
|
LocalTesting/app/src/main/java/jlin2/examples/localtesting/EmailValidator.kt
|
2986351018
|
package com.assignment.firebaseauthentication
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.assignment.firebaseauthentication", appContext.packageName)
}
}
|
Firebase_Authentication/app/src/androidTest/java/com/assignment/firebaseauthentication/ExampleInstrumentedTest.kt
|
2408059975
|
package com.assignment.firebaseauthentication
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)
}
}
|
Firebase_Authentication/app/src/test/java/com/assignment/firebaseauthentication/ExampleUnitTest.kt
|
3872001523
|
package com.assignment.firebaseauthentication
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
|
Firebase_Authentication/app/src/main/java/com/assignment/firebaseauthentication/MainActivity.kt
|
4241411011
|
package com.assignment.firebaseauthentication
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
class LogIn : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
private lateinit var emailEt: EditText
private lateinit var passET: EditText
private lateinit var button: Button
private lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_log_in)
// Initialize Firebase Auth
auth = FirebaseAuth.getInstance()
// Find view references
emailEt = findViewById(R.id.emailEt)
passET = findViewById(R.id.passET)
button = findViewById(R.id.button)
textView = findViewById(R.id.textView)
// Login Button Click Listener
button.setOnClickListener {
val email = emailEt.text.toString().trim()
val password = passET.text.toString().trim()
// Validate user input (empty fields)
if (email.isEmpty()) {
Toast.makeText(this, "Please enter your email", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
if (password.isEmpty()) {
Toast.makeText(this, "Please enter your password", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
// Sign in user with email and password
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Login successful, navigate to another activity (replace with your logic)
Toast.makeText(this, "Login successful!", Toast.LENGTH_SHORT).show()
startActivity(Intent(this, MainActivity::class.java))
// Your logic after successful login (e.g., navigate to Home activity)
} else {
Toast.makeText(this, "Login failed: ${task.exception?.message}", Toast.LENGTH_SHORT).show()
}
}
}
// Navigate to Signup Activity on Textview Click
textView.setOnClickListener {
val intent = Intent(this, SignUp::class.java) // Replace with your Signup activity class name
startActivity(intent)
}
}
}
|
Firebase_Authentication/app/src/main/java/com/assignment/firebaseauthentication/LogIn.kt
|
2418257734
|
package com.assignment.firebaseauthentication
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
class SignUp : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
private lateinit var emailEt: EditText
private lateinit var passET: EditText
private lateinit var confirmPassEt: EditText
private lateinit var button: Button
private lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sign_up)
// Initialize Firebase Auth
auth = FirebaseAuth.getInstance()
// Find view references
emailEt = findViewById(R.id.emailEt)
passET = findViewById(R.id.passET)
confirmPassEt = findViewById(R.id.confirmPassEt)
button = findViewById(R.id.button)
textView = findViewById(R.id.textView)
// Signup Button Click Listener
button.setOnClickListener {
val email = emailEt.text.toString().trim()
val password = passET.text.toString().trim()
val confirmPassword = confirmPassEt.text.toString().trim()
// Validate user input (empty fields, password match)
if (email.isEmpty()) {
Toast.makeText(this, "Please enter your email", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
if (password.isEmpty()) {
Toast.makeText(this, "Please enter your password", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
if (confirmPassword != password) {
Toast.makeText(this, "Passwords do not match", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
// Create a new user with email and password
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign up successful, navigate to another activity (replace with your logic)
Toast.makeText(this, "Registration successful!", Toast.LENGTH_SHORT).show()
// Your logic after successful registration (e.g., navigate to Home activity)
} else {
Toast.makeText(this, "Registration failed: ${task.exception?.message}", Toast.LENGTH_SHORT).show()
}
}
}
// Navigate to Login Activity on Textview Click
textView.setOnClickListener {
val intent = Intent(this, LogIn::class.java) // Replace with your Login activity class name
startActivity(intent)
}
}
}
|
Firebase_Authentication/app/src/main/java/com/assignment/firebaseauthentication/SignUp.kt
|
3779590355
|
package wioleta.wrobel.memoriesapp
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("wioleta.wrobel.memoriesapp", appContext.packageName)
}
}
|
Memories-App/app/src/androidTest/java/wioleta/wrobel/memoriesapp/ExampleInstrumentedTest.kt
|
71890519
|
package wioleta.wrobel.memoriesapp
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() {
//given
var json = "[{\"memoryDate\":\"2023-12-21\",\"memoryTitle\":\"tak\",\"memoryDescription\":\"ghgh\",\"memoryImage\":\"content://media/picker/0/com.android.providers.media.photopicker/media/1000000019\",\"cardColorType\":\"BLUE\",\"fontColorType\":\"GREEN\",\"fontType\":\"BERKSHIRE\"},{\"memoryDate\":\"2023-12-23\",\"memoryTitle\":\"test\",\"memoryDescription\":\"zdjecie\",\"memoryImage\":\"content://media/picker/0/com.android.providers.media.photopicker/media/1000000019\",\"cardColorType\":\"PINK\",\"fontColorType\":\"GREEN\",\"fontType\":\"YESEVA\"},{\"memoryDate\":\"2023-12-23\",\"memoryTitle\":\"bmnowe\",\"memoryDescription\":\"chjnn\",\"memoryImage\":\"content://media/picker/0/com.android.providers.media.photopicker/media/1000000018\",\"cardColorType\":\"PINK\",\"fontColorType\":\"GREY\",\"fontType\":\"LOBSTER\"},{\"memoryDate\":\"2023-12-23\",\"memoryTitle\":\"nowe\",\"memoryDescription\":\"ghjj\",\"memoryImage\":\"content://media/picker/0/com.android.providers.media.photopicker/media/1000000019\",\"cardColorType\":\"GREEN\",\"fontColorType\":\"GREY\",\"fontType\":\"LOBSTER\"},{\"memoryDate\":\"2023-12-28\",\"memoryTitle\":\"gh\",\"memoryDescription\":\"gh\",\"memoryImage\":\"content://media/picker/0/com.android.providers.media.photopicker/media/1000000019\",\"cardColorType\":\"PINK\",\"fontColorType\":\"PINK\",\"fontType\":\"YESEVA\"}]"
//
var jsonConverter = wioleta.wrobel.memoriesapp.util.JsonConverter
var result = jsonConverter.memoryListFromJson(json)
assertEquals(5, result.count())
assertTrue(result.first().memoryImage.isNotEmpty())
}
}
|
Memories-App/app/src/test/java/wioleta/wrobel/memoriesapp/ExampleUnitTest.kt
|
3534266330
|
package wioleta.wrobel.memoriesapp.ViewModel
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import wioleta.wrobel.memoriesapp.model.Memory
class MemoriesAppViewModel() : ViewModel() {
private val _uiState = MutableStateFlow(MemoriesAppUiState())
val uiState: StateFlow<MemoriesAppUiState> = _uiState
fun navigateToSingleMemory(currentMemory: Memory) {
_uiState.update {
it.copy(isCardClicked = true, memory = currentMemory)
}
}
fun navigateToMemoryList() {
_uiState.update {
it.copy(isCardClicked = false)
}
}
}
data class MemoriesAppUiState(
// val memoriesList: List <Memory> = emptyList(),
// val memoriesListLength: Int = 0,
val memory: Memory? = null,
val isCardClicked: Boolean = false,
// val currentCardColor: MemoryCardColors = MemoryCardColors.values().first(),
// val currentFontFamily: MemoryFontFamily = MemoryFontFamily.values().first(),
// val currentFontColor: MemoryFontColor = MemoryFontColor.values().first()
)
|
Memories-App/app/src/main/java/wioleta/wrobel/memoriesapp/ViewModel/MemoriesAppViewModel.kt
|
3130930468
|
package wioleta.wrobel.memoriesapp.ui.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Shapes
import androidx.compose.ui.unit.dp
val Shapes = Shapes(
large = RoundedCornerShape(
bottomStart = 5.dp,
topEnd = 5.dp,
bottomEnd = 5.dp,
topStart = 5.dp
),
)
|
Memories-App/app/src/main/java/wioleta/wrobel/memoriesapp/ui/theme/Shape.kt
|
744879110
|
package wioleta.wrobel.memoriesapp.ui.theme
import androidx.compose.ui.graphics.Color
val primary_color_light = Color(0xFF9a82f5)
val surface_color_light = Color.White
val secondary_color_light = Color(0xFFFDEBED)
val tertiary_color_light = Color(0xFFBEEBE9)
val card_color_pink = Color(0xFFfcdeea)
val card_color_green = Color(0xFFBEEBE9)
val card_color_blue = Color(0xFF92f4fc)
val card_color_yellow = Color(0xFFfcfce6)
val card_color_grey = Color(0xFFd5e0e6)
val font_color_grey = Color(0xFF898AA6)
val font_color_blue = Color(0xFF6886C5)
val font_color_green = Color(0xFF5AA469)
val font_color_pink = Color(0xFFED5AB3)
|
Memories-App/app/src/main/java/wioleta/wrobel/memoriesapp/ui/theme/Color.kt
|
2241223852
|
package wioleta.wrobel.memoriesapp.ui.theme
import android.app.Activity
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
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.LocalView
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.core.view.WindowCompat
import wioleta.wrobel.memoriesapp.R
private val DarkColorScheme = darkColorScheme(
primary = primary_color_light,
secondary = secondary_color_light,
tertiary = tertiary_color_light,
surface = surface_color_light,
)
private val LightColorScheme = lightColorScheme(
primary = primary_color_light,
secondary = secondary_color_light,
tertiary = tertiary_color_light,
)
val font_main_galada = FontFamily(Font(R.font.galada_regular))
val font_yeseva_one = FontFamily(Font(R.font.yeseva_one_regular))
val font_berkshire_swash = FontFamily(Font(R.font.berkshire_swash_regular))
val font_playball = FontFamily(Font(R.font.playball_regular))
val font_lobster = FontFamily(Font(R.font.lobster_regular))
@Composable
fun MemoriesAppTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
val colorScheme = when {
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.surface.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content,
shapes = Shapes
)
}
|
Memories-App/app/src/main/java/wioleta/wrobel/memoriesapp/ui/theme/Theme.kt
|
3366718532
|
package wioleta.wrobel.memoriesapp.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
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 = font_main_galada,
fontWeight = FontWeight.Normal,
fontSize = 36.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
),
labelMedium = TextStyle(
fontWeight = FontWeight.Normal,
fontSize = 20.sp,
fontFamily = font_lobster,
color = primary_color_light
),
labelSmall = TextStyle(
fontFamily = font_lobster,
fontWeight = FontWeight.Normal,
fontSize = 14.sp
)
)
|
Memories-App/app/src/main/java/wioleta/wrobel/memoriesapp/ui/theme/Type.kt
|
1742779708
|
package wioleta.wrobel.memoriesapp.database
import com.maxkeppeker.sheets.core.models.base.rememberSheetState
object DataPicker {
}
|
Memories-App/app/src/main/java/wioleta/wrobel/memoriesapp/database/DataPicker.kt
|
1049475924
|
package wioleta.wrobel.memoriesapp
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
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.Spacer
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.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
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.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.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.net.toUri
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage
import wioleta.wrobel.memoriesapp.ViewModel.MemoriesAppViewModel
import wioleta.wrobel.memoriesapp.model.Memory
import wioleta.wrobel.memoriesapp.ui.theme.MemoriesAppTheme
import wioleta.wrobel.memoriesapp.util.StorageOperation
class MainActivity : ComponentActivity() {
private var memoriesList = mutableListOf<Memory>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
memoriesList = StorageOperation.readMemoryList(this).toMutableList()
val memory = intent.getSerializableExtra("memory") as? Memory
memory?.let {
memoriesList.add(it)
StorageOperation.writeMemoryList(this, memoriesList)
}
setContent {
MemoriesAppTheme {
Surface {
MainScreen()
}
}
}
}
@Composable
fun MainScreen() {
val context: Context = LocalContext.current
val memoriesListLength by remember { mutableStateOf(memoriesList.size) }
if (memoriesListLength > 0) {
DisplayMemoriesScreen(context)
} else {
MainScreenFirstTimeRunningApp(context)
}
}
@Composable
fun MainScreenFirstTimeRunningApp(context: Context) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxSize()
) {
Text(
text = stringResource(id = R.string.add_first_memory),
color = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.height(12.dp))
FloatingActionButton(
containerColor = MaterialTheme.colorScheme.tertiary,
onClick = {
val intent = Intent(context, AddMemoryActivity::class.java)
startActivity(intent)
}
) {
Icon(
imageVector = Icons.Filled.Add,
contentDescription = "add_icon",
tint = MaterialTheme.colorScheme.surface,
modifier = Modifier.size(30.dp)
)
}
}
}
@Composable
fun DisplayMemoriesScreen(
context: Context,
) {
val viewModel: MemoriesAppViewModel = viewModel()
val uiState by viewModel.uiState.collectAsState()
Column(
modifier = Modifier
.fillMaxSize()
.padding(15.dp)
) {
if (!uiState.isCardClicked) {
DisplayTitle()
}
Box(modifier = Modifier.fillMaxSize()) {
DisplayMemoriesListOrSingleMemory(memoriesList = memoriesList)
if (!uiState.isCardClicked) {
FloatingActionButton(
containerColor = MaterialTheme.colorScheme.primary,
modifier = Modifier.align(Alignment.BottomCenter),
onClick = {
val intent = Intent(context, AddMemoryActivity::class.java)
startActivity(intent)
finish()
}
) {
Icon(
imageVector = Icons.Filled.Add,
contentDescription = "add icon",
tint = MaterialTheme.colorScheme.surface,
modifier = Modifier.size(25.dp)
)
}
}
}
}
}
@Composable
private fun DisplayTitle() {
Box(
modifier = Modifier
.fillMaxWidth()
.height(100.dp)
) {
Text(
text = stringResource(id = R.string.memories_list),
modifier = Modifier.align(Alignment.Center),
color = MaterialTheme.colorScheme.primary
)
IconButton(
onClick = { /*TODO*/ },
modifier = Modifier.align(Alignment.BottomEnd)
) {
Icon(
painter = painterResource(id = R.drawable.filter_list),
contentDescription = "filter icon",
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(35.dp)
)
}
}
}
@Composable
fun DisplayMemoriesListOrSingleMemory(
memoriesList: List<Memory>,
) {
val viewModel: MemoriesAppViewModel = viewModel()
val uiState by viewModel.uiState.collectAsState()
if (!uiState.isCardClicked) {
LazyColumn() {
items(memoriesList) { memory ->
Card(
modifier = Modifier
.padding(top = 10.dp)
.height(100.dp)
.clickable {
viewModel.navigateToSingleMemory(memory)
},
colors = CardDefaults.cardColors(containerColor = memory.cardColorType.color),
) {
Box(
modifier = Modifier
.fillMaxSize()
.padding(10.dp)
) {
Column(
modifier = Modifier
.align(Alignment.CenterStart)
.padding(4.dp)
) {
Text(
text = memory.memoryDate,
fontFamily = memory.fontType.font,
fontSize = 16.sp,
color = memory.fontColorType.color,
overflow = TextOverflow.Ellipsis,
)
Spacer(modifier = Modifier.height(2.dp))
Text(
text = memory.memoryTitle,
fontFamily = memory.fontType.font,
fontSize = 24.sp,
fontWeight = FontWeight.Bold,
color = memory.fontColorType.color,
)
}
Icon(
imageVector = Icons.Filled.Close,
contentDescription = "clear_icon",
modifier = Modifier
.align(Alignment.TopEnd)
.clickable { StorageOperation },
tint = Color.White
)
Icon(
imageVector = Icons.Filled.Edit,
contentDescription = "edit_icon",
modifier = Modifier
.align(Alignment.BottomEnd)
.clickable { },
tint = Color.White
)
}
}
}
}
} else {
DisplaySingleMemory(currentMemory = uiState.memory)
}
}
@Composable
fun DisplaySingleMemory(currentMemory: Memory?) {
LocalContext.current
val imageToDisplay = currentMemory?.memoryImage?.toUri()
if (currentMemory != null) {
Card(
modifier = Modifier
.fillMaxSize()
.padding(15.dp),
colors = CardDefaults.cardColors(containerColor = currentMemory.cardColorType.color)
) {
Column(modifier = Modifier.padding(18.dp)) {
Box(
modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.TopEnd
) {
Text(
text = currentMemory.memoryDate,
fontFamily = currentMemory.fontType.font,
color = currentMemory.fontColorType.color,
fontSize = 16.sp
)
}
Spacer(modifier = Modifier.height(15.dp))
Column(
Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Box(
modifier = Modifier
.padding(10.dp)
.fillMaxWidth()
.height(250.dp),
contentAlignment = Alignment.Center
)
{
LoadImageFromURi(imageToDisplay = imageToDisplay)
}
Spacer(modifier = Modifier.height(10.dp))
Text(
text = currentMemory.memoryTitle,
fontFamily = currentMemory.fontType.font,
color = currentMemory.fontColorType.color,
fontSize = 26.sp
)
Spacer(modifier = Modifier.height(10.dp))
Box(modifier = Modifier.fillMaxSize())
{
Text(
text = currentMemory.memoryDescription,
fontFamily = currentMemory.fontType.font,
color = currentMemory.fontColorType.color,
fontSize = 20.sp,
textAlign = TextAlign.Justify
)
}
}
}
}
} else { }
}
@Composable
fun LoadImageFromURi(imageToDisplay: Uri?) {
// if (imageToDisplay != null) {
// contentResolver.takePersistableUriPermission(
// imageToDisplay,
// Intent.FLAG_GRANT_READ_URI_PERMISSION
// )
// }
AsyncImage(
model = imageToDisplay,
contentDescription = "added photo",
contentScale = ContentScale.Crop
)
}
}
|
Memories-App/app/src/main/java/wioleta/wrobel/memoriesapp/MainActivity.kt
|
2205029997
|
package wioleta.wrobel.memoriesapp.util
import android.content.Context
import wioleta.wrobel.memoriesapp.model.Memory
object StorageOperation {
fun writeMemoryList(context: Context, memoryList: List<Memory>) {
val json = JsonConverter.memoryListToJason(memoryList)
val sharedPrefs = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE).edit()
sharedPrefs.putString(MEMORY_LIST_KEY, json)
sharedPrefs.apply()
}
fun readMemoryList(context: Context): List<Memory> {
val sharedPrefs = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE)
val json = sharedPrefs.getString(MEMORY_LIST_KEY, null)
return if (json != null) JsonConverter.memoryListFromJson(json) else emptyList()
}
fun readMemory(context: Context): Memory? {
val sharedPrefs = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE)
val json = sharedPrefs.getString(MEMORY_KEY, null)
return if ( json != null) JsonConverter.memoryFromJason(json) else null
}
fun writeMemory(context: Context, memory: Memory) {
val json = JsonConverter.memoryToJason(memory)
val sharedPrefs = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE).edit()
sharedPrefs.putString(MEMORY_KEY, json)
sharedPrefs.apply()
}
private const val SHARED_PREFS_NAME = "MEMORY_SHARED_PREFS"
private const val MEMORY_LIST_KEY = "MEMORY_LIST_KEY"
private const val MEMORY_KEY = "MEMORY_KEY"
}
|
Memories-App/app/src/main/java/wioleta/wrobel/memoriesapp/util/StorageOperation.kt
|
329948987
|
package wioleta.wrobel.memoriesapp.util
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import wioleta.wrobel.memoriesapp.model.Memory
object JsonConverter {
private val moshi = Moshi.Builder().build()
fun memoryToJason(memory: Memory): String {
val type = Memory::class.java
return moshi.adapter<Memory>(type).toJson(memory)
}
fun memoryFromJason(json: String): Memory? {
val type = Memory::class.java
return moshi.adapter<Memory>(type).fromJson(json)
}
fun memoryListToJason(memoryList: List<Memory>): String {
val type = Types.newParameterizedType(List::class.java, Memory::class.java)
return moshi.adapter<List<Memory>>(type).toJson(memoryList)
}
fun memoryListFromJson(json: String): List<Memory> {
val type = Types.newParameterizedType(List::class.java, Memory::class.java)
return moshi.adapter<List<Memory>>(type).fromJson(json) ?: emptyList()
}
}
|
Memories-App/app/src/main/java/wioleta/wrobel/memoriesapp/util/JsonConverter.kt
|
1827851391
|
package wioleta.wrobel.memoriesapp
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
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.saveable.rememberSaveable
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.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.maxkeppeker.sheets.core.models.base.rememberSheetState
import com.maxkeppeler.sheets.calendar.CalendarDialog
import com.maxkeppeler.sheets.calendar.models.CalendarConfig
import com.maxkeppeler.sheets.calendar.models.CalendarSelection
import com.maxkeppeler.sheets.calendar.models.CalendarStyle
import wioleta.wrobel.memoriesapp.model.Memory
import wioleta.wrobel.memoriesapp.model.MemoryCardColors
import wioleta.wrobel.memoriesapp.model.MemoryFontColor
import wioleta.wrobel.memoriesapp.model.MemoryFontFamily
import wioleta.wrobel.memoriesapp.ui.theme.MemoriesAppTheme
import wioleta.wrobel.memoriesapp.util.StorageOperation
import java.time.LocalDate
class AddMemoryActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MemoriesAppTheme {
Surface {
AddMemoryScreen()
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddMemoryScreen() {
val context = LocalContext.current
var memoryDate: LocalDate by rememberSaveable { mutableStateOf(LocalDate.now()) }
var memoryTitle by rememberSaveable { mutableStateOf("") }
var memoryDescription by rememberSaveable { mutableStateOf("") }
val cardColors = MemoryCardColors.values()
val fontColors = MemoryFontColor.values()
val fontsFamily = MemoryFontFamily.values()
var currentCardColor by rememberSaveable { mutableStateOf(cardColors.first()) }
var currentFontColor by rememberSaveable { mutableStateOf(fontColors.first()) }
var currentFontFamily by rememberSaveable { mutableStateOf(fontsFamily.first()) }
val textStyle: androidx.compose.ui.text.TextStyle = androidx.compose.ui.text.TextStyle(
fontWeight = FontWeight.Normal,
fontSize = 20.sp,
fontFamily = currentFontFamily.font,
color = currentFontColor.color
)
val scrollState = rememberScrollState()
val calendarState = rememberSheetState()
CalendarDialog(
state = calendarState,
config = CalendarConfig(
style = CalendarStyle.MONTH
),
selection = CalendarSelection.Date { date ->
memoryDate = date
})
var selectedImage by remember { mutableStateOf<Uri?>(null) }
val singlePhotoPickerLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.PickVisualMedia(),
onResult = { uri ->
val flag = Intent.FLAG_GRANT_WRITE_URI_PERMISSION
if (uri != null) {
context.contentResolver.takePersistableUriPermission(uri, flag)
selectedImage = uri
}
})
Card(
colors = CardDefaults.cardColors(currentCardColor.color),
modifier = Modifier
.fillMaxSize()
.padding(15.dp)
.verticalScroll(scrollState)
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 26.dp, vertical = 10.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(
text = stringResource(id = R.string.add_memory),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.primary
)
//Date type how to do it??
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth()
) {
OutlinedTextField(
value = memoryDate.toString(),
onValueChange = {},
enabled = false,
label = {
Text(
text = stringResource(id = R.string.memory_date),
style = MaterialTheme.typography.labelMedium,
textAlign = TextAlign.Center,
)
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
singleLine = true,
colors = TextFieldDefaults.outlinedTextFieldColors(
disabledBorderColor = MaterialTheme.colorScheme.primary,
textColor = Color.Gray
),
textStyle = textStyle,
modifier = Modifier
.height(66.dp)
.width(150.dp)
)
Spacer(modifier = Modifier.width(10.dp))
ElevatedButton(
onClick = { calendarState.show() },
colors = ButtonDefaults.buttonColors(MaterialTheme.colorScheme.primary),
shape = MaterialTheme.shapes.large,
modifier = Modifier.size(30.dp),
contentPadding = PaddingValues(1.dp)
) {
Icon(
imageVector = Icons.Filled.Add,
contentDescription = "add_icon",
tint = Color.White
)
}
}
Spacer(modifier = Modifier.height(5.dp))
OutlinedTextField(
value = memoryTitle,
onValueChange = { memoryTitle = it },
label = {
Text(
text = stringResource(id = R.string.memory_title),
style = MaterialTheme.typography.labelMedium,
)
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
singleLine = true,
colors = TextFieldDefaults.outlinedTextFieldColors(
unfocusedBorderColor = MaterialTheme.colorScheme.primary,
textColor = Color.Gray
),
textStyle = textStyle,
modifier = Modifier
.height(66.dp)
.fillMaxWidth()
)
Spacer(modifier = Modifier.height(5.dp))
OutlinedTextField(
value = memoryDescription,
onValueChange = { memoryDescription = it },
label = {
Text(
text = stringResource(id = R.string.memory_description),
style = MaterialTheme.typography.labelMedium,
)
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
colors = TextFieldDefaults.outlinedTextFieldColors(
unfocusedBorderColor = MaterialTheme.colorScheme.primary,
textColor = Color.Gray
),
textStyle = textStyle,
modifier = Modifier
.height(300.dp)
.fillMaxWidth()
)
Spacer(modifier = Modifier.height(5.dp))
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth()
) {
OutlinedTextField(
value = if (selectedImage == null) "" else selectedImage.toString(),
enabled = false,
onValueChange = {},
label = {
Text(
text = stringResource(id = R.string.add_image),
style = MaterialTheme.typography.labelMedium,
)
},
colors = TextFieldDefaults.outlinedTextFieldColors(
disabledBorderColor = MaterialTheme.colorScheme.primary,
textColor = Color.Gray
),
textStyle = textStyle,
modifier = Modifier
.height(66.dp)
.width(150.dp)
)
Spacer(modifier = Modifier.width(10.dp))
ElevatedButton(
onClick = {
singlePhotoPickerLauncher.launch(
PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
)
},
colors = ButtonDefaults.buttonColors(MaterialTheme.colorScheme.primary),
shape = MaterialTheme.shapes.large,
modifier = Modifier.size(30.dp),
contentPadding = PaddingValues(1.dp)
) {
Icon(
imageVector = Icons.Filled.Add,
contentDescription = "add_icon",
tint = Color.White
)
}
}
Spacer(modifier = Modifier.height(10.dp))
LazyRow(horizontalArrangement = Arrangement.spacedBy(15.dp)) {
items(items = cardColors) { cardColor ->
ElevatedButton(
onClick = { currentCardColor = cardColor },
colors = ButtonDefaults.buttonColors(containerColor = cardColor.color),
shape = MaterialTheme.shapes.large,
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary),
modifier = Modifier.size(49.dp),
) {}
}
}
Spacer(modifier = Modifier.height(6.dp))
LazyRow(horizontalArrangement = Arrangement.spacedBy(17.dp)) {
items(items = fontColors) { fontColor ->
ElevatedButton(
onClick = { currentFontColor = fontColor },
colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.tertiary),
shape = MaterialTheme.shapes.large,
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary),
modifier = Modifier.height(40.dp)
) {
Text(
text = stringResource(id = R.string.font_color_text),
color = fontColor.color,
style = MaterialTheme.typography.labelSmall,
)
}
}
}
Spacer(modifier = Modifier.height(6.dp))
LazyRow(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
items(items = fontsFamily) { fontFamily ->
ElevatedButton(
onClick = { currentFontFamily = fontFamily },
colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.tertiary),
shape = MaterialTheme.shapes.large,
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary),
modifier = Modifier.height(40.dp)
) {
Text(
text = stringResource(id = R.string.font_color_text),
style = MaterialTheme.typography.labelSmall,
color = currentFontColor.color,
fontFamily = fontFamily.font,
)
}
}
}
Spacer(modifier = Modifier.height(15.dp))
Row() {
ElevatedButton(
onClick = {
val intent = Intent(context, MainActivity::class.java)
startActivity(intent)
finish()
},
colors = ButtonDefaults.buttonColors(MaterialTheme.colorScheme.primary),
shape = MaterialTheme.shapes.large,
modifier = Modifier.width(125.dp)
) {
Text(
text = stringResource(id = R.string.cancel_button),
style = MaterialTheme.typography.labelMedium,
color = Color.White
)
}
Spacer(modifier = Modifier.width(20.dp))
ElevatedButton(
onClick = {
val currentMemoryImage = selectedImage.toString()
val currentMemoryDate = memoryDate.toString()
val memory = Memory(
memoryDate = currentMemoryDate,
memoryTitle = memoryTitle,
memoryDescription = memoryDescription,
memoryImage = currentMemoryImage,
cardColorType = currentCardColor,
fontColorType = currentFontColor,
fontType = currentFontFamily
)
StorageOperation.writeMemory(context, memory)
val intent = Intent(context, MainActivity::class.java)
intent.putExtra("memory", memory)
startActivity(intent)
finish()
},
colors = ButtonDefaults.buttonColors(MaterialTheme.colorScheme.primary),
shape = MaterialTheme.shapes.large,
modifier = Modifier.width(125.dp)
) {
Text(
text = stringResource(id = R.string.save_button),
style = MaterialTheme.typography.labelMedium,
color = Color.White
)
}
}
}
}
}
}
|
Memories-App/app/src/main/java/wioleta/wrobel/memoriesapp/AddMemoryActivity.kt
|
456075200
|
package wioleta.wrobel.memoriesapp.model
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontFamily
import com.squareup.moshi.JsonClass
import wioleta.wrobel.memoriesapp.ui.theme.card_color_blue
import wioleta.wrobel.memoriesapp.ui.theme.card_color_green
import wioleta.wrobel.memoriesapp.ui.theme.card_color_grey
import wioleta.wrobel.memoriesapp.ui.theme.card_color_pink
import wioleta.wrobel.memoriesapp.ui.theme.card_color_yellow
import wioleta.wrobel.memoriesapp.ui.theme.font_berkshire_swash
import wioleta.wrobel.memoriesapp.ui.theme.font_color_blue
import wioleta.wrobel.memoriesapp.ui.theme.font_color_green
import wioleta.wrobel.memoriesapp.ui.theme.font_color_grey
import wioleta.wrobel.memoriesapp.ui.theme.font_color_pink
import wioleta.wrobel.memoriesapp.ui.theme.font_lobster
import wioleta.wrobel.memoriesapp.ui.theme.font_playball
import wioleta.wrobel.memoriesapp.ui.theme.font_yeseva_one
import java.io.Serializable
@JsonClass(generateAdapter = true)
data class Memory(
val memoryDate: String,
val memoryTitle: String,
val memoryDescription: String,
val memoryImage: String,
val cardColorType: MemoryCardColors,
val fontColorType: MemoryFontColor,
val fontType: MemoryFontFamily
) : Serializable
enum class MemoryCardColors(val color: Color) {
GREEN(card_color_green),
PINK(card_color_pink),
BLUE(card_color_blue),
YELLOW(card_color_yellow),
GREY(card_color_grey)
}
enum class MemoryFontColor(val color: Color) {
GREY(font_color_grey),
PINK(font_color_pink),
GREEN(font_color_green),
BLUE(font_color_blue)
}
enum class MemoryFontFamily(val font: FontFamily) {
LOBSTER(font_lobster),
YESEVA(font_yeseva_one),
BERKSHIRE(font_berkshire_swash),
PLAYBALL(font_playball)
}
|
Memories-App/app/src/main/java/wioleta/wrobel/memoriesapp/model/Memory.kt
|
2473766900
|
package com.example.dryfruits1
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.dryfruits1", appContext.packageName)
}
}
|
DryFruits1/app/src/androidTest/java/com/example/dryfruits1/ExampleInstrumentedTest.kt
|
738066345
|
package com.example.dryfruits1
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)
}
}
|
DryFruits1/app/src/test/java/com/example/dryfruits1/ExampleUnitTest.kt
|
1210021702
|
package com.example.dryfruits1
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.navigation.NavController
import androidx.navigation.findNavController
import androidx.navigation.ui.setupWithNavController
import com.example.dryfruits1.Fragment.Notification_Bottom_Fragment
import com.example.dryfruits1.databinding.ActivityMainBinding
import com.google.android.material.bottomnavigation.BottomNavigationView
class MainActivity : AppCompatActivity() {
private lateinit var binding : ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding= ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
var NavController = findNavController(R.id.fragmentContainerView)
var bottomnav = findViewById<BottomNavigationView>(R.id.bottomNavigationView)
bottomnav.setupWithNavController(NavController)
binding.notificationButton.setOnClickListener{
val bottomSheetDialog =Notification_Bottom_Fragment()
bottomSheetDialog.show(supportFragmentManager,"Test")
}
}
}
|
DryFruits1/app/src/main/java/com/example/dryfruits1/MainActivity.kt
|
1230966188
|
package com.example.dryfruits1
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.dryfruits1.databinding.ActivityDetailsBinding
class DetailsActivity : AppCompatActivity() {
private lateinit var binding:ActivityDetailsBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding= ActivityDetailsBinding.inflate(layoutInflater)
setContentView(binding.root)
val foodName=intent.getStringExtra("MenuItemName")
val foodImage=intent.getIntExtra("MenuItemImage",0)
binding.detailFoodName.text=foodName
binding.detailFoodImage.setImageResource(foodImage)
binding.imageButton.setOnClickListener{
finish()
}
}
}
|
DryFruits1/app/src/main/java/com/example/dryfruits1/DetailsActivity.kt
|
1152422356
|
package com.example.dryfruits1
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.dryfruits1.databinding.ActivityStartBinding
class StartActivity : AppCompatActivity() {
private val binding: ActivityStartBinding by lazy {
ActivityStartBinding.inflate (layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.nextButton.setOnClickListener {
val intent = Intent( this, LoginActivity::class.java)
startActivity (intent)
}
}
}
|
DryFruits1/app/src/main/java/com/example/dryfruits1/StartActivity.kt
|
1889024082
|
package com.example.dryfruits1
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.dryfruits1.databinding.FragmentCongratsBottomSheetBinding
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
class CongratsBottomSheet : BottomSheetDialogFragment() {
private lateinit var binding:FragmentCongratsBottomSheetBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
binding=FragmentCongratsBottomSheetBinding.inflate(layoutInflater,container,false)
binding.goHome.setOnClickListener(){
val intent = Intent(requireContext(),MainActivity::class.java)
startActivity(intent)
}
return binding.root
}
companion object {
}
}
|
DryFruits1/app/src/main/java/com/example/dryfruits1/CongratsBottomSheet.kt
|
54593388
|
package com.example.dryfruits1.adapter
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View.OnClickListener
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.dryfruits1.DetailsActivity
import com.example.dryfruits1.databinding.MenuItemBinding
class MenuAdapter(private val menuItemsName:MutableList<String>, private val menuItemsPrice:MutableList<String>, private val MenuImage:MutableList<Int>,private val requireContext:Context): RecyclerView.Adapter<MenuAdapter.MenuViewHolder>() {
private val itemClickListener:OnClickListener?=null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MenuViewHolder {
val binding = MenuItemBinding.inflate(LayoutInflater.from(parent.context),parent,false)
return MenuViewHolder(binding)
}
override fun onBindViewHolder(holder: MenuViewHolder, position: Int) {
holder.bind(position)
}
override fun getItemCount(): Int = menuItemsName.size
inner class MenuViewHolder(private val binding: MenuItemBinding):RecyclerView.ViewHolder(binding.root){
init {
binding.root.setOnClickListener{
val position = adapterPosition
if (position!=RecyclerView.NO_POSITION){
itemClickListener?.onItemClick(position)
//set onlcicklistener to open details
val intent = Intent(requireContext,DetailsActivity::class.java)
intent.putExtra("MenuItemName",menuItemsName.get(position))
intent.putExtra("MenuItemImage",MenuImage.get(position))
requireContext.startActivity(intent)
}
}
}
fun bind(position: Int) {
binding.apply {
menufoodName.text=menuItemsName[position]
menuPrice.text=menuItemsPrice[position]
menuImage.setImageResource(MenuImage[position])
}
}
}
interface OnClickListener {
fun onItemClick(position: Int)
}
}
|
DryFruits1/app/src/main/java/com/example/dryfruits1/adapter/MenuAdapter.kt
|
44063945
|
package com.example.dryfruits1.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.dryfruits1.databinding.CartItemBinding
class CartAdapter(private val CartItems:MutableList<String>,
private val CartItemPrice:MutableList<String>,
private var CartImage:MutableList<Int>): RecyclerView.Adapter<CartAdapter.CartViewHolder>() {
private val itemQuantities = IntArray(CartItems.size){1}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CartViewHolder {
val binding=CartItemBinding.inflate(LayoutInflater.from(parent.context),parent,false)
return CartViewHolder(binding)
}
override fun onBindViewHolder(holder: CartViewHolder, position: Int) {
holder.bind(position)
}
override fun getItemCount(): Int = CartItems.size
inner class CartViewHolder(private val binding: CartItemBinding) :RecyclerView.ViewHolder (binding.root) {
fun bind(position: Int) {
binding.apply {
val quantity = itemQuantities[position]
cartFoodName.text = CartItems[position]
cartItemPrice.text = CartItemPrice[position]
cartImage.setImageResource(CartImage[position])
cartItemQuantity.text = quantity.toString()
minusbutton.setOnClickListener {
deceaseQuantity(position)
}
plusbutton.setOnClickListener {
increaseQuantity(position)
}
deletebutton.setOnClickListener {
val itemPosition= adapterPosition
if( itemPosition != RecyclerView.NO_POSITION) {
deleteItem (itemPosition)
}
}
}
}
private fun deceaseQuantity(position: Int) {
if (itemQuantities[position] > 1) {
itemQuantities[position]--
binding.cartItemQuantity.text = itemQuantities[position].toString()
}
}
private fun increaseQuantity(position: Int) {
if (itemQuantities[position] < 10) {
itemQuantities[position]++
binding.cartItemQuantity.text = itemQuantities[position].toString()
}
}
private fun deleteItem(position: Int) {
CartItems.removeAt(position)
CartImage.removeAt(position)
CartItemPrice.removeAt(position)
notifyItemRemoved(position)
notifyItemRangeChanged(position, CartItems.size)
}
} }
|
DryFruits1/app/src/main/java/com/example/dryfruits1/adapter/CartAdapter.kt
|
4075801227
|
package com.example.dryfruits1.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.dryfruits1.databinding.NotificationItemBinding
class NotificationAdapter(private var notification:ArrayList<String>,private var notificationImage:ArrayList<Int>): RecyclerView.Adapter<NotificationAdapter.NotificationViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NotificationViewHolder {
val binding=NotificationItemBinding.inflate(LayoutInflater.from(parent.context),parent,false)
return NotificationViewHolder(binding)
}
override fun onBindViewHolder(holder: NotificationViewHolder, position: Int) {
holder.bind(position)
}
override fun getItemCount(): Int = notification.size
inner class NotificationViewHolder(private val binding: NotificationItemBinding):RecyclerView.ViewHolder(binding.root) {
fun bind(position: Int) {
binding.apply {
notificationImageView.setImageResource(notificationImage[position])
notoficationTextView.text = notification[position]
}
}
}
}
|
DryFruits1/app/src/main/java/com/example/dryfruits1/adapter/NotificationAdapter.kt
|
1796343871
|
package com.example.dryfruits1.adapter
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.dryfruits1.DetailsActivity
import com.example.dryfruits1.databinding.PopularItemBinding
class PopularAdapter(private val items:List<String>,private val price:List<String>,private val image:List<Int>,private val requireContext:Context) : RecyclerView.Adapter<PopularAdapter.PopularViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PopularViewHolder {
return PopularViewHolder(PopularItemBinding.inflate(LayoutInflater.from(parent.context),parent,false))
}
override fun onBindViewHolder(holder: PopularViewHolder, position: Int) {
val item = items[position]
val price=price[position]
val images=image[position]
holder.bind(item,price,images )
holder.itemView.setOnClickListener{
val intent = Intent(requireContext, DetailsActivity::class.java)
intent.putExtra("MenuItemName",item)
intent.putExtra("MenuItemImage",images)
requireContext.startActivity(intent)
}
}
override fun getItemCount(): Int {
return items.size
}
class PopularViewHolder (private val binding:PopularItemBinding):RecyclerView.ViewHolder(binding.root) {
private val imagesView = binding.menuImage
fun bind(item: String, price: String,images: Int) {
binding.menufoodName.text=item
binding.menuPrice.text=price
imagesView.setImageResource(images)
}
}
}
|
DryFruits1/app/src/main/java/com/example/dryfruits1/adapter/PopularAdapter.kt
|
1134861358
|
package com.example.dryfruits1.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.dryfruits1.databinding.BuyAgainItemBinding
class BuyAgainAdapter(private val buyAgainFoodName:ArrayList<String>,private val
buyAgainFoodPrice:ArrayList<String>,private val
buyAgainFoodImage:ArrayList<Int>): RecyclerView.Adapter<BuyAgainAdapter.BuyAgainViewHolder>() {
override fun onBindViewHolder(holder: BuyAgainViewHolder, position: Int) {
holder.bind(buyAgainFoodName [position] , buyAgainFoodPrice [position] , buyAgainFoodImage [position] )
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BuyAgainViewHolder {
val binding= BuyAgainItemBinding.inflate(LayoutInflater.from(parent.context),parent,false)
return BuyAgainViewHolder(binding)
}
override fun getItemCount(): Int = buyAgainFoodPrice.size
class BuyAgainViewHolder(private val binding: BuyAgainItemBinding) : RecyclerView.ViewHolder
(binding.root){
fun bind(foodName: String, foodPrice: String, foodlmage: Int) {
binding.buyAgainFoodName.text=foodName
binding.buyAgainFoodPrice.text =foodPrice
binding.buyAgainFoodImage.setImageResource(foodlmage)
}
}
}
|
DryFruits1/app/src/main/java/com/example/dryfruits1/adapter/BuyAgainAdapter.kt
|
1670978893
|
package com.example.dryfruits1
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.dryfruits1.databinding.ActivityPayOutBinding
class PayOutActivity : AppCompatActivity() {
lateinit var binding:ActivityPayOutBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding=ActivityPayOutBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.PLaceMyOrder.setOnClickListener{
val bottomSheetDialog=CongratsBottomSheet()
bottomSheetDialog.show(supportFragmentManager,"Test")
}
}
}
|
DryFruits1/app/src/main/java/com/example/dryfruits1/PayOutActivity.kt
|
4249374211
|
package com.example.dryfruits1.Fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.dryfruits1.R
import com.example.dryfruits1.adapter.MenuAdapter
import com.example.dryfruits1.databinding.FragmentMenuBottomSheetBinding
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
class MenuBottomSheetFragment : BottomSheetDialogFragment() {
private lateinit var binding: FragmentMenuBottomSheetBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View{
binding = FragmentMenuBottomSheetBinding.inflate(inflater,container,false)
binding.buttonBack.setOnClickListener(){
dismiss()
}
val menuFoodName = listOf( "Cashews","Almonds","Pistachios","Peanuts","Raisins","Dates","Anjeer")
val menuItemPtice = listOf("Rs.965","Rs.959","Rs.532","Rs.554","Rs.242","Rs.425","Rs.425")
val menuImage = listOf(
R.drawable.menu1,
R.drawable.menu2,
R.drawable.menu3,
R.drawable.menu4,
R.drawable.menu5,
R.drawable.menu6,
R.drawable.menu7
)
val adapter = MenuAdapter(ArrayList(menuFoodName),ArrayList(menuItemPtice),ArrayList(menuImage),requireContext())
binding.menuRecyclerView.layoutManager = LinearLayoutManager(requireContext())
binding.menuRecyclerView.adapter = adapter
return binding.root
}
companion object {
}
}
|
DryFruits1/app/src/main/java/com/example/dryfruits1/Fragment/MenuBottomSheetFragment.kt
|
5298174
|
package com.example.dryfruits1.Fragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.dryfruits1.R
import com.example.dryfruits1.adapter.BuyAgainAdapter
import com.example.dryfruits1.databinding.FragmentHistoryBinding
class HistoryFragment : Fragment() {
private lateinit var binding: FragmentHistoryBinding
private lateinit var buyAgainAdapter: BuyAgainAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = FragmentHistoryBinding. inflate (layoutInflater, container ,false)
setupRecyclerView()
return binding.root
}
private fun setupRecyclerView(){
val buyAgainFoodName = arrayListOf("Food 1","Food 1","Food 1")
val buyAgainFoodPrice= arrayListOf("Rs.500","Rs.500","Rs.500")
val buyAgainFoodImage = arrayListOf(R.drawable.menu1,R.drawable.menu2,R.drawable.menu3)
buyAgainAdapter= BuyAgainAdapter(buyAgainFoodName,buyAgainFoodPrice,buyAgainFoodImage)
binding.BuyAgainRecyclerView.adapter=buyAgainAdapter
binding.BuyAgainRecyclerView.layoutManager=LinearLayoutManager(requireContext())
}
companion object {
}
}
|
DryFruits1/app/src/main/java/com/example/dryfruits1/Fragment/HistoryFragment.kt
|
2269622087
|
package com.example.dryfruits1.Fragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.dryfruits1.R
import com.example.dryfruits1.adapter.NotificationAdapter
import com.example.dryfruits1.databinding.FragmentNotificationBottomBinding
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
class Notification_Bottom_Fragment : BottomSheetDialogFragment() {
private lateinit var binding: FragmentNotificationBottomBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding=FragmentNotificationBottomBinding.inflate(layoutInflater)
val notification = listOf("Your order has been Canceled Successfully" , "Order has been taken by the driver","Congrats Your Order Placed")
val notificationImages= listOf(R.drawable.sademoji,R.drawable.truck,R.drawable.congrats)
val adapter = NotificationAdapter(ArrayList(notification), ArrayList(notificationImages))
binding.notificationRecyclerView.layoutManager=(LinearLayoutManager(requireContext()))
binding.notificationRecyclerView.adapter=adapter
return binding.root
}
companion object {
}
}
|
DryFruits1/app/src/main/java/com/example/dryfruits1/Fragment/Notification_Bottom_Fragment.kt
|
486335377
|
package com.example.dryfruits1.Fragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.SearchView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.room.util.query
import com.example.dryfruits1.R
import com.example.dryfruits1.adapter.MenuAdapter
import com.example.dryfruits1.databinding.FragmentSearchBinding
class SearchFragment : Fragment() {
private lateinit var binding:FragmentSearchBinding
private lateinit var adapter:MenuAdapter
private val originalMenuFoodName = listOf("Cashews","Almonds","Pistachios","Peanuts","Raisins","Dates","Anjeer")
private val originalMenuItemPrice = listOf("Rs.965","Rs.959","Rs.532","Rs.554","Rs.242","Rs.425","Rs.425")
private val originalMenuImage = listOf(
R.drawable.menu1,
R.drawable.menu2,
R.drawable.menu3,
R.drawable.menu4,
R.drawable.menu5,
R.drawable.menu6,
R.drawable.menu7
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
private val filteredMenuFoodName = mutableListOf<String>()
private val filteredMenuItemPrice = mutableListOf<String>()
private val filteredMenuFoodImage= mutableListOf<Int>()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding=FragmentSearchBinding.inflate(inflater,container,false)
adapter= MenuAdapter(filteredMenuFoodName,filteredMenuItemPrice,filteredMenuFoodImage,requireContext())
binding.menuRecyclerView.layoutManager=LinearLayoutManager(requireContext())
binding.menuRecyclerView.adapter=adapter
//setup for search view
setupSearchView()
//show all menu items
showAllMenu()
return binding.root
}
private fun showAllMenu() {
filteredMenuFoodName.clear()
filteredMenuItemPrice.clear()
filteredMenuFoodImage.clear()
filteredMenuFoodName.addAll(originalMenuFoodName)
filteredMenuItemPrice.addAll(originalMenuItemPrice)
filteredMenuFoodImage.addAll(originalMenuImage)
adapter.notifyDataSetChanged()
}
private fun setupSearchView() {
binding.searchView.setOnQueryTextListener(object :SearchView.OnQueryTextListener{
override fun onQueryTextSubmit(query: String): Boolean {
filterMenuItems(query)
return true
}
override fun onQueryTextChange(newText: String): Boolean {
filterMenuItems(newText)
return true
}
})
}
private fun filterMenuItems(query:String) {
filteredMenuFoodName.clear()
filteredMenuItemPrice.clear()
filteredMenuFoodImage.clear()
originalMenuFoodName.forEachIndexed { index, foodName ->
if(foodName.contains(query,ignoreCase = true)){
filteredMenuFoodName.add(foodName)
filteredMenuItemPrice.add(originalMenuItemPrice[index])
filteredMenuFoodImage.add(originalMenuImage[index])
}
}
adapter.notifyDataSetChanged()
}
companion object {
}
}
|
DryFruits1/app/src/main/java/com/example/dryfruits1/Fragment/SearchFragment.kt
|
205092434
|
package com.example.dryfruits1.Fragment
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.dryfruits1.CongratsBottomSheet
import com.example.dryfruits1.PayOutActivity
import com.example.dryfruits1.R
import com.example.dryfruits1.adapter.CartAdapter
import com.example.dryfruits1.databinding.FragmentCartBinding
class CartFragment : Fragment() {
private lateinit var binding: FragmentCartBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentCartBinding.inflate (inflater, container, false)
val cartFoodName = listOf( "Cashews","Almonds","Pistachios","Peanuts","Raisins","Dates")
val cartItemPtice = listOf("Rs.965","Rs.959","Rs.532","Rs.554","Rs.242","Rs.425")
val cartImage = listOf(
R.drawable.menu1,
R.drawable.menu2,
R.drawable.menu3,
R.drawable.menu4,
R.drawable.menu5,
R.drawable.menu6)
val adapter =CartAdapter(ArrayList(cartFoodName),ArrayList(cartItemPtice),ArrayList(cartImage))
binding.cartRecyclerView.layoutManager = LinearLayoutManager(requireContext())
binding.cartRecyclerView.adapter = adapter
binding.proceedButton.setOnClickListener{
val intent = Intent(requireContext(),PayOutActivity::class.java)
startActivity(intent)
}
return binding.root
}
companion object {
}
}
|
DryFruits1/app/src/main/java/com/example/dryfruits1/Fragment/CartFragment.kt
|
743054571
|
package com.example.dryfruits1.Fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.denzcoskun.imageslider.constants.ScaleTypes
import com.denzcoskun.imageslider.interfaces.ItemClickListener
import com.denzcoskun.imageslider.models.SlideModel
import com.example.dryfruits1.R
import com.example.dryfruits1.adapter.PopularAdapter
import com.example.dryfruits1.databinding.FragmentHomeBinding
class HomeFragment : Fragment() {
private lateinit var binding: FragmentHomeBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View{
// Inflate the layout for this fragment
binding = FragmentHomeBinding.inflate(inflater,container,false)
binding.viewAllMenu.setOnClickListener{
val bottomSheetDialog = MenuBottomSheetFragment()
bottomSheetDialog.show(parentFragmentManager,"Test")
}
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val imageList = ArrayList<SlideModel>()
imageList.add(SlideModel(R.drawable.banner1, ScaleTypes.FIT))
imageList.add(SlideModel(R.drawable.banner2, ScaleTypes.FIT))
imageList.add(SlideModel(R.drawable.banner3, ScaleTypes.FIT))
val imageSlider = binding.imageSlider
imageSlider.setImageList(imageList)
imageSlider.setImageList(imageList, ScaleTypes.FIT)
imageSlider.setItemClickListener(object :ItemClickListener{
override fun doubleClick(position: Int) {
TODO("Not yet implemented")
}
override fun onItemSelected(position: Int) {
val itemPosition = imageList[position]
val itemMessage="Selected Image $position"
Toast.makeText(requireContext(),itemMessage,Toast.LENGTH_SHORT).show()
}
})
val foodName = listOf("Cashews","Almonds","Pistachios","Peanuts")
val Price= listOf("Rs.965","Rs.959","Rs.532","Rs.554")
val popularFoodImages = listOf(R.drawable.menu1,R.drawable.menu2,R.drawable.menu3,R.drawable.menu4)
val adapter = PopularAdapter(foodName,Price,popularFoodImages,requireContext())
binding.PopularRecyclerView.layoutManager=LinearLayoutManager(requireContext())
binding.PopularRecyclerView.adapter = adapter
}
companion object {
}
}
|
DryFruits1/app/src/main/java/com/example/dryfruits1/Fragment/HomeFragment.kt
|
3179609473
|
package com.example.dryfruits1.Fragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.dryfruits1.R
class ProfileFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_profile, container, false)
}
companion object {
}
}
|
DryFruits1/app/src/main/java/com/example/dryfruits1/Fragment/ProfileFragment.kt
|
1499006595
|
package com.example.dryfruits1
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.dryfruits1.databinding.ActivityLoginBinding
import com.example.dryfruits1.databinding.ActivitySiginBinding
class SiginActivity : AppCompatActivity() {
private val binding : ActivitySiginBinding by lazy {
ActivitySiginBinding.inflate (layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView (binding.root)
binding.alreadyhavebutton.setOnClickListener {
val intent = Intent( this, LoginActivity::class.java)
startActivity (intent)
}
}}
|
DryFruits1/app/src/main/java/com/example/dryfruits1/SiginActivity.kt
|
2411427439
|
package com.example.dryfruits1
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
class Splash_Screen : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash_screen)
Handler(Looper.getMainLooper()).postDelayed({
val intent = Intent(this,StartActivity::class.java)
startActivity(intent)
finish()
},3000)
}
}
|
DryFruits1/app/src/main/java/com/example/dryfruits1/Splash_Screen.kt
|
634905784
|
package com.example.dryfruits1
import android.R
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import com.example.dryfruits1.databinding.ActivityChooseLocationBinding
class ChooseLocation : AppCompatActivity() {
private val binding: ActivityChooseLocationBinding by lazy {
ActivityChooseLocationBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
val locationList = arrayOf("Jaipur", "Odisha", "Bundi", "Sikar")
val adapter = ArrayAdapter(this, R.layout.simple_list_item_1, locationList)
val autoCompleteTextView = binding.listOfLocation
autoCompleteTextView.setAdapter(adapter)
}
}
|
DryFruits1/app/src/main/java/com/example/dryfruits1/ChooseLocation.kt
|
2736077335
|
package com.example.dryfruits1
import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.dryfruits1.databinding.ActivityLoginBinding
class LoginActivity : AppCompatActivity() {
private val binding: ActivityLoginBinding by lazy {
ActivityLoginBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.loginbutton.setOnClickListener {
val intent= Intent(this, SiginActivity::class.java)
startActivity (intent)
}
binding.donthavebutton.setOnClickListener {
val intent=Intent( this, SiginActivity::class.java)
startActivity (intent)
}
}
}
|
DryFruits1/app/src/main/java/com/example/dryfruits1/LoginActivity.kt
|
3375545076
|
package dti.g25.pendu
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import dti.g25.pendu.presentateur.Presentateur
// Les lettres
var lettres = emptyArray<Button>()
lateinit var tvScore: TextView
lateinit var tvLettresMots: TextView
lateinit var tvResult: TextView
lateinit var imagePendu: ImageView
lateinit var btnRecommencer : Button
// Couleurs des boutons
val COULEUR_NORMAL = 0xFF5b39c6.toInt()
val COULEUR_SELECTIONNE = 0xFF808080.toInt()
class MainActivity : AppCompatActivity(), View.OnClickListener {
val presentateur = Presentateur(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
for(i in 65 .. 90){
val resID = resources.getIdentifier("btn${i.toChar()}", "id", packageName)
val lettre = findViewById(resID) as Button
lettres += lettre
lettre.setOnClickListener{onClick(lettre)}
}
tvScore = findViewById(R.id.tvScore)
tvLettresMots = findViewById(R.id.tvLettresMots)
tvResult = findViewById(R.id.tvResult)
imagePendu = findViewById(R.id.imgPendu)
btnRecommencer = findViewById(R.id.btnReinit) as Button
btnRecommencer.setOnClickListener{presentateur.démarrer()}
}
/**
* Écouteur des boutons alphabétisés
*
* @param v Le bouton cliqué
*/
override fun onClick(v : View) {
var lettreButton: Button = v as Button
var buttonText : String = lettreButton.text.toString()
presentateur.sélectionnerLettre(buttonText.single())
}
/**
* Changer la couleur à gris quand on clique sur une lettre
*
* @param lettre Le lettre qu'on a cliqué
*/
fun changerCouleur(lettre : Char){
lettres[lettre.code - 65].setBackgroundColor(COULEUR_SELECTIONNE)
}
/**
* Afficher l'état des lettres
*
* @param clic L'état des lettres (Such creative! WOW!)
*/
fun afficherÉtatLettres(etat: String){
tvLettresMots.text = etat
}
/**
* Afficher le score
*
* @param score Le score (NO WAY!)
*/
fun afficherScore(score: Int){
tvScore.text = score.toString()
}
/**
* Afficher les instructions
*/
fun afficherInstructions(){
tvResult.text = getString(R.string.guessWord)
}
/**
* Afficher la réussite (On god)
*/
fun afficherRéussi(){
tvResult.text = getString(R.string.win)
}
/**
* Afficher L'INCOMPÉTENCE DU JOUEUR DE NE PAS DEVINER LE MOT HAHAHAHAHHAHAHAHAHA
*/
fun afficherÉchec(motADeviner : String){
tvResult.text = getString(R.string.skillIssue)
tvLettresMots.text = getString(R.string.motReveal)+ " " +motADeviner
}
/**
* Reset les couleurs du bouton
*/
fun afficherReset(){
btnRecommencer.text = getString(R.string.btnRestart)
for(buttonLettre: Button in lettres){
buttonLettre.setBackgroundColor(COULEUR_NORMAL)
}
}
/**
* HAAAAAAAAAAAANNNNNNNNNNNNNNNNNNNNNGGGGGGGGGGGGGGGGGGGGGGMAN1 (Afficher les images du hangman)
*/
fun afficherImage(numero: Int){
var imageValue = "hangman$numero"
var id: Int = resources.getIdentifier(imageValue, "drawable", packageName)
imagePendu.setImageResource(id)
}
}
|
Pendu/app/src/main/java/dti/g25/pendu/MainActivity.kt
|
1400553194
|
package dti.g25.pendu.test
import dti.g25.pendu.modèle.Jeu
import org.junit.Test
class JeuTest {
@Test
fun testEssayerLettre(){
var valeurObservée: Boolean
val valeurAttendue = true
var jeuTest = Jeu(listeMots())
valeurObservée = jeuTest.essayerUneLettre('A')
println("Le mot est : " +jeuTest.motÀDeviner)
if(valeurObservée == valeurAttendue){
println("SUCCESS!")
}
else {
println("ERREUR: attendu: "+valeurAttendue+" observé: "+valeurObservée)
}
}
@Test
fun testEstReussi(){
var valeurObservée: Boolean
val valeurAttendue = true
var jeuTest = Jeu(listeMots())
valeurObservée = jeuTest.estRéussi()
if(valeurObservée == valeurAttendue){
println("SUCCESS!")
}
else {
println("ERREUR: attendu: "+valeurAttendue+" observé: "+valeurObservée)
}
}
@Test
fun testEstUnÉchec(){
var valeurObservée: Boolean
val valeurAttendue = true
var jeuTest = Jeu(listeMots())
valeurObservée = jeuTest.estUnÉchec()
if(valeurObservée == valeurAttendue){
println("SUCCESS!")
}
else {
println("ERREUR: attendu: "+valeurAttendue+" observé: "+valeurObservée)
}
}
@Test
fun testÉtatLettres(){
lateinit var valeurObservée: CharArray
//val valeurAttendue = true
var jeuTest = Jeu(listeMots())
jeuTest.essayerUneLettre('E')
println("Le mot est : " +jeuTest.motÀDeviner)
valeurObservée = jeuTest.étatLettres()
for (valeur: Char in valeurObservée){
print(valeur)
}
}
fun listeMots(): Array<String>{
val listeMots = arrayOf<String>("Serendipity\n",
"Pernicious\n",
"Mellifluous\n",
"Quixotic\n",
"Furtive\n",
"Supercilious\n",
"Ebullient\n",
"Voracious\n",
"Cacophony\n",
"Inscrutable")
return listeMots
}
}
|
Pendu/app/src/main/java/dti/g25/pendu/test/JeuTest.kt
|
2468430558
|
package dti.g25.pendu.modèle
class Jeu (listeDeMots: Array<String>) {
var lettresEssayées: CharArray = CharArray(26){' '}
var motÀDeviner : String
var pointage: Int = 0
get() = field
var nbErreurs: Int = 0
get() = field
var listeDeMots: Array<String>
init {
this.listeDeMots = listeDeMots
motÀDeviner = this.listeDeMots[kotlin.random.Random.nextInt(this.listeDeMots.size)]
}
/**
* Essaye une lettre choisi par le joueur en cliquant le bouton
*
* @param lettre La lettre à essayer
*
* @return true si la lettre est dans le mot à trouver sinon false si ce n'est pas
*/
fun essayerUneLettre(lettre: Char): Boolean {
if (lettre in lettresEssayées) {
//nbErreurs++
return false
}
lettresEssayées[nbErreurs + pointage] = lettre
val arrayMotÀDeviner = motÀDeviner.toCharArray()
var réussiOuPas = false
arrayMotÀDeviner.forEach { lettreMotADeviner ->
if (lettreMotADeviner.lowercase() == lettre.lowercase()) {
pointage++
réussiOuPas = true
}
}
if (réussiOuPas) {
return true
}
nbErreurs++
return false
}
/**
* Voir si tout les lettres du mot ont été trouvé
*
* @return true si le joueur a gagné sinon retourne false
*/
fun estRéussi(): Boolean{
if(pointage >= motÀDeviner.length - 1){
return true
}
return false
}
/**
* Voir si le joueur a perdu
*
* @return true si le joueur a perdu sinon retourne false
*/
fun estUnÉchec(): Boolean{
if(nbErreurs >= 6){
return true
}
return false
}
/**
* Réinitialise le jeu
*/
fun réinitialiser(){
pointage = 0
nbErreurs = 0
lettresEssayées = CharArray(26){' '}
motÀDeviner = this.listeDeMots[kotlin.random.Random.nextInt(this.listeDeMots.size)]
}
/**
* Verfier l'état des lettres
*
* @return Une liste de caractères qui montre quelle lettres le joueur a trouvé sinon pas une lettres pas trouvé va être un "_"
*/
fun étatLettres(): CharArray{
var i: Int = 0
var étatLettres: CharArray = CharArray(motÀDeviner.length - 1) {'_'}
val arrayMotÀDeviner: Array<String> = motÀDeviner.map { it.toString() }.toTypedArray()
for (lettresDevinées: Char in lettresEssayées){
i = 0
for(lettresMotÀDeviner: String in arrayMotÀDeviner){
if(lettresMotÀDeviner.single().lowercase().equals((lettresDevinées.lowercase()))){
étatLettres.set(i, lettresDevinées)
}
i++
}
}
return étatLettres
}
}
|
Pendu/app/src/main/java/dti/g25/pendu/modèle/Jeu.kt
|
2539496746
|
package dti.g25.pendu.presentateur
import dti.g25.pendu.MainActivity
import dti.g25.pendu.modèle.Jeu
class Presentateur (var vue: MainActivity){
var jeu = Jeu(listeDesMots())
var aCommencé : Boolean = false
/**
* Réagit à une sélection d'une lettre
*
* @param lettre La lettre cliqué
*/
fun sélectionnerLettre(lettre: Char){
if(aCommencé){
jeu.essayerUneLettre(lettre)
val lesLettres: String = jeu.étatLettres().joinToString(" ")
vue.changerCouleur(lettre)
vue.afficherÉtatLettres(lesLettres)
vue.afficherScore(jeu.pointage)
vue.afficherImage(jeu.nbErreurs)
vue.afficherInstructions()
if (jeu.estRéussi()){
vue.afficherRéussi()
aCommencé = false
}
if (jeu.estUnÉchec()){
vue.afficherÉchec(jeu.motÀDeviner)
aCommencé = false
}
}
}
/**
* Réinitialise le jeu
*/
fun démarrer(){
aCommencé = true
jeu.réinitialiser()
val etatResetLettres = jeu.étatLettres().joinToString(" ")
vue.afficherInstructions()
vue.afficherÉtatLettres(etatResetLettres)
vue.afficherScore(jeu.pointage)
vue.afficherImage(0)
vue.afficherReset()
}
/**
* Liste des mots
*/
fun listeDesMots(): Array<String>{
return arrayOf<String>("Baleine\n" ,
"Enfant\n" ,
"Tapisserie\n" ,
"Nuage\n" ,
"Grenouille\n" ,
"Plage\n" ,
"Oiseau\n" ,
"Crocodile\n" ,
"Vent\n" ,
"Canard\n" ,
"Tournesol\n" ,
"Cerf\n" ,
"Cheval\n" ,
"Piano\n" ,
"Moustache\n" ,
"Montagne\n" ,
"Feuille\n" ,
"Papillon\n" ,
"Bouquet\n" ,
"Tomate\n" ,
"Chaussure\n" ,
"Parapluie\n" ,
"Boule\n" ,
"Chenille\n" ,
"Tigre\n" ,
"Crayon\n" ,
"Coquillage\n" ,
"Bateau\n" ,
"Aigle\n" ,
"Girafe\n" ,
"Souris\n" ,
"Chat\n" ,
"Chapeau\n" ,
"Citrouille\n" ,
"Lune\n" ,
"Guitare\n" ,
"Tortue\n" ,
"Marmotte\n" ,
"Tuyau\n" ,
"Cascade\n" ,
"Baleine\n" ,
"Papier\n" ,
"Feu\n" ,
"Orage\n" ,
"Couronne\n" ,
"Grenade\n" ,
"Escalier\n" ,
"Haricot\n" ,
"Nuageux\n" ,
"Sourire\n" ,
"Poisson\n" ,
"Statue\n" ,
"Casquette\n" ,
"Coccinelle\n" ,
"Vase\n" ,
"Baleine\n" ,
"Piano\n" ,
"Soupe\n" ,
"Fourmi\n" ,
"Ours\n" ,
"Dentelle\n" ,
"Saumon\n" ,
"Cactus\n" ,
"Crabe\n" ,
"Moustique\n" ,
"Cendrier\n" ,
"Plante\n" ,
"Fleur\n" ,
"Chien\n" ,
"Clavier\n" ,
"Grenouille\n" ,
"Souffle\n" ,
"Parfum\n" ,
"Sapin\n" ,
"Papaye\n" ,
"Enfant\n" ,
"Statue")
}
}
|
Pendu/app/src/main/java/dti/g25/pendu/presentateur/Presentateur.kt
|
3801754127
|
package com.pietrantuono.columnsync
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.pietrantuono.columnsync", appContext.packageName)
}
}
|
ColumnSync/app/src/androidTest/java/com/pietrantuono/columnsync/ExampleInstrumentedTest.kt
|
4047565543
|
package com.pietrantuono.columnsync
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)
}
}
|
ColumnSync/app/src/test/java/com/pietrantuono/columnsync/ExampleUnitTest.kt
|
2710824364
|
package com.pietrantuono.columnsync.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
|
ColumnSync/app/src/main/java/com/pietrantuono/columnsync/ui/theme/Color.kt
|
38293857
|
package com.pietrantuono.columnsync.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 ColumnSyncTheme(
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
)
}
|
ColumnSync/app/src/main/java/com/pietrantuono/columnsync/ui/theme/Theme.kt
|
1272269500
|
package com.pietrantuono.columnsync.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
)
*/
)
|
ColumnSync/app/src/main/java/com/pietrantuono/columnsync/ui/theme/Type.kt
|
3337585743
|
package com.pietrantuono.columnsync
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.pietrantuono.columnsync.ui.theme.ColumnSyncTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ColumnSyncTheme {
SyncedColumn()
}
}
}
}
@Composable
private fun SyncedColumn() {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly,
) {
val stateRowOne = rememberLazyListState()
val stateRowTwo = rememberLazyListState()
val key1 by remember {
derivedStateOf {
stateRowOne.firstVisibleItemScrollOffset
}
}
LaunchedEffect(key1) {
stateRowTwo.scrollToItem(
stateRowOne.firstVisibleItemIndex,
stateRowOne.firstVisibleItemScrollOffset,
)
}
LazyColumn(
modifier = Modifier.weight(1f),
state = stateRowOne,
) {
items(100) {
Text("Item $it")
}
}
Spacer(modifier = Modifier.width(48.dp))
val key2 by remember {
derivedStateOf {
stateRowTwo.firstVisibleItemScrollOffset
}
}
LaunchedEffect(key2) {
stateRowOne.scrollToItem(
stateRowTwo.firstVisibleItemIndex,
stateRowTwo.firstVisibleItemScrollOffset,
)
}
LazyColumn(
modifier = Modifier.weight(1f),
state = stateRowTwo,
) {
items(100) {
Text("Item $it")
}
}
}
}
|
ColumnSync/app/src/main/java/com/pietrantuono/columnsync/MainActivity.kt
|
497306612
|
package com.example.movieappmad24
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.movieappmad24", appContext.packageName)
}
}
|
MAD-Exercise-03/app/src/androidTest/java/com/example/movieappmad24/ExampleInstrumentedTest.kt
|
3234575977
|
package com.example.movieappmad24
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)
}
}
|
MAD-Exercise-03/app/src/test/java/com/example/movieappmad24/ExampleUnitTest.kt
|
3392487537
|
package com.example.movieappmad24.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
|
MAD-Exercise-03/app/src/main/java/com/example/movieappmad24/ui/theme/Color.kt
|
407900815
|
package com.example.movieappmad24.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 MovieAppMAD24Theme(
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
)
}
|
MAD-Exercise-03/app/src/main/java/com/example/movieappmad24/ui/theme/Theme.kt
|
462305732
|
package com.example.movieappmad24.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
)
*/
)
|
MAD-Exercise-03/app/src/main/java/com/example/movieappmad24/ui/theme/Type.kt
|
650707661
|
package com.example.movieappmad24.scenes
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Home
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.navigation.NavController
import androidx.navigation.compose.currentBackStackEntryAsState
import com.example.movieappmad24.nav.Screen
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SimpleTopAppBar(title: String?, showBackButton: Boolean = false, navController: NavController){
CenterAlignedTopAppBar(
title = { title?.let { Text(it) } },
colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.primaryContainer,
titleContentColor = MaterialTheme.colorScheme.primary
),
navigationIcon = {
if (showBackButton){
IconButton(onClick = { navController.navigateUp() }) {
Icon(
imageVector = Icons.Filled.ArrowBack,
contentDescription = "arrowback"
)
}
}
}
)
}
@Composable
fun SimpleBottomAppBar(navController: NavController){
val currentScreen = navController.currentBackStackEntryAsState().value?.destination?.route
NavigationBar {
NavigationBarItem(
label = { Text("Home") },
selected = currentScreen == Screen.Home.route,
onClick = { navController.navigate(Screen.Home.route) },
icon = { Icon(
imageVector = Icons.Filled.Home,
contentDescription = "Go to home"
)
}
)
}
}
|
MAD-Exercise-03/app/src/main/java/com/example/movieappmad24/scenes/ScreenComponents.kt
|
2974222726
|
package com.example.movieappmad24.scenes
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
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.FavoriteBorder
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.ShapeDefaults
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.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import coil.compose.SubcomposeAsyncImage
import coil.request.ImageRequest
import com.example.movieappmad24.models.Movie
import com.example.movieappmad24.models.getMovies
import com.example.movieappmad24.nav.Screen
@Composable
fun HomeScreen(navController: NavController) {
Scaffold (
topBar = {
SimpleTopAppBar(title = "Movie App", false, navController)
},
bottomBar = {
SimpleBottomAppBar(navController)
}
){ innerPadding ->
MovieList(
modifier = Modifier.padding(innerPadding),
movies = getMovies(),
navController = navController
)
}
}
@Composable
fun MovieList(
modifier: Modifier,
movies: List<Movie> = getMovies(),
navController: NavController
){
LazyColumn(modifier = modifier) {
items(movies) { movie ->
MovieRow(movie = movie){ movieId ->
navController.navigate(Screen.Details.route + "/$movieId")
}
}
}
}
@Composable
fun MovieRow(
movie: Movie,
onItemClick: (String) -> Unit = {}
){
Card(modifier = Modifier
.fillMaxWidth()
.padding(5.dp)
.clickable {
onItemClick(movie.id)
},
shape = ShapeDefaults.Large,
elevation = CardDefaults.cardElevation(10.dp)
) {
Column {
MovieCardHeader(imageUrl = movie.images[0])
MovieDetails(modifier = Modifier.padding(12.dp), movie = movie)
}
}
}
@Composable
fun MovieCardHeader(imageUrl: String) {
Box(
modifier = Modifier
.height(150.dp)
.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
MovieImage(imageUrl)
FavoriteIcon()
}
}
@Composable
fun MovieImage(imageUrl: String){
SubcomposeAsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(imageUrl)
.crossfade(true)
.build(),
contentScale = ContentScale.Crop,
contentDescription = "movie poster",
loading = {
CircularProgressIndicator()
}
)
}
@Composable
fun FavoriteIcon() {
Box(
modifier = Modifier
.fillMaxSize()
.padding(10.dp),
contentAlignment = Alignment.TopEnd
){
Icon(
tint = MaterialTheme.colorScheme.secondary,
imageVector = Icons.Default.FavoriteBorder,
contentDescription = "Add to favorites")
}
}
@Composable
fun MovieDetails(modifier: Modifier = Modifier, movie: Movie) {
var showDetails by remember {
mutableStateOf(false)
}
Column(modifier = modifier) {
MovieTitleRow(movie.title, showDetails) { showDetails = !showDetails }
MovieDetailsContent(movie, showDetails)
}
}
@Composable
fun MovieTitleRow(title: String, showDetails: Boolean, onToggleDetails: () -> Unit) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(6.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(text = title)
Icon(
modifier = Modifier.clickable(onClick = onToggleDetails),
imageVector = if (showDetails) Icons.Filled.KeyboardArrowDown else Icons.Default.KeyboardArrowUp,
contentDescription = "show more"
)
}
}
@Composable
fun MovieDetailsContent(movie: Movie, showDetails: Boolean) {
AnimatedVisibility(
visible = showDetails,
enter = fadeIn(),
exit = fadeOut()
) {
Column {
MovieAttributes("Director", movie.director)
MovieAttributes("Released", movie.year.toString())
MovieAttributes("Genre", movie.genre)
MovieAttributes("Actors", movie.actors)
MovieAttributes("Rating", movie.rating.toString())
Divider(modifier = Modifier.padding(3.dp))
MoviePlot(movie.plot)
}
}
}
@Composable
fun MovieAttributes(label: String, value: String) {
Text(text = "$label: $value", style = MaterialTheme.typography.bodySmall)
}
@Composable
fun MoviePlot(plot: String) {
Text(buildAnnotatedString {
withStyle(style = SpanStyle(color = Color.DarkGray, fontSize = 13.sp)) {
append("Plot: ")
}
withStyle(style = SpanStyle(color = Color.DarkGray, fontSize = 13.sp, fontWeight = FontWeight.Normal)) {
append(plot)
}
})
}
|
MAD-Exercise-03/app/src/main/java/com/example/movieappmad24/scenes/HomeScreen.kt
|
882272895
|
package com.example.movieappmad24.scenes
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.example.movieappmad24.models.Movie
import com.example.movieappmad24.models.getMovies
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DetailScreen(movieId: String?, navController: NavController) {
Scaffold (
topBar = {
SimpleTopAppBar(title = getMovieById(movieId)?.title, true, navController = navController)
}
){innerPadding ->
Column(
modifier = Modifier.padding(innerPadding),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
getMovieById(movieId)?.let {
MovieRow(movie = it)
}
DisplayMovieImages(movieId)
}
}
}
fun getMovieById(id: String?): Movie? {
val movieList = getMovies()
return movieList.find { it.id == id }
}
@Composable
fun DisplayMovieImages(id: String?){
LazyRow(modifier = Modifier){
val imageList = getMovieById(id)?.images
imageList?.let { list ->
items(list) { image ->
Box(
modifier = Modifier
.padding(horizontal = 8.dp)
.clip(RoundedCornerShape(8.dp))
) {
MovieImage(imageUrl = image)
}
}
}
}
}
|
MAD-Exercise-03/app/src/main/java/com/example/movieappmad24/scenes/DetailScreen.kt
|
4162991084
|
package com.example.movieappmad24
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.navigation.compose.rememberNavController
import com.example.movieappmad24.nav.Navigation
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val navController = rememberNavController()
Navigation(navController)
}
}
}
|
MAD-Exercise-03/app/src/main/java/com/example/movieappmad24/MainActivity.kt
|
4130383343
|
package com.example.movieappmad24.models
data class Movie(
val id: String,
val title: String,
val year: String,
val genre: String,
val director: String,
val actors: String,
val plot: String,
val images: List<String>,
val trailer: String,
val rating: String
)
fun getMovies(): List<Movie> {
return listOf(
Movie(id = "tt0499549",
title = "Avatar",
year = "2009",
genre = "Action, Adventure, Fantasy",
director = "James Cameron",
actors = "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
plot = "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
images = listOf("https://images-na.ssl-images-amazon.com/images/M/MV5BMjEyOTYyMzUxNl5BMl5BanBnXkFtZTcwNTg0MTUzNA@@._V1_SX1500_CR0,0,1500,999_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BNzM2MDk3MTcyMV5BMl5BanBnXkFtZTcwNjg0MTUzNA@@._V1_SX1777_CR0,0,1777,999_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTY2ODQ3NjMyMl5BMl5BanBnXkFtZTcwODg0MTUzNA@@._V1_SX1777_CR0,0,1777,999_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTMxOTEwNDcxN15BMl5BanBnXkFtZTcwOTg0MTUzNA@@._V1_SX1777_CR0,0,1777,999_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTYxMDg1Nzk1MV5BMl5BanBnXkFtZTcwMDk0MTUzNA@@._V1_SX1500_CR0,0,1500,999_AL_.jpg"),
trailer = "trailer_placeholder",
rating = "7.9"),
Movie(id = "tt0416449",
title = "300",
year = "2006",
genre = "Action, Drama, Fantasy",
director = "Zack Snyder",
actors = "Gerard Butler, Lena Headey, Dominic West, David Wenham",
plot = "King Leonidas of Sparta and a force of 300 men fight the Persians at Thermopylae in 480 B.C.",
images = listOf("https://images-na.ssl-images-amazon.com/images/M/MV5BMTMwNTg5MzMwMV5BMl5BanBnXkFtZTcwMzA2NTIyMw@@._V1_SX1777_CR0,0,1777,937_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTQwNTgyNTMzNF5BMl5BanBnXkFtZTcwNDA2NTIyMw@@._V1_SX1777_CR0,0,1777,935_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTc0MjQzOTEwMV5BMl5BanBnXkFtZTcwMzE2NTIyMw@@._V1_SX1777_CR0,0,1777,947_AL_.jpg"
),
trailer = "trailer_placeholder",
rating = "7.7"),
Movie(id = "tt0848228",
title = "The Avengers",
year = "2012",
genre = "Action, Sci-Fi, Thriller",
director = "Joss Whedon",
actors = "Robert Downey Jr., Chris Evans, Mark Ruffalo, Chris Hemsworth",
plot = "Earth's mightiest heroes must come together and learn to fight as a team if they are to stop the mischievous Loki and his alien army from enslaving humanity.",
images = listOf("https://images-na.ssl-images-amazon.com/images/M/MV5BMTA0NjY0NzE4OTReQTJeQWpwZ15BbWU3MDczODg2Nzc@._V1_SX1777_CR0,0,1777,999_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMjE1MzEzMjcyM15BMl5BanBnXkFtZTcwNDM4ODY3Nw@@._V1_SX1777_CR0,0,1777,999_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMjMwMzM2MTg1M15BMl5BanBnXkFtZTcwNjM4ODY3Nw@@._V1_SX1777_CR0,0,1777,999_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTQ4NzM2Mjc5MV5BMl5BanBnXkFtZTcwMTkwOTY3Nw@@._V1_SX1777_CR0,0,1777,999_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTc3MzQ3NjA5N15BMl5BanBnXkFtZTcwMzY5OTY3Nw@@._V1_SX1777_CR0,0,1777,999_AL_.jpg"),
trailer = "trailer_placeholder",
rating = "8.1"),
Movie(id = "tt0993846",
title = "The Wolf of Wall Street",
year = "2013",
genre = "Biography, Comedy, Crime",
director = "Martin Scorsese",
actors = "Leonardo DiCaprio, Jonah Hill, Margot Robbie, Matthew McConaughey",
plot = "Based on the true story of Jordan Belfort, from his rise to a wealthy stock-broker living the high life to his fall involving crime, corruption and the federal government.",
images = listOf("https://images-na.ssl-images-amazon.com/images/M/MV5BNDIwMDIxNzk3Ml5BMl5BanBnXkFtZTgwMTg0MzQ4MDE@._V1_SX1500_CR0,0,1500,999_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTc0NzAxODAyMl5BMl5BanBnXkFtZTgwMDg0MzQ4MDE@._V1_SX1500_CR0,0,1500,999_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTExMDk1MDE4NzVeQTJeQWpwZ15BbWU4MDM4NDM0ODAx._V1_SX1500_CR0,0,1500,999_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTg3MTY4NDk4Nl5BMl5BanBnXkFtZTgwNjc0MzQ4MDE@._V1_SX1500_CR0,0,1500,999_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTgzMTg4MDI0Ml5BMl5BanBnXkFtZTgwOTY0MzQ4MDE@._V1_SY1000_CR0,0,1553,1000_AL_.jpg"),
trailer = "trailer_placeholder",
rating = "8.2"),
Movie(id = "tt0816692",
title = "Interstellar",
year = "2014",
genre = "Adventure, Drama, Sci-Fi",
director = "Christopher Nolan",
actors = "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
plot = "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
images = listOf("https://images-na.ssl-images-amazon.com/images/M/MV5BMjA3NTEwOTMxMV5BMl5BanBnXkFtZTgwMjMyODgxMzE@._V1_SX1500_CR0,0,1500,999_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMzQ5ODE2MzEwM15BMl5BanBnXkFtZTgwMTMyODgxMzE@._V1_SX1500_CR0,0,1500,999_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTg4Njk4MzY0Nl5BMl5BanBnXkFtZTgwMzIyODgxMzE@._V1_SX1500_CR0,0,1500,999_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMzE3MTM0MTc3Ml5BMl5BanBnXkFtZTgwMDIyODgxMzE@._V1_SX1500_CR0,0,1500,999_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BNjYzNjE2NDk3N15BMl5BanBnXkFtZTgwNzEyODgxMzE@._V1_SX1500_CR0,0,1500,999_AL_.jpg"),
trailer = "trailer_placeholder",
rating = "8.6"),
Movie(id = "tt0944947",
title = "Game of Thrones",
year = "2011 - 2018",
genre = "Adventure, Drama, Fantasy",
director = "N/A",
actors = "Peter Dinklage, Lena Headey, Emilia Clarke, Kit Harington",
plot = "While a civil war brews between several noble families in Westeros, the children of the former rulers of the land attempt to rise up to power. Meanwhile a forgotten race, bent on destruction, plans to return after thousands of years in the North.",
images = listOf("https://images-na.ssl-images-amazon.com/images/M/MV5BNDc1MGUyNzItNWRkOC00MjM1LWJjNjMtZTZlYWIxMGRmYzVlXkEyXkFqcGdeQXVyMzU3MDEyNjk@._V1_SX1777_CR0,0,1777,999_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BZjZkN2M5ODgtMjQ2OC00ZjAxLWE1MjMtZDE0OTNmNGM0NWEwXkEyXkFqcGdeQXVyNjUxNzgwNTE@._V1_SX1777_CR0,0,1777,999_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMDk4Y2Y1MDAtNGVmMC00ZTlhLTlmMmQtYjcyN2VkNzUzZjg2XkEyXkFqcGdeQXVyNjUxNzgwNTE@._V1_SX1777_CR0,0,1777,999_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BNjZjNWIzMzQtZWZjYy00ZTkwLWJiMTYtOWRkZDBhNWJhY2JmXkEyXkFqcGdeQXVyMjk3NTUyOTc@._V1_SX1777_CR0,0,1777,999_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BNTMyMTRjZWEtM2UxMS00ZjU5LWIxMTYtZDA5YmJhZmRjYTc4XkEyXkFqcGdeQXVyMjk3NTUyOTc@._V1_SX1777_CR0,0,1777,999_AL_.jpg"),
trailer = "trailer_placeholder",
rating = "9.5"),
Movie(id = "tt2306299",
title = "Vikings",
year = "2013–2020",
genre = "Action, Drama, History",
director = "N/A",
actors = "Travis Fimmel, Clive Standen, Gustaf Skarsgård, Katheryn Winnick",
plot = "The world of the Vikings is brought to life through the journey of Ragnar Lothbrok, the first Viking to emerge from Norse legend and onto the pages of history - a man on the edge of myth.",
images = listOf("https://images-na.ssl-images-amazon.com/images/M/MV5BMjM5MTM1ODUxNV5BMl5BanBnXkFtZTgwNTAzOTI2ODE@._V1_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BNzU2NDcxODMyOF5BMl5BanBnXkFtZTgwNDAzOTI2ODE@._V1_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMjMzMzIzOTU2M15BMl5BanBnXkFtZTgwODMzMTkyODE@._V1_SY1000_SX1500_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTQ2NTQ2MDA3NF5BMl5BanBnXkFtZTgwODkxMDUxODE@._V1_SY1000_SX1500_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTcxOTQ3NTA5N15BMl5BanBnXkFtZTgwMzExMDUxODE@._V1_SY1000_SX1500_AL_.jpg"),
trailer = "trailer_placeholder",
rating = "9.5"),
Movie(id = "tt0903747",
title = "Breaking Bad",
year = "2008–2013",
genre = "Crime, Drama, Thriller",
director = "N/A",
actors = "Bryan Cranston, Anna Gunn, Aaron Paul, Dean Norris",
plot = "A high school chemistry teacher diagnosed with inoperable lung cancer turns to manufacturing and selling methamphetamine in order to secure his family's financial future.",
images = listOf("https://images-na.ssl-images-amazon.com/images/M/MV5BMTgyMzI5NDc5Nl5BMl5BanBnXkFtZTgwMjM0MTI2MDE@._V1_SY1000_CR0,0,1498,1000_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTQ2NDkwNDk5NV5BMl5BanBnXkFtZTgwNDM0MTI2MDE@._V1_SY1000_CR0,0,1495,1000_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTM4NDcyNDMzMF5BMl5BanBnXkFtZTgwOTI0MTI2MDE@._V1_SY1000_CR0,0,1495,1000_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTAzMTczMjM3NjFeQTJeQWpwZ15BbWU4MDc1MTI1MzAx._V1_SY1000_CR0,0,1495,1000_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMjA5MTE3MTgwMF5BMl5BanBnXkFtZTgwOTQxMjUzMDE@._V1_SX1500_CR0,0,1500,999_AL_.jpg"),
trailer = "trailer_placeholder",
rating = "9.5"),
Movie(id = "tt2707408",
title = "Narcos",
year = "2015-",
genre = "Biography, Crime, Drama",
director = "N/A",
actors = "Wagner Moura, Boyd Holbrook, Pedro Pascal, Joanna Christie",
plot = "A chronicled look at the criminal exploits of Colombian drug lord Pablo Escobar.",
images = listOf("https://images-na.ssl-images-amazon.com/images/M/MV5BMTk2MDMzMTc0MF5BMl5BanBnXkFtZTgwMTAyMzA1OTE@._V1_SX1500_CR0,0,1500,999_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMjIxMDkyOTEyNV5BMl5BanBnXkFtZTgwNjY3Mjc3OTE@._V1_SY1000_SX1500_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMjA2NDUwMTU2NV5BMl5BanBnXkFtZTgwNTI1Mzc3OTE@._V1_SY1000_CR0,0,1499,1000_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BODA1NjAyMTQ3Ml5BMl5BanBnXkFtZTgwNjI1Mzc3OTE@._V1_SY1000_CR0,0,1499,1000_AL_.jpg",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMTU0NzQ0OTAwNl5BMl5BanBnXkFtZTgwMDAyMzA1OTE@._V1_SX1500_CR0,0,1500,999_AL_.jpg"),
trailer = "trailer_placeholder",
rating = "9.5"),
)
}
|
MAD-Exercise-03/app/src/main/java/com/example/movieappmad24/models/Movie.kt
|
1326595056
|
package com.example.movieappmad24.nav
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.navArgument
import com.example.movieappmad24.scenes.DetailScreen
import com.example.movieappmad24.scenes.HomeScreen
sealed class Screen(val route: String) {
object Home : Screen("homescreen")
object Details : Screen("detailscreen")
}
@Composable
fun Navigation(navController: NavHostController) {
NavHost(navController = navController, startDestination = Screen.Home.route) {
composable(Screen.Home.route) {
HomeScreen(navController)
}
composable(Screen.Details.route + "/{movieId}",
arguments = listOf(navArgument("movieId") { type = NavType.StringType })) { backStackEntry ->
val movieId = backStackEntry.arguments?.getString("movieId")
DetailScreen(movieId = movieId, navController = navController)
}
}
}
|
MAD-Exercise-03/app/src/main/java/com/example/movieappmad24/nav/Navigation.kt
|
1161382964
|
package com.example.uichalleng1
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.uichalleng1", appContext.packageName)
}
}
|
UiChallenge1/app/src/androidTest/java/com/example/uichalleng1/ExampleInstrumentedTest.kt
|
905070048
|
package com.example.uichalleng1
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)
}
}
|
UiChallenge1/app/src/test/java/com/example/uichalleng1/ExampleUnitTest.kt
|
158656746
|
package com.example.uichalleng1
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.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Search
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
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.clip
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
@Preview
@Composable
fun WalletSection() {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column {
Text(
text = "Wallet", fontSize = 17.sp, color = MaterialTheme.colorScheme.onBackground
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = "$ 44.475",
fontSize = 24.sp,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onBackground
)
}
Box(
modifier = Modifier
.clip(RoundedCornerShape(15.dp))
.background(MaterialTheme.colorScheme.secondaryContainer)
.clickable {}
.padding(6.dp),
) {
Icon(
imageVector = Icons.Rounded.Search,
contentDescription = "Search",
tint = MaterialTheme.colorScheme.onSecondaryContainer
)
}
}
}
|
UiChallenge1/app/src/main/java/com/example/uichalleng1/WalletSection.kt
|
1074281597
|
package com.example.uichalleng1.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
val PurpleStart = Color(0xFFD24BE9)
val PurpleEnd = Color(0xFFDF8FEC)
val BlueStart = Color(0xFF2196F3)
val BlueEnd = Color(0xFF79C3FD)
val OrangeStart = Color(0xFFFF8400)
val OrangeEnd = Color(0xFFFDA35F)
val GreenStart = Color(0xFF11B114)
val GreenEnd = Color(0xFF52DB59)
|
UiChallenge1/app/src/main/java/com/example/uichalleng1/ui/theme/Color.kt
|
2580958251
|
package com.example.uichalleng1.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 UiChalleng1Theme(
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
)
}
|
UiChallenge1/app/src/main/java/com/example/uichalleng1/ui/theme/Theme.kt
|
2142835000
|
package com.example.uichalleng1.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
)
*/
)
|
UiChallenge1/app/src/main/java/com/example/uichalleng1/ui/theme/Type.kt
|
872275444
|
package com.example.uichalleng1
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.example.uichalleng1.ui.theme.UiChalleng1Theme
import com.google.accompanist.systemuicontroller.rememberSystemUiController
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
UiChalleng1Theme {
// A surface container using the 'background' color from the theme
SetBarColor(color = MaterialTheme.colorScheme.background)
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
HomeScreen()
}
}
}
}
@Composable
private fun SetBarColor(color: Color) {
val systemUiController = rememberSystemUiController()
SideEffect {
systemUiController.setSystemBarsColor(
color = color
)
}
}
}
@Composable
fun HomeScreen() {
Scaffold(
bottomBar = {
BottomNavigationBar()
}
) { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
) {
WalletSection()
CardsSection()
Spacer(modifier = Modifier.height(16.dp))
FinanceSection()
CurrenciesSection()
}
}
}
|
UiChallenge1/app/src/main/java/com/example/uichalleng1/MainActivity.kt
|
3960262589
|
package com.example.uichalleng1
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.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.shape.RoundedCornerShape
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.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
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.uichalleng1.data.Card
import com.example.uichalleng1.ui.theme.*
val cards = listOf(
Card(
cardType = "VISA",
cardNumber = "3664 7865 3786 3976",
cardName = "Business",
balance = 46.467,
color = getGradient(PurpleStart, PurpleEnd),
),
Card(
cardType = "MASTER CARD",
cardNumber = "234 7583 7899 2223",
cardName = "Savings",
balance = 6.467,
color = getGradient(BlueStart, BlueEnd),
),
Card(
cardType = "VISA",
cardNumber = "0078 3467 3446 7899",
cardName = "School",
balance = 3.467,
color = getGradient(OrangeStart, OrangeEnd),
),
Card(
cardType = "MASTER CARD",
cardNumber = "3567 7865 3786 3976",
cardName = "Trips",
balance = 26.47,
color = getGradient(GreenStart, GreenEnd),
),
)
fun getGradient(
startColor: Color,
endColor: Color,
): Brush {
return Brush.horizontalGradient(
colors = listOf(startColor, endColor)
)
}
@Preview
@Composable
fun CardsSection() {
LazyRow {
items(cards.size) { index ->
CardItem(index)
}
}
}
@Composable
fun CardItem(
index: Int,
) {
val card = cards[index]
var lastItemPadding = 0.dp
if (index == cards.size - 1) {
lastItemPadding = 16.dp
}
var image = painterResource(id = R.drawable.ic_visa)
if (card.cardType == "MASTER CARD") {
image = painterResource(id = R.drawable.ic_mastercard)
}
Box(
modifier = Modifier.padding(start = 16.dp, end = lastItemPadding),
) {
Column(
modifier = Modifier
.clip(RoundedCornerShape(25.dp))
.background((card.color))
.width(250.dp)
.height(160.dp)
.clickable { }
.padding(vertical = 12.dp, horizontal = 16.dp),
verticalArrangement = Arrangement.SpaceBetween,
) {
Image(
painter = image, contentDescription = null, modifier = Modifier.width(60.dp)
)
Spacer(modifier = Modifier.height(10.dp))
Text(
text = card.cardName,
color = Color.White,
fontSize = 17.sp,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(10.dp))
Text(
text = "$ ${card.balance}",
color = Color.White,
fontSize = 22.sp,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = card.cardNumber,
color = Color.White,
fontSize = 17.sp,
fontWeight = FontWeight.Bold
)
}
}
}
|
UiChallenge1/app/src/main/java/com/example/uichalleng1/CardsSection.kt
|
973477735
|
package com.example.uichalleng1
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.AttachMoney
import androidx.compose.material.icons.rounded.CurrencyYen
import androidx.compose.material.icons.rounded.Euro
import androidx.compose.material.icons.rounded.KeyboardArrowDown
import androidx.compose.material.icons.rounded.KeyboardArrowUp
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
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.draw.clip
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.dp
import androidx.compose.ui.unit.sp
import com.example.uichalleng1.data.Currency
import com.example.uichalleng1.ui.theme.GreenStart
val currencies = listOf(
Currency(
name = "USD", buy = 23.35f, sell = 23.25f, icon = Icons.Rounded.AttachMoney
),
Currency(
name = "EUR", buy = 13.35f, sell = 13.25f, icon = Icons.Rounded.Euro
),
Currency(
name = "YEN", buy = 26.35f, sell = 26.35f, icon = Icons.Rounded.CurrencyYen
),
Currency(
name = "USD", buy = 23.35f, sell = 23.25f, icon = Icons.Rounded.AttachMoney
),
Currency(
name = "EUR", buy = 63.35f, sell = 73.25f, icon = Icons.Rounded.Euro
),
Currency(
name = "YEN", buy = 16.35f, sell = 16.35f, icon = Icons.Rounded.CurrencyYen
),
Currency(
name = "YEN", buy = 16.35f, sell = 16.35f, icon = Icons.Rounded.CurrencyYen
),
Currency(
name = "YEN", buy = 16.35f, sell = 16.35f, icon = Icons.Rounded.CurrencyYen
),
Currency(
name = "YEN", buy = 16.35f, sell = 16.35f, icon = Icons.Rounded.CurrencyYen
),
Currency(
name = "YEN", buy = 16.35f, sell = 16.35f, icon = Icons.Rounded.CurrencyYen
),
Currency(
name = "YEN", buy = 16.35f, sell = 16.35f, icon = Icons.Rounded.CurrencyYen
),
Currency(
name = "YEN", buy = 16.35f, sell = 16.35f, icon = Icons.Rounded.CurrencyYen
),
Currency(
name = "YEN", buy = 16.35f, sell = 16.35f, icon = Icons.Rounded.CurrencyYen
),
Currency(
name = "YEN", buy = 16.35f, sell = 16.35f, icon = Icons.Rounded.CurrencyYen
),
Currency(
name = "YEN", buy = 16.35f, sell = 16.35f, icon = Icons.Rounded.CurrencyYen
),
Currency(
name = "YEN", buy = 16.35f, sell = 16.35f, icon = Icons.Rounded.CurrencyYen
),
Currency(
name = "YEN", buy = 16.35f, sell = 16.35f, icon = Icons.Rounded.CurrencyYen
),
)
@Preview
@Composable
fun CurrenciesSection() {
var isVisible by remember {
mutableStateOf(false)
}
var iconState by remember {
mutableStateOf(Icons.Rounded.KeyboardArrowUp)
}
Box(
modifier = Modifier
.fillMaxSize()
.padding(top = 32.dp),
contentAlignment = Alignment.BottomCenter
) {
Column(
modifier = Modifier
.clip(RoundedCornerShape(topStart = 30.dp, topEnd = 30.dp))
.background(MaterialTheme.colorScheme.inverseOnSurface)
.animateContentSize()
) {
Row(
modifier = Modifier
.padding(16.dp)
.animateContentSize()
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Box(
modifier = Modifier
.clip(CircleShape)
.background(MaterialTheme.colorScheme.secondary)
.clickable {
isVisible = !isVisible
iconState = if (isVisible) {
Icons.Rounded.KeyboardArrowUp
} else {
Icons.Rounded.KeyboardArrowDown
}
},
) {
Icon(
imageVector = iconState,
contentDescription = "Currencies",
modifier = Modifier.size(24.dp),
tint = MaterialTheme.colorScheme.onSecondary
)
}
Spacer(modifier = Modifier.width(20.dp))
Text(
text = "Currencies",
fontSize = 20.sp,
color = MaterialTheme.colorScheme.onSecondaryContainer,
fontWeight = FontWeight.Bold
)
}
Spacer(
modifier = Modifier
.height(1.dp)
.fillMaxWidth()
.background(MaterialTheme.colorScheme.secondaryContainer)
)
if (isVisible) {
BoxWithConstraints(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
.clip(RoundedCornerShape(topStart = 25.dp, topEnd = 25.dp))
.background(MaterialTheme.colorScheme.background)
) {
val boxWithConstrainedScope = this
val width = boxWithConstrainedScope.maxWidth / 3
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Spacer(modifier = Modifier.height(16.dp))
Row(
modifier = Modifier.fillMaxWidth()
) {
Text(
modifier = Modifier
.width(width)
.padding(start = 15.dp),
text = "Currencies",
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.onBackground
)
Text(
modifier = Modifier
.width(width)
.padding(start = 30.dp, end = 30.dp),
text = "Buy",
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.onBackground,
textAlign = TextAlign.End
)
Text(
modifier = Modifier
.width(width)
.padding(start = 30.dp, end = 30.dp),
text = "Sell",
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.onBackground,
)
}
Spacer(modifier = Modifier.height(16.dp))
LazyColumn {
items(currencies.size) {
CurrencyItem(it, width)
}
}
}
}
}
}
}
}
@Composable
fun CurrencyItem(it: Int, width: Dp) {
val currency = currencies[it]
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically
) {
Row(
modifier = Modifier.width(width), verticalAlignment = Alignment.CenterVertically
) {
Box(
modifier = Modifier
.clip(RoundedCornerShape(8.dp))
.background(GreenStart)
.padding(4.dp)
) {
Icon(
modifier = Modifier.size(18.dp),
imageVector = currency.icon,
contentDescription = currency.name,
tint = Color.White
)
}
Text(
modifier = Modifier.padding(start = 10.dp),
text = currency.name,
fontWeight = FontWeight.Bold,
fontSize = 18.sp,
color = MaterialTheme.colorScheme.onBackground
)
}
Text(
modifier = Modifier.padding(start = 40.dp),
text = "$ ${currency.buy}",
fontWeight = FontWeight.SemiBold,
fontSize = 16.sp,
color = MaterialTheme.colorScheme.onBackground,
textAlign = TextAlign.End
)
Text(
modifier = Modifier.padding(start = 20.dp),
text = "$ ${currency.sell}",
fontWeight = FontWeight.SemiBold,
fontSize = 16.sp,
color = MaterialTheme.colorScheme.onBackground,
textAlign = TextAlign.End
)
}
}
|
UiChallenge1/app/src/main/java/com/example/uichalleng1/CurrenciesSection.kt
|
762890022
|
package com.example.uichalleng1
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Row
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.AccountCircle
import androidx.compose.material.icons.rounded.Home
import androidx.compose.material.icons.rounded.Notifications
import androidx.compose.material.icons.rounded.Wallet
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.uichalleng1.data.BottomNavigation
val items = listOf(
BottomNavigation(
title = "Home", icon = Icons.Rounded.Home
),
BottomNavigation(
title = "Wallet", icon = Icons.Rounded.Wallet
),
BottomNavigation(
title = "Notifications", icon = Icons.Rounded.Notifications
),
BottomNavigation(
title = "Account", icon = Icons.Rounded.AccountCircle
)
)
@Preview
@Composable
fun BottomNavigationBar() {
NavigationBar {
Row(
modifier = Modifier.background(MaterialTheme.colorScheme.inverseOnSurface)
) {
items.forEachIndexed { index, item ->
NavigationBarItem(selected = index == 0, onClick = {}, icon = {
Icon(
imageVector = item.icon,
contentDescription = item.title,
tint = MaterialTheme.colorScheme.onBackground
)
}, label = {
Text(
text = item.title, color = MaterialTheme.colorScheme.onBackground
)
})
}
}
}
}
|
UiChallenge1/app/src/main/java/com/example/uichalleng1/BottomNavigationBar.kt
|
223423100
|
package com.example.uichalleng1.data
import androidx.compose.ui.graphics.Brush
data class Card(
val cardType: String,
val cardNumber: String,
val cardName: String,
val balance: Double,
val color: Brush
)
|
UiChallenge1/app/src/main/java/com/example/uichalleng1/data/Card.kt
|
4151809679
|
package com.example.uichalleng1.data
import androidx.compose.ui.graphics.vector.ImageVector
data class BottomNavigation(
val title: String, val icon: ImageVector
)
|
UiChallenge1/app/src/main/java/com/example/uichalleng1/data/BottomNavigation.kt
|
1927224706
|
package com.example.uichalleng1.data
import androidx.compose.ui.graphics.vector.ImageVector
data class Currency (
val name: String,
val buy: Float,
val sell: Float,
val icon: ImageVector
)
|
UiChallenge1/app/src/main/java/com/example/uichalleng1/data/Currency.kt
|
2700953411
|
package com.example.uichalleng1.data
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
data class Finance(
val icon: ImageVector,
val name: String,
val background: Color
)
|
UiChallenge1/app/src/main/java/com/example/uichalleng1/data/Fianance.kt
|
3796017273
|
package com.example.uichalleng1
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.MonetizationOn
import androidx.compose.material.icons.rounded.StarHalf
import androidx.compose.material.icons.rounded.Wallet
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
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.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.uichalleng1.data.Finance
import com.example.uichalleng1.ui.theme.BlueStart
import com.example.uichalleng1.ui.theme.GreenStart
import com.example.uichalleng1.ui.theme.OrangeStart
import com.example.uichalleng1.ui.theme.PurpleStart
val financeList = listOf(
Finance(
icon = Icons.Rounded.StarHalf, name = "My\nBusiness", background = OrangeStart
),
Finance(
icon = Icons.Rounded.Wallet, name = "My\nWallet", background = BlueStart
),
Finance(
icon = Icons.Rounded.StarHalf, name = "Finance\nAnalytics", background = PurpleStart
),
Finance(
icon = Icons.Rounded.MonetizationOn, name = "My\nTransactions", background = GreenStart
),
)
@Preview
@Composable
fun FinanceSection() {
Column {
Text(
text = "Finance",
fontSize = 24.sp,
color = MaterialTheme.colorScheme.onBackground,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(16.dp)
)
LazyRow {
items(financeList.size) {
FinanceItem(it)
}
}
}
}
@Composable
fun FinanceItem(
it: Int
) {
val finance = financeList[it]
var lastItemPadding = 0.dp
if (it == financeList.size - 1) {
lastItemPadding = 16.dp
}
Box (
modifier = Modifier.padding(start = 16.dp, end = lastItemPadding)
){
Column(
modifier = Modifier
.clip(RoundedCornerShape(25.dp))
.background(MaterialTheme.colorScheme.secondaryContainer)
.size(120.dp)
.clickable { }
.padding(13.dp),
verticalArrangement = Arrangement.SpaceBetween
) {
Box(
modifier = Modifier
.clip(RoundedCornerShape(16.dp))
.background(finance.background)
.padding(6.dp)
) {
Icon(
imageVector = finance.icon, contentDescription = finance.name,
tint = Color.White
)
}
Text(
text = finance.name,
color = MaterialTheme.colorScheme.onSecondaryContainer,
fontWeight = FontWeight.SemiBold,
fontSize = 15.sp
)
}
}
}
|
UiChallenge1/app/src/main/java/com/example/uichalleng1/FinanceSection.kt
|
3854135574
|
fun main(args: Array<String>) {
println("Hello World!")
// Try adding program arguments via Run/Debug configuration.
// Learn more about running applications: https://www.jetbrains.com/help/idea/running-applications.html.
println("Program arguments: ${args.joinToString()}")
}
|
SQL_s08/src/main/kotlin/Main.kt
|
3350697704
|
package com.example.viewbinding_checkbox
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.viewbinding_checkbox", appContext.packageName)
}
}
|
binding_and_checkbox/app/src/androidTest/java/com/example/viewbinding_checkbox/ExampleInstrumentedTest.kt
|
3801206146
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.