content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.firstkotlin
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.firstkotlin", appContext.packageName)
}
} | firstKotlin/app/src/androidTest/java/com/example/firstkotlin/ExampleInstrumentedTest.kt | 2199436650 |
package com.example.firstkotlin
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)
}
} | firstKotlin/app/src/test/java/com/example/firstkotlin/ExampleUnitTest.kt | 612195727 |
package com.example.firstkotlin.RView
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.example.firstkotlin.R
class FifthActivity:AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.fifth_layout)
}
} | firstKotlin/app/src/main/java/com/example/firstkotlin/RView/FifthActivity.kt | 4057098233 |
package com.example.firstkotlin.RView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import androidx.recyclerview.widget.RecyclerView.inflate
import com.example.firstkotlin.ListView.Fruit
import com.example.firstkotlin.R
//class FifthAdapter:RecyclerView.Adapter<ViewHolder>() {
//
// inner class ViewHolder(view: View):RecyclerView.ViewHolder(view){
// private val imageView:ImageView = view.findViewById(R.id.fruitImage)
// private val textView:TextView = view.findViewById(R.id.fruitName)
//
// fun bindViewHolderItem(fruit: Fruit){
// imageView.setImageResource(fruit.imageId)
// textView.text = fruit.name
// }
// }
//
// override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
// val view = LayoutInflater.from(parent.context).inflate(R.layout.fruit_item,parent,false)
// }
//
// override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
// TODO("Not yet implemented")
// }
//
// override fun getItemCount(): Int {
// TODO("Not yet implemented")
// }
//
//} | firstKotlin/app/src/main/java/com/example/firstkotlin/RView/FifthAdapter.kt | 3198191345 |
package com.example.firstkotlin.ViewModel
import androidx.lifecycle.ViewModel
class MainViewModel : ViewModel() {
var counter = 0
} | firstKotlin/app/src/main/java/com/example/firstkotlin/ViewModel/MainViewModel.kt | 3534791902 |
package com.example.firstkotlin.ViewModel.VMLivingData
import android.content.SharedPreferences
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.firstkotlin.R
class ClickCounterLD:AppCompatActivity() {
lateinit var viewModel: ClickCounterVMLD
//延迟初始化,从轻量数据库取数据的
lateinit var sp: SharedPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.clickcounter_ld)
//创建sp的示例,不过传递的常数并不知道是什么
sp = getSharedPreferences("data", MODE_PRIVATE)
//为counterReserved设置初始的值
val counterReserved = sp.getInt("counter_reserved", 3)
//创建VM实例
viewModel = ViewModelProvider(this, ClickCounterF(counterReserved)).get(
ClickCounterVMLD::class.java)
val plusOne = findViewById<Button>(R.id.plusOneBtn)
plusOne.setOnClickListener {
viewModel.plusOne()
}
val clear = findViewById<Button>(R.id.clearBtn)
clear.setOnClickListener {
viewModel.clear()
}
viewModel.counter.observe(this) { count ->
val infoText = findViewById<TextView>(R.id.infoText)
infoText.text = count.toString()
}
}
override fun onPause() {
super.onPause()
sp.edit() {
putInt("counter_reserved", viewModel.counter.value ?: 0)
}
}
} | firstKotlin/app/src/main/java/com/example/firstkotlin/ViewModel/VMLivingData/ClickCounterLD.kt | 863606984 |
package com.example.firstkotlin.ViewModel.VMLivingData
data class User(var firstName: String, var lastName: String, var age: Int) | firstKotlin/app/src/main/java/com/example/firstkotlin/ViewModel/VMLivingData/User.kt | 2634410864 |
package com.example.firstkotlin.ViewModel.VMLivingData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.firstkotlin.ViewModel.ClickCounterVM
//这段代码很多不会的,交给以后的我吧
class ClickCounterF(private val countReserved: Int) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return ClickCounterVM(countReserved) as T
}
} | firstKotlin/app/src/main/java/com/example/firstkotlin/ViewModel/VMLivingData/ClickCounterF.kt | 3841673842 |
package com.example.firstkotlin.ViewModel.VMLivingData
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class ClickCounterVMLD(countReserved: Int) : ViewModel() {
private val userLiveData = MutableLiveData<User>()
// val userName: LiveData<String> = Transformations.map(userLiveData) { user -> "${user.frist}"
//这里我暂时不能理解,交给后来的人吧
val counter: LiveData<Int>
get() = _counter
private val _counter = MutableLiveData<Int>()
//这里在init结构体中给counter设置数据,这样之前保存的计数值就可以在初始化的时候得到恢复
init {
_counter.value = countReserved
}
fun plusOne() {
val count = _counter.value ?: 0
_counter.value = count + 1
}
fun clear() {
_counter.value = 0
}
} | firstKotlin/app/src/main/java/com/example/firstkotlin/ViewModel/VMLivingData/ClickCounterVMLD.kt | 1630731007 |
package com.example.firstkotlin.ViewModel
import android.content.SharedPreferences
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.get
import com.example.firstkotlin.R
class ClickCounter : AppCompatActivity() {
lateinit var viewModel: ClickCounterVM
//延迟初始化,从轻量数据库取数据的
lateinit var sp: SharedPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.clickcounter)
//创建sp的示例,不过传递的常数并不知道是什么
sp = getSharedPreferences("data", MODE_PRIVATE)
//为counterReserved设置初始的值
val counterReserved = sp.getInt("counter_reserved", 3)
//创建VM实例
viewModel = ViewModelProvider(this,ClickCounterViewModelFactory(counterReserved)).get(ClickCounterVM::class.java)
//设置按钮监听
val onPlusOne = findViewById<Button>(R.id.plusOneBtn)
onPlusOne.setOnClickListener {
viewModel.counter++
refreshCounter()
}
val clearBtn = findViewById<Button>(R.id.clearBtn)
clearBtn.setOnClickListener {
viewModel.counter = 0
refreshCounter()
}
refreshCounter()
}
private fun refreshCounter() {
val infotext = findViewById<TextView>(R.id.infoText)
infotext. text = viewModel.counter.toString()
}
/*
* override fun onPause() {:这是 onPause() 方法的重写,它是 Android 生命周期的一部分。当应用程序失去焦点或进入后台时,系统会调用 onPause() 方法。
* super.onPause():这是调用父类的 onPause() 方法,以确保执行父类中的相关逻辑。通常,在重写生命周期方法时,我们会调用父类的方法。
* sp.edit {:这里的 sp 是一个 SharedPreferences 对象的实例,用于获取和修改 SharedPreferences 数据。通过调用 edit() 方法,我们获得了一个 SharedPreferences.Editor 对象,用于进行修改操作。
* putInt("count_reserved", viewModel.counter):这行代码使用 putInt() 方法将名为 "count_reserved" 的键和 viewModel.counter 的值存储到 SharedPreferences 中。viewModel.counter 是一个 ViewModel 中的计数器属性,它的值将被保存。
* */
override fun onPause() {
super.onPause()
sp.edit() {
putInt("counter_reserved", viewModel.counter)
}
}
} | firstKotlin/app/src/main/java/com/example/firstkotlin/ViewModel/ClickCounter.kt | 3383334180 |
package com.example.firstkotlin.ViewModel
import androidx.lifecycle.ViewModel
class ClickCounterVM(countReserved: Int) : ViewModel() {
var counter = countReserved
} | firstKotlin/app/src/main/java/com/example/firstkotlin/ViewModel/ClickCounterVM.kt | 4266570684 |
package com.example.firstkotlin.ViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
//这段代码很多不会的,交给以后的我吧
class ClickCounterViewModelFactory(private val countReserved: Int) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return ClickCounterVM(countReserved) as T
}
} | firstKotlin/app/src/main/java/com/example/firstkotlin/ViewModel/MainViewModelFactory.kt | 378981095 |
package com.example.firstkotlin
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
class ThirdActivity:AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.third_layout)
val extraData = intent.getStringExtra("extra_data")
Log.d("页面3","页面2传过来的值是 $extraData")
}
} | firstKotlin/app/src/main/java/com/example/firstkotlin/ThirdActivity.kt | 4236785566 |
package com.example.firstkotlin
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.example.firstkotlin.Data.SharedPreferencesTest
import com.example.firstkotlin.Data.WritingData
import com.example.firstkotlin.BroadcastReceiver.BroadcastTest
import com.example.firstkotlin.Data.SqlDataBase.SQLData_MainActivity
import com.example.firstkotlin.Login.LoginActivity
import com.example.firstkotlin.RView.FifthActivity
import com.example.firstkotlin.ViewModel.ClickCounter
import com.example.firstkotlin.ViewModel.MainViewModel
import com.example.firstkotlin.ViewModel.VMLivingData.ClickCounterLD
class MainActivity : AppCompatActivity() {
lateinit var viewModel : MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
//按钮1的跳转设置
val button1 : Button = findViewById(R.id.button1)
button1.setOnClickListener {
val intent = Intent("com.example.activitytest.ACTION_START")
startActivityForResult(intent,1)
Toast.makeText(this,"点击了button1按钮",Toast.LENGTH_SHORT).show()
}
//按钮2的跳转设置
val button2 : Button = findViewById(R.id.button2)
button2.setOnClickListener {
val intent2 = Intent("android.intent.action.FORTH")
startActivity(intent2)
Toast.makeText(this,"点击了button1_2按钮",Toast.LENGTH_SHORT).show()
}
//按钮3的跳转设置
val button3 : Button = findViewById(R.id.button3)
button3.setOnClickListener {
val intent3 = Intent(this,FifthActivity::class.java)
startActivity(intent3)
Toast.makeText(this,"点击了button1_3按钮",Toast.LENGTH_SHORT).show()
}
//按钮4的跳转设置
val button4 : Button = findViewById(R.id.button4)
button4.setOnClickListener {
val intent4 = Intent(this,ClickCounter::class.java)
startActivity(intent4)
Toast.makeText(this,"点击了button1_4 VM按钮",Toast.LENGTH_SHORT).show()
}
//按钮5的跳转设置
val button5 : Button = findViewById(R.id.button5)
button5.setOnClickListener {
val intent5 = Intent(this,ClickCounterLD::class.java)
startActivity(intent5)
Toast.makeText(this,"点击了button1_5 VMLD按钮",Toast.LENGTH_SHORT).show()
}
//按钮5.5的跳转设置
val button5_5 : Button = findViewById(R.id.button5_5)
button5_5.setOnClickListener {
val intent5_5 = Intent(this, BroadcastTest::class.java)
startActivity(intent5_5)
Toast.makeText(this,"点击了button7 Share Preferences",Toast.LENGTH_SHORT).show()
}
//按钮5.7的跳转设置
val button5_7 : Button = findViewById(R.id.button5_7)
button5_7.setOnClickListener {
val intent5_7 = Intent(this, LoginActivity::class.java)
startActivity(intent5_7)
Toast.makeText(this,"点击了button 登录页",Toast.LENGTH_SHORT).show()
}
//按钮6的跳转设置
val button6 : Button = findViewById(R.id.button6)
button6.setOnClickListener {
val intent6 = Intent(this,WritingData::class.java)
startActivity(intent6)
Toast.makeText(this,"点击了button6 Data",Toast.LENGTH_SHORT).show()
}
//按钮7的跳转设置
val button7 : Button = findViewById(R.id.button7)
button7.setOnClickListener {
val intent7 = Intent(this,SharedPreferencesTest::class.java)
startActivity(intent7)
Toast.makeText(this,"点击了button7 Share Preferences",Toast.LENGTH_SHORT).show()
}
//按钮8的跳转设置
val button8 : Button = findViewById(R.id.button8)
button8.setOnClickListener {
val intent8 = Intent(this,SQLData_MainActivity::class.java)
startActivity(intent8)
Toast.makeText(this,"SQLdb",Toast.LENGTH_SHORT).show()
}
//viewModel的设置
//不可以直接去创建ViewModel的实例,而是一定要通过ViewModelProvider来获取ViewModel的实例
//ViewModelProvider(<你的Activity或Fragment实例>).get(<你的ViewModel>::class.java)
viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
//声明按钮,设置按钮的响应
val plusonebtn = findViewById<Button>(R.id.plusOneBtn)
plusonebtn.setOnClickListener {
viewModel.counter++
//按按钮后执行动作,并把新值写入
refreshCounter()
}
//写入完了之后就会按顺序再到这里执行,这次展示的值就是新值
refreshCounter()
}
//给TextView赋值,一个方法
private fun refreshCounter() {
val infoText = findViewById<TextView>(R.id.infoText)
infoText.text = viewModel.counter.toString()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when(requestCode){
1 -> if(resultCode == RESULT_OK){
val returnedData = data?.getStringExtra("data_return")
Toast.makeText(this,returnedData,Toast.LENGTH_SHORT).show()
}
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.add_item -> Toast.makeText(this, "You clicked Add",
Toast.LENGTH_SHORT).show()
R.id.remove_item -> Toast.makeText(this, "You clicked Remove",
Toast.LENGTH_SHORT).show()
}
return true
}
}
| firstKotlin/app/src/main/java/com/example/firstkotlin/MainActivity.kt | 2823656001 |
package com.example.firstkotlin
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.second_layout)
val button2: Button = findViewById(R.id.button2)
button2.setOnClickListener {
val data = "你好,页面3"
val intent = Intent(this,ThirdActivity::class.java)
intent.putExtra("extra_data",data)
startActivity(intent)
}
val buttonFinish: Button = findViewById(R.id.button_finish)
buttonFinish.setOnClickListener {
val intent = Intent()
intent.putExtra("data_return","你好,页面1")
setResult(RESULT_OK,intent)
finish()
}
}
} | firstKotlin/app/src/main/java/com/example/firstkotlin/SecondActivity.kt | 460733346 |
package com.example.firstkotlin.ListView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.TextView
import com.example.firstkotlin.R
import org.w3c.dom.Text
class FruitAdapter(activity: ForthActivity, val resourceId: Int, data: List<Fruit>) :
ArrayAdapter<Fruit>(activity, resourceId, data) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
//还是不知道有什么用,就当标准写法了
val view = LayoutInflater.from(context).inflate(resourceId, parent, false)
val fruitImage: ImageView = view.findViewById(R.id.fruitImage)
val fruitName: TextView = view.findViewById(R.id.fruitName)
//获取当前实例
val fruit:Fruit? = getItem(position)
if (fruit != null) {
fruitImage.setImageResource(fruit.imageId)
fruitName.text = fruit.name
}
return view
}
} | firstKotlin/app/src/main/java/com/example/firstkotlin/ListView/FruitAdapter.kt | 4143753059 |
package com.example.firstkotlin.ListView
class Fruit(val name:String, val imageId: Int) | firstKotlin/app/src/main/java/com/example/firstkotlin/ListView/Fruit.kt | 2188565622 |
package com.example.firstkotlin.ListView
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.firstkotlin.R
class ForthActivity : AppCompatActivity() {
private val fruitList = ArrayList<Fruit>()
// ("鸡蛋", "香肠", "香肠", "",
// "虾", "猕猴桃", "柠檬", "葡萄", "牛油果", "西瓜",
// "山竹", "肉", "菜", "胡萝卜", "西红柿", "香菇",
// "青椒", "玉米", "葱姜蒜", "土豆")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.forth_layout)
initFruits()
val listView = findViewById<ListView>(R.id.listView)
val adapter = FruitAdapter(this, R.layout.fruit_item, fruitList)
listView.adapter = adapter
listView.setOnItemClickListener { _, _, position, _ ->
val fruitPosition = fruitList[position]
Toast.makeText(this,fruitPosition.name,Toast.LENGTH_SHORT).show()
}
}
private fun initFruits() {
fruitList.add(Fruit("鸡蛋", R.mipmap.jidan))
fruitList.add(Fruit("香肠", R.mipmap.xiangchang))
fruitList.add(Fruit("鱼", R.mipmap.yu))
fruitList.add(Fruit("虾", R.mipmap.xia))
fruitList.add(Fruit("猕猴桃", R.mipmap.mihoutao))
fruitList.add(Fruit("柠檬", R.mipmap.ningmeng))
fruitList.add(Fruit("葡萄", R.mipmap.putao))
fruitList.add(Fruit("牛油果", R.mipmap.niuyouguo))
fruitList.add(Fruit("西瓜", R.mipmap.xigua))
fruitList.add(Fruit("山竹", R.mipmap.shanzhu))
fruitList.add(Fruit("肉", R.mipmap.rou))
fruitList.add(Fruit("菜", R.mipmap.cai))
fruitList.add(Fruit("胡萝卜", R.mipmap.huluobo))
fruitList.add(Fruit("西红柿", R.mipmap.xihongshi))
fruitList.add(Fruit("香菇", R.mipmap.xianggu))
fruitList.add(Fruit("青椒", R.mipmap.qingjiao))
fruitList.add(Fruit("玉米", R.mipmap.yumi))
fruitList.add(Fruit("葱姜蒜", R.mipmap.jiangcongsuan))
fruitList.add(Fruit("土豆", R.mipmap.tudou))
}
} | firstKotlin/app/src/main/java/com/example/firstkotlin/ListView/ForthActivity.kt | 1176593025 |
package com.example.firstkotlin.Data.Room
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
@Dao
interface UserDao {
@Insert
fun insertUser(user: User): Long
@Update
fun updateUser(newUser: User)
@Query("select * from User")
fun loadAllUsers(): List<User>
@Query("select * from User where age > :age")
fun loadUsersOlderThan(age: Int): List<User>
@Delete
fun deleteUser(user: User)
@Query("delete from User where lastName = :lastName")
fun deleteUserByLastName(lastName: String): Int
} | firstKotlin/app/src/main/java/com/example/firstkotlin/Data/Room/UserDao.kt | 2900606523 |
package com.example.firstkotlin.Data.Room
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(version = 1, entities = [User::class])
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
companion object {
private var instance: AppDatabase? = null
//@Synchronized 是一个注解,用于实现线程同步。它可以应用于函数或代码块,用于确保在同一时间只能有一个线程访问被注解的函数或代码块
@Synchronized
fun getDatabase(context: Context): AppDatabase {
instance?.let {
return it
}
return Room.databaseBuilder(context.applicationContext,
AppDatabase::class.java, "app_database")
.build().apply {
instance = this
}
}
}
} | firstKotlin/app/src/main/java/com/example/firstkotlin/Data/Room/AppDatabase.kt | 1507382296 |
package com.example.firstkotlin.Data.Room
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class User(var firstName: String, var lastName: String, var age: Int) {
//使用@PrimaryKey注解将它设为了主键,再把autoGenerate参数指定成true
@PrimaryKey(autoGenerate = true)
var id: Long = 0
} | firstKotlin/app/src/main/java/com/example/firstkotlin/Data/Room/User.kt | 3538972227 |
package com.example.firstkotlin.Data
import android.content.Context
import android.os.Bundle
import android.widget.EditText
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import com.example.firstkotlin.R
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.IOException
import java.io.InputStreamReader
import java.io.OutputStreamWriter
class WritingData : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_writing_data)
val editText1 = findViewById<EditText>(R.id.editText)
val inputText = load()
if (inputText.isNotEmpty()){
editText1.setText(inputText)
// 将光标移动到最后
editText1.setSelection(inputText.length)
Toast.makeText(this,"读取数据成功",Toast.LENGTH_SHORT).show()
}
}
override fun onDestroy() {
super.onDestroy()
val dataInput = findViewById<EditText>(R.id.editText)
val inputText = dataInput.text.toString()
save(inputText)
}
/**
* 一个写入文件里的方法
* */
private fun save(inputText: String) {
try {
val output = openFileOutput("data", Context.MODE_PRIVATE)
val writer = BufferedWriter(OutputStreamWriter(output))
// use函数,这是Kotlin提供的一个内置扩展函数。
// 它会保证在Lambda表达式中的代码全部执行完之后自动将外层的流关闭,这样就不需要我们再编写一个finally语句,手动去关闭流了,是一个非常好用的扩展函数。
writer.use {
it.write(inputText)
}
} catch (e: IOException) {
e.printStackTrace()
}
}
/**
* 一个读取文件里的方法
* */
private fun load():String {
val content = StringBuilder()
try {
val input = openFileInput("data")
val reader = BufferedReader(InputStreamReader(input))
reader.use {
reader.forEachLine {
content.append(it)
}
}
}catch (e:IOException){
e.printStackTrace()
}
return content.toString()
}
} | firstKotlin/app/src/main/java/com/example/firstkotlin/Data/WritingData.kt | 353148252 |
package com.example.firstkotlin.Data.SqlDataBase
import android.content.ContentValues
import android.os.Bundle
import android.widget.Button
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.firstkotlin.R
class SQLData_MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sqldata_main)
//绑定按钮
val createDatabase = findViewById<Button>(R.id.createDatabase)
val dbHelper = MyDatabaseHelper(this, "BookStore.db", 2)
createDatabase.setOnClickListener {
dbHelper.writableDatabase
}
//绑定按钮
val addData = findViewById<Button>(R.id.addData)
addData.setOnClickListener {
val db = dbHelper.writableDatabase
val values1 = ContentValues().apply {
//开始组装第一条数据
put("name", "The Da Vinci Code")
put("author", "John Johnson")
put("pages", 454)
put("price", 16.96)
}
//插入第一条数据
db.insert("Book", null, values1)
val values2 = ContentValues().apply {
put("name", "The Lost Symbol")
put("author", "Dan")
put("pages", 510)
put("price", 19.95)
}
db.insert("Book", null, values2)
}
}
}
| firstKotlin/app/src/main/java/com/example/firstkotlin/Data/SqlDataBase/SQLData_MainActivity.kt | 593447308 |
package com.example.firstkotlin.Data.SqlDataBase
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.widget.Toast
class MyDatabaseHelper(val context: Context, name: String, version: Int) :
SQLiteOpenHelper(context, name, null, version) {
private val createBook = "create table Book (" +
" id integer primary key autoincrement," +
"author text," +
"price real," +
"pages integer," +
"name text)"
private val category = "create table Category (" +
"id integer primary key autoincrement," +
"category_name text," +
"category_code integer)"
override fun onCreate(db: SQLiteDatabase) {
db.execSQL(createBook)
db.execSQL(category)
Toast.makeText(context, "Create succeeded", Toast.LENGTH_SHORT).show()
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
db.execSQL("drop table if exists Book")
db.execSQL("drop table if exists Category")
onCreate(db)
}
} | firstKotlin/app/src/main/java/com/example/firstkotlin/Data/SqlDataBase/MyDatabaseHelper.kt | 1357139453 |
package com.example.firstkotlin.Data
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.widget.Button
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.firstkotlin.R
class SharedPreferencesTest : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_shared_preferences_test)
//存储数据
val saveBtn = findViewById<Button>(R.id.saveButton)
saveBtn.setOnClickListener{
val editor = getSharedPreferences("data", Context.MODE_PRIVATE).edit()
editor.putString("name","你爹")
editor.putInt("age",28)
editor.putBoolean("married",false)
editor.apply()
}
//读取数据
val restoreBtn = findViewById<Button>(R.id.restoreButton)
restoreBtn.setOnClickListener{
val prefs = getSharedPreferences("data",Context.MODE_PRIVATE)
val name = prefs.getString("name","")
val age = prefs.getInt("age",0)
val married = prefs.getBoolean("married",false)
Log.d("SharedPreferencesTest","name is $name")
Log.d("SharedPreferencesTest","age is $age")
Log.d("SharedPreferencesTest","married is $married")
}
}
} | firstKotlin/app/src/main/java/com/example/firstkotlin/Data/SharedPreferencesTest.kt | 2805989570 |
package com.example.firstkotlin.BroadcastReceiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.widget.Toast
class MyBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Toast.makeText(context, "received in MyBroadcastReceiver", Toast.LENGTH_SHORT).show()
}
} | firstKotlin/app/src/main/java/com/example/firstkotlin/BroadcastReceiver/MyBroadcastReceiver.kt | 3312730221 |
package com.example.firstkotlin.BroadcastReceiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import com.example.firstkotlin.R
class BroadcastTest : AppCompatActivity() {
lateinit var timeChangeReceiver: TimeChangeReceiver
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_broadcast_test)
val sentBC = findViewById<Button>(R.id.button)
sentBC.setOnClickListener {
val intent =Intent("com.example.broadcasttest.MY_BROADCAST")
intent.setPackage(packageName)
sendBroadcast(intent)
}
// //BroadcastReceiver想要监听什么广播,就在这里添加相应的action
// val intentFilter = IntentFilter()
// intentFilter.addAction("android.intent.action.TIME_TICK")
//
// timeChangeReceiver = TimeChangeReceiver()
// registerReceiver(timeChangeReceiver, intentFilter)
}
//在注册广播接收器之后,需要在不再需要接收广播消息时调用 unregisterReceiver() 方法来取消注册,以避免内存泄漏
//成对存在
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(timeChangeReceiver)
}
inner class TimeChangeReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Toast.makeText(context, "时间刷新了", Toast.LENGTH_SHORT).show()
}
}
} | firstKotlin/app/src/main/java/com/example/firstkotlin/BroadcastReceiver/BroadcastTest.kt | 160734710 |
package com.example.firstkotlin.Login
import android.app.AlertDialog
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
open class BaseActivity : AppCompatActivity() {
lateinit var recevier: ForceOfflineReceiver
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
ActivityCollector.addActivity(this)
}
override fun onDestroy() {
super.onDestroy()
ActivityCollector.removeActivity(this)
}
override fun onResume() {
super.onResume()
val intentFilter = IntentFilter()
intentFilter.addAction("com.example.broadcastbestpractice.FORCE_OFFLINE")
recevier = ForceOfflineReceiver()
registerReceiver(recevier, intentFilter)
}
//始终需要保证只有处于栈顶的Activity才能接收到这条强制下线广播
override fun onPause() {
super.onPause()
unregisterReceiver(recevier)
}
inner class ForceOfflineReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
AlertDialog.Builder(context).apply {
setTitle("强制退出")
setMessage("你被强制登出下线了")
setCancelable(false)
setPositiveButton("OjbK") { _, _ ->
//销毁所有的Activity
ActivityCollector.finishAll()
val i = Intent(context, LoginActivity::class.java)
context.startActivity(i)
}
show()
}
}
}
} | firstKotlin/app/src/main/java/com/example/firstkotlin/Login/BaseActivity.kt | 724712306 |
package com.example.firstkotlin.Login
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.firstkotlin.R
class LoginMainActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login_main)
//强制下线功能
val forceOfflineBtn = findViewById<Button>(R.id.forceOffline)
forceOfflineBtn.setOnClickListener {
val intent = Intent("com.example.broadcastbestpractice.FORCE_OFFLINE")
sendBroadcast(intent)
}
}
} | firstKotlin/app/src/main/java/com/example/firstkotlin/Login/LoginMainActivity.kt | 3460956407 |
package com.example.firstkotlin.Login
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.firstkotlin.MainActivity
import com.example.firstkotlin.R
class LoginActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
//声明那些控件
val loginBtn = findViewById<Button>(R.id.login)
val accountEdit = findViewById<EditText>(R.id.accountEdit)
val passwordEdit = findViewById<EditText>(R.id.passwordEdit)
val cbRememberPass = findViewById<CheckBox>(R.id.rememberPass)
val prefs = getPreferences(Context.MODE_PRIVATE)
val isRemember = prefs.getBoolean("remember_password",false)
if(isRemember){
//将账号密码设置到文本框中
val account = prefs.getString("account","")
val password = prefs.getString("password","")
accountEdit.setText(account)
passwordEdit.setText(password)
//设置选项为勾选
cbRememberPass.isChecked = true
}
//登录的功能
loginBtn.setOnClickListener {
val account = accountEdit.text.toString()
val password = passwordEdit.text.toString()
// 如果账号是Admin 且密码是123456,就认为登录成功
if (account == "Admin" && password == "123456") {
val editor = prefs.edit()
if(cbRememberPass.isChecked){
editor.putBoolean("remember_password",true)
editor.putString("account",account)
editor.putString("password",password)
}else{
editor.clear()
}
//提交内容进行保存
editor.apply()
//设置登录后的跳转
val intent = Intent(this,LoginMainActivity::class.java)
startActivity(intent)
finish()
}else{
Toast.makeText(this,"wrongPassword",Toast.LENGTH_SHORT).show()
}
}
}
} | firstKotlin/app/src/main/java/com/example/firstkotlin/Login/LoginActivity.kt | 3082184721 |
package com.example.firstkotlin.Login
import android.app.Activity
object ActivityCollector {
private val activities = ArrayList<Activity>()
fun addActivity(activity: Activity) {
activities.add(activity)
}
fun removeActivity(activity: Activity) {
activities.remove(activity)
}
fun finishAll() {
for (activity in activities) {
if (!activity.isFinishing) {
activity.finish()
}
}
activities.clear()
}
} | firstKotlin/app/src/main/java/com/example/firstkotlin/Login/ActivityCollector.kt | 3979812481 |
package com.example.grader_t
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.grader_t", appContext.packageName)
}
} | Grader_T/app/src/androidTest/java/com/example/grader_t/ExampleInstrumentedTest.kt | 4145182736 |
package com.example.grader_t
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)
}
} | Grader_T/app/src/test/java/com/example/grader_t/ExampleUnitTest.kt | 2712391639 |
package com.example.grader_t
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)
}
} | Grader_T/app/src/main/java/com/example/grader_t/MainActivity.kt | 2808644347 |
package com.example.grader_t
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class Splash_screen : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash_screen)
}
} | Grader_T/app/src/main/java/com/example/grader_t/Splash_screen.kt | 1754931670 |
package dev.jules.toptrumps
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("dev.jules.toptrumps", appContext.packageName)
}
} | Top-Trumps/Android/TopTrumps/app/src/androidTest/java/dev/jules/toptrumps/ExampleInstrumentedTest.kt | 3302696426 |
package dev.jules.toptrumps
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)
}
} | Top-Trumps/Android/TopTrumps/app/src/test/java/dev/jules/toptrumps/ExampleUnitTest.kt | 1444470370 |
package dev.jules.toptrumps.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) | Top-Trumps/Android/TopTrumps/app/src/main/java/dev/jules/toptrumps/ui/theme/Color.kt | 1318664070 |
package dev.jules.toptrumps.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.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 TopTrumpsTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor -> {
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
)
} | Top-Trumps/Android/TopTrumps/app/src/main/java/dev/jules/toptrumps/ui/theme/Theme.kt | 834322393 |
package dev.jules.toptrumps.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
)
*/
) | Top-Trumps/Android/TopTrumps/app/src/main/java/dev/jules/toptrumps/ui/theme/Type.kt | 3906453167 |
package dev.jules.toptrumps
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp
import dev.jules.toptrumps.ui.theme.TopTrumpsTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
TopTrumpsTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Body()
}
}
}
}
}
@Composable
fun Body() {
Scaffold(
topBar = {
Surface(color = Color.Green, modifier = Modifier.fillMaxWidth()) {
Text("Welcome", fontSize = 18.sp)
}
},
floatingActionButton = {
FloatingActionButton(onClick = { /*TODO*/ }) {
Text("Test BTN")
}
}
) { innerPadding ->
Text("Test Content", modifier = Modifier.padding(innerPadding))
LazyColumn {
}
}
}
@Preview(showBackground = true, showSystemUi = true)
@Composable
fun BodyPreview() {
Body()
} | Top-Trumps/Android/TopTrumps/app/src/main/java/dev/jules/toptrumps/MainActivity.kt | 381616722 |
package com.example.week2_wzy
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.week2_wzy", appContext.packageName)
}
} | Week2_wzy/app/src/androidTest/java/com/example/week2_wzy/ExampleInstrumentedTest.kt | 1818019122 |
package com.example.week2_wzy
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)
}
} | Week2_wzy/app/src/test/java/com/example/week2_wzy/ExampleUnitTest.kt | 1260794438 |
package com.example.week2_wzy.home
import androidx.lifecycle.MutableLiveData
import com.example.week2_wzy.base.BaseModel
import com.example.week2_wzy.entity.GoodsEntity
import io.reactivex.internal.operators.maybe.MaybeDoAfterSuccess
class HomeModel :BaseModel(){
val repo=HomeRepo()
val success=MutableLiveData<GoodsEntity>()
val field=MutableLiveData<String>()
fun getGood(category:Int,currentPage:Int,pageSize:Int){
repo.getGoods(category,currentPage,pageSize,success,field)
}
// repo.getGoods(category,currentPage,pageSize,success,field)
} | Week2_wzy/app/src/main/java/com/example/week2_wzy/home/HomeModel.kt | 2779845328 |
package com.example.week2_wzy.home
import androidx.lifecycle.MutableLiveData
import com.example.week2_wzy.base.BaseRepo
import com.example.week2_wzy.entity.GoodsEntity
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
class HomeRepo:BaseRepo() {
fun getGoods(category_id :Int,
currentPage:Int,
pageSize:Int,
success:MutableLiveData<GoodsEntity>,
field:MutableLiveData<String>){
api().getGoods(category_id,currentPage,pageSize)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object :Observer<GoodsEntity>{
override fun onSubscribe(d: Disposable) {
}
override fun onError(e: Throwable) {
// field.value=e.message
}
override fun onComplete() {
}
override fun onNext(t: GoodsEntity) {
success.value=t
}
})
}
} | Week2_wzy/app/src/main/java/com/example/week2_wzy/home/HomeRepo.kt | 1194289271 |
package com.example.week2_wzy
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import com.example.week2_wzy.adapter.GoodsAdapter
import com.example.week2_wzy.base.BaseActivity
import com.example.week2_wzy.databinding.ActivityMainBinding
import com.example.week2_wzy.entity.Data
import com.example.week2_wzy.home.HomeModel
class MainActivity : BaseActivity<ActivityMainBinding>() {
lateinit var hm:HomeModel
lateinit var adapter:GoodsAdapter
val list= mutableListOf<Data>()
override fun initdata() {
hm=ViewModelProvider(this)[HomeModel::class.java]
hm.getGood(0,1,10)
hm.success.observe(this){
list.addAll(it.data)
adapter.notifyDataSetChanged()
}
}
override fun initview() {
db.rv.layoutManager=GridLayoutManager(this,2)
adapter=GoodsAdapter(list)
db.rv.adapter=adapter
//点击事件
adapter.setOnItemClickListener { adapter, view, position ->
intent=Intent(this,XqActivity::class.java)
startActivity(intent)
}
}
override fun bindLayout(): Int=R.layout.activity_main
} | Week2_wzy/app/src/main/java/com/example/week2_wzy/MainActivity.kt | 1702857333 |
package com.example.week2_wzy.entity
data class GoodsEntity(
val code: Int,
val `data`: List<Data>,
val message: String
)
data class Data(
val bannerList: List<String>,
val category_id: Int,
val goods_attribute: String,
val goods_banner: String,
val goods_code: String,
val goods_default_icon: String,
val goods_default_price: Int,
val goods_desc: String,
val goods_detail_one: String,
val goods_detail_two: String,
val goods_sales_count: Int,
val goods_stock_count: Int,
val id: Int
) | Week2_wzy/app/src/main/java/com/example/week2_wzy/entity/GoodsEntity.kt | 2258061851 |
package com.example.week2_wzy
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import com.example.week2_wzy.adapter.GoodsAdapter
import com.example.week2_wzy.base.BaseActivity
import com.example.week2_wzy.databinding.ActivityXqBinding
import com.example.week2_wzy.entity.Data
import com.example.week2_wzy.home.HomeModel
class XqActivity :BaseActivity<ActivityXqBinding>() {
// lateinit var hm: HomeModel
// lateinit var adapter: GoodsAdapter
// val list= mutableListOf<Data>()
// override fun initdata() {
//
//
// override fun initview() {
//
// }
//
// override fun bindLayout(): Int=R.layout.activity_xq
override fun initdata() {
}
override fun initview() {
}
override fun bindLayout(): Int=R.layout.activity_xq
} | Week2_wzy/app/src/main/java/com/example/week2_wzy/XqActivity.kt | 3154300406 |
package com.example.week2_wzy.adapter
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.example.week2_wzy.R
import com.example.week2_wzy.entity.Data
class GoodsAdapter (goodlist:MutableList<Data>):BaseQuickAdapter<Data,BaseViewHolder>(R.layout.item,goodlist){
override fun convert(helper: BaseViewHolder, item: Data) {
Glide.with(context).load(item.goods_default_icon).into(helper.getView(R.id.iv))
helper.setText(R.id.tv,"${item.goods_default_price}元")
}
} | Week2_wzy/app/src/main/java/com/example/week2_wzy/adapter/GoodsAdapter.kt | 1393554826 |
package com.example.week2_wzy.base.net
import com.example.week2_wzy.entity.GoodsEntity
import io.reactivex.Observable
import retrofit2.http.GET
import retrofit2.http.Query
interface Api {
@GET("/goods/info")
fun getGoods(@Query("category_id")category_id :Int,
@Query("currentPage")currentPage :Int,
@Query("pageSize")pageSize :Int,
):Observable<GoodsEntity>
} | Week2_wzy/app/src/main/java/com/example/week2_wzy/base/net/Api.kt | 1319506254 |
package com.example.week2_wzy.base.net
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
class RetrofitManager {
companion object{
fun getRetrofit():Retrofit{
val okHttpClient=OkHttpClient.Builder()
.writeTimeout(30,TimeUnit.SECONDS)
.readTimeout(30,TimeUnit.SECONDS)
.callTimeout(30,TimeUnit.SECONDS)
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
val retrofit=Retrofit.Builder()
.baseUrl("http://10.161.9.80:7012")
.client(okHttpClient.build())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
return retrofit.build()
}
}
} | Week2_wzy/app/src/main/java/com/example/week2_wzy/base/net/RetrofitManager.kt | 3722569287 |
package com.example.week2_wzy.base
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
abstract class BaseActivity <VDB:ViewDataBinding>:AppCompatActivity(){
lateinit var db:VDB
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
db=DataBindingUtil.setContentView(this,bindLayout())
initview()
initdata()
}
abstract fun initdata()
abstract fun initview()
abstract fun bindLayout(): Int
} | Week2_wzy/app/src/main/java/com/example/week2_wzy/base/BaseActivity.kt | 112059805 |
package com.example.week2_wzy.base
import com.example.week2_wzy.base.net.Api
import com.example.week2_wzy.base.net.RetrofitManager
open class BaseRepo {
fun api():Api=RetrofitManager.getRetrofit().create(Api::class.java)
} | Week2_wzy/app/src/main/java/com/example/week2_wzy/base/BaseRepo.kt | 2266796044 |
package com.example.week2_wzy.base
import androidx.lifecycle.ViewModel
open class BaseModel:ViewModel() {
} | Week2_wzy/app/src/main/java/com/example/week2_wzy/base/BaseModel.kt | 2386118509 |
package tanoshi.multiplatform.shared.extension
import tanoshi.multiplatform.common.extension.interfaces.Extension
expect class ExtensionLoader {
val loadedExtensionClasses : HashMap< String , Extension >
fun loadTanoshiExtension( vararg tanoshiExtensionFile : String )
} | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/shared/extension/ExtensionLoader.kt | 2495009216 |
package tanoshi.multiplatform.shared.extension
import java.io.File
import java.io.FileInputStream
expect class ExtensionManager {
val extensionLoader : ExtensionLoader
fun install( extensionId : String , fileInputStream : FileInputStream )
fun install( extensionId: String , file : File )
fun uninstall( extensionId: String )
} | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/shared/extension/ExtensionManager.kt | 1411557959 |
package tanoshi.multiplatform.shared
expect open class ViewModel() | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/shared/ViewModel.kt | 443947927 |
package tanoshi.multiplatform.shared.util
expect open class ApplicationActivity {
fun <applicationActivity:ApplicationActivity> changeActivity(
applicationActivityName : Class<applicationActivity> ,
vararg objects : Any
)
} | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/shared/util/ApplicationActivity.kt | 3126102306 |
package tanoshi.multiplatform.shared
import tanoshi.multiplatform.common.util.logger.Logger
import tanoshi.multiplatform.shared.extension.ExtensionManager
expect class SharedApplicationData {
val appStartUpTime : String
val logFileName : String
val extensionManager : ExtensionManager
val logger : Logger
val portrait : Boolean
} | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/shared/SharedApplicationData.kt | 2438729163 |
package tanoshi.multiplatform.common.extension
import tanoshi.multiplatform.common.extension.interfaces.Extension
import tanoshi.multiplatform.common.util.SelectableMenu
interface ViewableExtension : Extension {
val name : String
val domainsList : SelectableMenu<String>
val language : String
fun search( name : String , index : Int ) : List<ViewableEntry>
fun fetchDetail( entry : ViewableEntry )
fun fetchPlayableContentList( entry : ViewableEntry )
fun fetchPlayableMedia( entry : ViewableContent ) : List<ViewableMedia>
} | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/ViewableExtension.kt | 449393322 |
package tanoshi.multiplatform.common.extension
data class PlayableEntry(
var name : String? = null ,
var language : String? = null ,
var content : List<PlayableContent>? = null ,
var otherData : HashMap<String,String>? = null ,
var coverArt : String? = null ,
var url : String? = null
) | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/PlayableEntry.kt | 2572590830 |
package tanoshi.multiplatform.common.extension
import tanoshi.multiplatform.common.extension.interfaces.Extension
import tanoshi.multiplatform.common.util.SelectableMenu
interface ReadableExtension : Extension {
val name : String
val domainsList : SelectableMenu<String>
val language : String
fun search( name : String , index : Int ) : List<ReadableEntry>
fun fetchDetail( entry : ReadableEntry )
fun fetchPlayableContentList( entry : ReadableEntry )
fun fetchPlayableMedia( entry : ReadableContent ) : List<ReadableMedia>
} | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/ReadableExtension.kt | 4110173184 |
package tanoshi.multiplatform.common.extension
import tanoshi.multiplatform.common.extension.interfaces.Extension
import tanoshi.multiplatform.common.util.SelectableMenu
interface PlayableExtension : Extension {
val name : String
val domainsList : SelectableMenu<String>
val language : String
fun search( name : String , index : Int ) : List<PlayableEntry>
fun fetchDetail( entry : PlayableEntry )
fun fetchPlayableContentList( entry : PlayableEntry )
fun fetchPlayableMedia( entry : PlayableContent ) : List<PlayableMedia>
} | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/PlayableExtension.kt | 2299838097 |
package tanoshi.multiplatform.common.extension
data class ReadableMedia(
var content : String
) | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/ViewableMedia.kt | 3295507763 |
package tanoshi.multiplatform.common.extension.enum
enum class ExtensionCategory {
WATCHABLE ,
VIEWABLE ,
READABLE
} | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/enum/ExtensionCategory.kt | 1748328503 |
package tanoshi.multiplatform.common.extension
data class ViewableMedia(
var url : String
) | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/ReadableMedia.kt | 3958100157 |
package tanoshi.multiplatform.common.extension
data class PlayableContent(
var name : String? = null ,
var url : String? = null ,
val lanuage : String? = null
) | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/PlayableContent.kt | 2207608528 |
package tanoshi.multiplatform.common.extension.annotations
@Target( AnnotationTarget.FIELD )
@Retention( AnnotationRetention.RUNTIME )
// this is annoation is used to look for changing field
// present in an extension class
// acts as customization button for that class
annotation class MUTABLEFILED(
val fieldName : String
) | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/annotations/MUTABLEFILED.kt | 2580233381 |
package tanoshi.multiplatform.common.extension.annotations
@Target( AnnotationTarget.FIELD )
@Retention( AnnotationRetention.RUNTIME )
// filed marked with this annotation are loaded at runtime
// to make changes to them
// so when a function is invoked they can use these modified fields
// these are grouped using groupId
annotation class GROUPMEMBER(
vararg val groupId : String
) | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/annotations/GROUPMEMBER.kt | 3153538579 |
package tanoshi.multiplatform.common.extension.annotations
@Target( AnnotationTarget.FUNCTION )
@Retention( AnnotationRetention.RUNTIME )
// marked funtion will be loaded at runtime
annotation class TAB(
val fieldName : String
) | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/annotations/TAB.kt | 2695948593 |
package tanoshi.multiplatform.common.extension.annotations
@Target( AnnotationTarget.FUNCTION )
@Retention( AnnotationRetention.RUNTIME )
// This annotation is used to filter out various filed that are not relevant to function
// so those which are relevent can be changed at runtime before function is invoked
// these are grouped using groupId
annotation class GROUPHOLDER(
vararg val groupId : String
) | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/annotations/GROUPHOLDER.kt | 380862241 |
package tanoshi.multiplatform.common.extension
data class PlayableMedia(
var mediaUrl : String? = null ,
var mediaLang : String? = null ,
var subtitleUrl : String? = null ,
var subtitleLang : String? = null ,
var quality : String? = null ,
) | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/PlayableMedia.kt | 2695366321 |
package tanoshi.multiplatform.common.extension.helper
import com.squareup.okhttp.Request
import com.squareup.okhttp.Request.Builder
val String.request : Request
get() = Request.Builder()
.url( this )
.build()
infix fun String.request( builderScope : Builder.() -> Unit ): Request = Request.Builder()
.url( this )
.apply(builderScope)
.build()
val defaultArg : Builder.() -> Unit = {
addHeader( "User-Agent" , "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" )
} | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/helper/okhttp.kt | 2496568525 |
package tanoshi.multiplatform.common.extension
data class ReadableContent(
var name : String? = null ,
var url : String? = null ,
val lanuage : String? = null
) | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/ReadableContent.kt | 1770159981 |
package tanoshi.multiplatform.common.extension
import tanoshi.multiplatform.common.util.logger.Logger
open class ApplicationAccess {
var logger : Logger? = null
} | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/ApplicationAccess.kt | 1462113469 |
package tanoshi.multiplatform.common.extension
data class ReadableEntry(
var name : String? = null ,
var language : String? = null ,
var content : List<ReadableContent>? = null ,
var otherData : HashMap<String,String>? = null ,
var url : String? = null
) | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/ReadableEntry.kt | 2944792977 |
package tanoshi.multiplatform.common.extension
data class ViewableContent(
var name : String? = null ,
var url : String? = null ,
val lanuage : String? = null
) | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/ViewableContent.kt | 909748087 |
package tanoshi.multiplatform.common.extension.interfaces
interface Extension | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/interfaces/Extension.kt | 2690332857 |
package tanoshi.multiplatform.common.extension
data class ViewableEntry(
var name : String? = null ,
var language : String? = null ,
var content : List<ViewableContent>? = null ,
var otherData : HashMap<String,String>? = null ,
var url : String? = null
) | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/ViewableEntry.kt | 3460544523 |
package tanoshi.multiplatform.common.util.logger
import tanoshi.multiplatform.common.exception.logger.AnotherTagIsAlreadyInUseException
class LogScope {
private var tag : Tag = Tag.NOTSPECIFIED
val WARN : Unit
get() {
if ( tag != Tag.NOTSPECIFIED ) throw AnotherTagIsAlreadyInUseException( tag.toString() )
tag = Tag.WARN
}
val ERROR : Unit
get() {
if ( tag != Tag.NOTSPECIFIED ) throw AnotherTagIsAlreadyInUseException( tag.toString() )
tag = Tag.ERROR
}
val DEBUG : Unit
get() {
if ( tag != Tag.NOTSPECIFIED ) throw AnotherTagIsAlreadyInUseException( tag.toString() )
tag = Tag.DEBUG
}
override fun toString(): String = tag.toString()
enum class Tag( name : String ) {
WARN( "WARNING" ) ,
ERROR( "ERROR" ) ,
DEBUG( "DEBUG" ) ,
NOTSPECIFIED( "NOTSPECIFIED" ) ;
override fun toString(): String = name
}
} | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/util/logger/LogScope.kt | 4211375810 |
package tanoshi.multiplatform.common.util.logger
import tanoshi.multiplatform.common.exception.logger.LogFileAlreadyExist
import java.io.File
import java.lang.Exception
class Logger {
private val log : ArrayList<Pair<String,String>> = ArrayList()
fun saveLog( file : File , overwrite : Boolean = false ) {
if ( log.isEmpty() ) return
try {
if ( file.isFile && !overwrite ) throw LogFileAlreadyExist( file.name )
file.outputStream().bufferedWriter().use { logFile ->
logFile.write( toString() )
}
} catch ( _ : Exception ) {}
}
val read : String
get() = toString()
val list : List<Pair<String,String>>
get() = log
infix fun log(logScope : LogScope.() -> String ) = LogScope().run {
val message = logScope()
val tag = toString()
log.add(
Pair( tag , message )
)
}
override fun toString(): String {
val buffer = StringBuilder()
for ( ( tag , message ) in log ) buffer.append( "$tag : $message" )
return buffer.toString()
}
} | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/util/logger/Logger.kt | 2515396478 |
package tanoshi.multiplatform.common.util
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import tanoshi.multiplatform.common.exception.SelectableMenuIsImmutableException
import tanoshi.multiplatform.common.exception.SelectableMenuEntryNotFoundException
class SelectableMenu < T > (
initialEntry : T , vararg entries : T
) {
private val selectedElement : MutableState<T> = mutableStateOf( initialEntry )
val activeElement : MutableState<T>
get() = selectedElement
val activeElementValue : T
get() = selectedElement.value
private var list : ArrayList<T> = ArrayList()
private var isImmutable : Boolean = false
init {
add( initialEntry )
entries.forEach { entry ->
add( entry )
}
}
val changeMutability : Boolean
get() {
isImmutable = !isImmutable
return isImmutable
}
fun entries() : List<T> = list
fun add( entry : T ) {
if ( isImmutable ) throw SelectableMenuIsImmutableException( this )
if ( ! list.contains( entry ) )list.add( entry )
}
fun remove( entry : T ) {
if ( isImmutable ) throw SelectableMenuIsImmutableException( this )
if ( list.contains( entry ) ) list.remove( entry )
}
fun select( entry : T ) {
if ( ! list.contains( entry ) ) throw SelectableMenuEntryNotFoundException( entry.toString() )
selectedElement.value = entry
}
override fun toString(): String {
return """
|object hash : ${this.hashCode()}
|active value : ${selectedElement.value}
|list : ${list.toString().let {
it.substring( 1 , it.length-1 )
}}
""".trimMargin( "|" )
}
} | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/util/SelectableMenu.kt | 1938386783 |
package tanoshi.multiplatform.common.util
import tanoshi.multiplatform.common.util.logger.Logger
import java.io.File
import java.text.SimpleDateFormat
import java.util.Calendar
val currentDateTime : String
get() = Calendar.getInstance().time.let { date ->
SimpleDateFormat( "yyyy-MM-dd-HH-mm-ss" ).let { formatter ->
formatter.format( date )
}
}
val String.toFile : File
get() = File( this )
fun logger() : Logger = Logger()
fun <T> selectableMenu(
initialValue : T , vararg entries : T
) : SelectableMenu<T> = SelectableMenu<T>(
initialValue , *entries
) | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/util/functions.kt | 74205228 |
package tanoshi.multiplatform.common.util
import java.io.File
val restrictedClasses : HashSet<String> = hashSetOf(
File::class.java.name
) | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/util/RestrictedClasses.kt | 1160311545 |
package tanoshi.multiplatform.common.navigation
import androidx.compose.runtime.*
// keep the current screen information and backstack
class NavigationController(
private val startScreen : String ,
stack : MutableSet<String> = mutableSetOf()
) {
var currentScreen by mutableStateOf( startScreen )
private var screenBackstack = stack
infix fun navigateTo( nextScreen : String ) {
if ( currentScreen == nextScreen ) return
if ( screenBackstack.contains( currentScreen ) ) screenBackstack.remove( currentScreen )
if ( nextScreen == startScreen ) screenBackstack = mutableSetOf()
else screenBackstack.add( currentScreen )
currentScreen = nextScreen
}
// back lambda stack it contains all that task that need to be done before invoking
// screen back function
val backLambdaStackObject = BackLambdaStack.backLambdaStack()
// back function
fun back() {
backLambdaStackObject.peek()?.run {
if ( invoke(backLambdaStackObject) != backLambdaStackObject.keepAfterInvocation ) backLambdaStackObject.pop()
return@back
}
if ( screenBackstack.isEmpty() ) return
currentScreen = screenBackstack.last()
screenBackstack.remove( currentScreen )
}
} | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/navigation/NavigationController.kt | 3074669592 |
package tanoshi.multiplatform.common.navigation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import kotlin.reflect.KProperty
// This Component file is made so
// That all the function that are needed to make navigation stack
// can be imported by one import statement
// i.e import tanoshi.multiplatform.shared.naviagtion.*
// All the Nav Controller Component
fun navController(
startScreen: String ,
stack : MutableSet<String> = mutableSetOf()
) : NavigationController = NavigationController( startScreen , stack )
@Composable
fun NavController (
startScreen : String ,
stack : MutableSet<String> = mutableSetOf()
) : MutableState<NavigationController> = rememberSaveable {
mutableStateOf( NavigationController( startScreen, stack ) )
}
operator fun NavigationController.getValue( thisObj : Any? , kProperty: KProperty<*>) : NavigationController = this
infix fun NavigationController.backStackLambdaPush( lambda : BackLambdaStack.() -> Any ) = backLambdaStackObject.push(lambda)
fun NavigationController.backStackLambdPeek() = backLambdaStackObject.peek()
fun NavigationController.backStackLambdaPop() = backLambdaStackObject.pop()
val NavigationController.back : Unit
get() {
back()
}
// All The Navigation Host Component
@Composable
fun CreateScreenCatalog(
navigationController: NavigationController ,
screen : @Composable NavigationHost.NavigationGraphBuilder.() -> Unit
) = NavigationHost( navigationController , screen ).also { it.renderView() }
@Composable
fun NavigationHost.NavigationGraphBuilder.Screen(
route: String,
content: @Composable () -> Unit
) {
if (navigationController.currentScreen == route) content()
} | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/navigation/Components.kt | 3557703331 |
package tanoshi.multiplatform.common.navigation
// why create this class because we are gonna perform stack operation
// and linked constant time for retrieval and addition
// lambda was extension of this class instead of simple lambda so it
// user can return status without any issue
class BackLambdaStack {
val keepAfterInvocation : WorkStatus = WorkStatus.KeepAfterInvocation
val removeAfterInvocation : WorkStatus = WorkStatus.RemoveAfterInvocation
enum class WorkStatus {
KeepAfterInvocation ,
RemoveAfterInvocation
}
private data class LambdaFunctionNode (
val lamda : BackLambdaStack.() -> Any ,
var prev : LambdaFunctionNode? = null
)
private var tail : LambdaFunctionNode? = null
fun push( backLambda : BackLambdaStack.() -> Any ) = backLambda.let { lockedValue ->
tail = LambdaFunctionNode( lockedValue , tail )
}
fun pop() = tail?.let {
tail = it.prev
}
fun peek() = tail?.let {
it.lamda
}
companion object {
fun backLambdaStack() : BackLambdaStack = BackLambdaStack()
}
} | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/navigation/BackLambdaStack.kt | 2566634375 |
package tanoshi.multiplatform.common.navigation
import androidx.compose.runtime.Composable
class NavigationHost(
val navigationController: NavigationController ,
val content : @Composable NavigationGraphBuilder.() -> Unit
) {
@Composable
fun renderView() {
NavigationGraphBuilder().renderScreen()
}
inner class NavigationGraphBuilder(
val navigationController: NavigationController = [email protected]
) {
@Composable
fun renderScreen() {
[email protected](this)
}
}
} | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/navigation/NavigationHost.kt | 1775324647 |
package tanoshi.multiplatform.common.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.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.unit.dp
import tanoshi.multiplatform.common.util.logger.Logger
@Composable
fun LogScreen(
logger : Logger
) {
// val scrollState = rememberLazyListState()
// val coroutineScope = rememberCoroutineScope()
LazyColumn (
modifier = Modifier
// .draggable(
// orientation = Orientation.Horizontal,
// state = rememberDraggableState { delta ->
// coroutineScope.launch {
// scrollState.scrollBy(-delta)
// }},
// )
.fillMaxSize()
.background( Color.White )
.padding( 10.dp )
.clip( RoundedCornerShape( 10.dp ) )
.background( Color.LightGray )
.padding( 10.dp )
){
for ( ( tag , message ) in logger.list ) {
item {
Column {
Text(
text = tag ,
modifier = Modifier
.fillMaxWidth()
.clip( RoundedCornerShape( 5.dp ) )
.background( tag.color )
.padding( horizontal = 10.dp ) ,
color = Color.Black ,
)
Text(
text = message ,
color = Color.Black
)
Spacer( Modifier.height( 10.dp ) )
}
}
}
// item {
// Text(
// text = log ,
// modifier = Modifier
// .fillMaxSize() ,
// color = Color.Black
// )
// }
}
}
private val String.color : Color
get() = when ( this ) {
"ERROR" -> Color.Red
"WARNING" -> Color.Yellow
"DEBUG" -> Color.Green
else -> Color.Black
} | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/screens/LogScreen.kt | 2162481347 |
package tanoshi.multiplatform.common.screens
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import tanoshi.multiplatform.shared.SharedApplicationData
@Composable
fun BrowseScreen(
sharedData : SharedApplicationData
) {
Box( Modifier.fillMaxSize() , contentAlignment = Alignment.Center ) {
Text( "Browse Screen" )
}
} | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/screens/BrowseScreen.kt | 4206210974 |
package tanoshi.multiplatform.common.screens
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.onClick
import androidx.compose.material.Icon
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.List
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
import tanoshi.multiplatform.common.model.MainScreenViewModel
import tanoshi.multiplatform.common.navigation.CreateScreenCatalog
import tanoshi.multiplatform.common.navigation.Screen
import tanoshi.multiplatform.shared.SharedApplicationData
@Composable
fun MainScreen(
sharedAppData : SharedApplicationData ,
viewModel : MainScreenViewModel
) = sharedAppData.run {
if ( portrait ) PortraitMainScreen( viewModel )
else LandscapeMainScreen( viewModel )
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun SharedApplicationData.PortraitMainScreen(
viewModel : MainScreenViewModel
) {
Scaffold(
bottomBar = {
Row(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
.padding( 5.dp ) ,
horizontalArrangement = Arrangement.SpaceEvenly ,
verticalAlignment = Alignment.CenterVertically
) {
MainScreen.entries.forEach { screen ->
Row(
Modifier.onClick {
viewModel.navController navigateTo screen.name
} ,
verticalAlignment = Alignment.CenterVertically
) {
Icon(
screen.icon ,
screen.label
)
AnimatedVisibility(
viewModel.navController.currentScreen == screen.name
) {
Text(
" ${screen.label}" ,
modifier = Modifier
.align(Alignment.CenterVertically)
)
}
}
}
}
}
) {
Box( Modifier.fillMaxSize().padding( it ) , contentAlignment = Alignment.Center ) {
MainScreenCatalog( viewModel = viewModel )
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun SharedApplicationData.LandscapeMainScreen( viewModel: MainScreenViewModel ) {
Row (
modifier = Modifier
.fillMaxSize()
) {
Column(
modifier = Modifier
.fillMaxHeight()
.wrapContentWidth()
.padding( 5.dp ) ,
horizontalAlignment = Alignment.CenterHorizontally ,
verticalArrangement = Arrangement.SpaceEvenly
) {
MainScreen.entries.forEach { screen ->
Column(
modifier = Modifier
.onClick {
viewModel.navController navigateTo screen.name
}
) {
Icon(
screen.icon ,
screen.label
)
// AnimatedVisibility(
// viewModel.navController.currentScreen == screen.label
// ) {
// Text( screen.label ,
// modifier = Modifier
// .align(Alignment.CenterHorizontally)
// )
// }
}
}
}
MainScreenCatalog( viewModel )
}
}
enum class MainScreen(
val label : String ,
val icon : ImageVector
) {
BrowseScreen(
"Browse Screen" ,
Icons.Filled.Home
) ,
LogScreen(
"Log Screen" ,
Icons.Filled.List
)
}
@Composable
private fun SharedApplicationData.MainScreenCatalog(
viewModel : MainScreenViewModel
) {
CreateScreenCatalog( viewModel.navController ) {
Screen( MainScreen.BrowseScreen.name ) {
BrowseScreen( this@MainScreenCatalog )
}
Screen( MainScreen.LogScreen.name ) {
LogScreen( logger )
}
}
} | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/screens/MainScreen.kt | 3572582064 |
package tanoshi.multiplatform.common.model
import tanoshi.multiplatform.common.navigation.NavigationController
import tanoshi.multiplatform.common.navigation.navController
import tanoshi.multiplatform.common.screens.MainScreen
import tanoshi.multiplatform.shared.ViewModel
class MainScreenViewModel : ViewModel() {
val navController : NavigationController = navController( startScreen = MainScreen.BrowseScreen.name )
} | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/model/MainScreenViewModel.kt | 3363067731 |
package tanoshi.multiplatform.common.exception.logger
class LogFileAlreadyExist( filePath : String ) : Exception( "File : $filePath" ) | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/exception/logger/LogFileAlreadyExist.kt | 3242429320 |
package tanoshi.multiplatform.common.exception.logger
class AnotherTagIsAlreadyInUseException( tag : String) : Exception(
"\nOnly one tag can be specified for a log scope block\nFirst One is Considered\nCurrently \"$tag\" is in active"
) | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/exception/logger/AnotherTagIsAlreadyInUseException.kt | 1509776942 |
package tanoshi.multiplatform.common.exception
class SelectableMenuEntryNotFoundException( entry : String ) : Exception(
"Entry \"$entry\" Not Found In List"
) | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/exception/SelectableMenuEntryNotFoundException.kt | 3407618291 |
package tanoshi.multiplatform.common.exception
import tanoshi.multiplatform.common.util.SelectableMenu
class SelectableMenuIsImmutableException( selectableMenuObj : SelectableMenu<*> ) : Exception(
"SelectableMenu object ${selectableMenuObj.hashCode()} is immutable"
) | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/exception/SelectableMenuIsImmutableException.kt | 2008946636 |
package tanoshi.multiplatform.common.exception.extensionManager
import java.lang.Exception
class IllegalDependenciesFoundException( msg : String ) : Exception( msg ) | Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/exception/extensionManager/IllegalDependenciesFoundException.kt | 3307275293 |
package tanoshi.multiplatform.desktop
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import tanoshi.multiplatform.common.model.MainScreenViewModel
import tanoshi.multiplatform.common.screens.MainScreen
import tanoshi.multiplatform.shared.util.ApplicationActivity
class App : ApplicationActivity() {
@Composable
override fun onCreate() {
val mainScreenViewModel by remember { mutableStateOf( MainScreenViewModel() ) }
MainScreen(
applicationData ,
mainScreenViewModel
)
}
} | Tanoshi-Multiplatform/composeApp/src/desktopMain/kotlin/tanoshi/multiplatform/desktop/App.kt | 3312205442 |
@file: JvmName( "MyApplication" )
package tanoshi.multiplatform.desktop
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import tanoshi.multiplatform.common.screens.LogScreen
import tanoshi.multiplatform.desktop.util.WindowStack
import tanoshi.multiplatform.desktop.util.customApplication
import tanoshi.multiplatform.shared.SharedApplicationData
fun main() : Unit = SharedApplicationData().run {
logger log {
"App Started At $appStartUpTime"
}
val windowStack = WindowStack( App() , this )
customApplication( this ) {
Window( onCloseRequest = ::exitApplication ) {
windowStack.render()
}
}
error?.let {
application( false ) {
Window( onCloseRequest = ::exitApplication , title = "App Log" ,
icon = rememberVectorPainter(
Icons.Filled.Settings
)
) {
LogScreen( logger )
}
}
}
}
| Tanoshi-Multiplatform/composeApp/src/desktopMain/kotlin/tanoshi/multiplatform/desktop/MyApplication.kt | 2215549171 |
package tanoshi.multiplatform.desktop.util
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import tanoshi.multiplatform.shared.SharedApplicationData
import tanoshi.multiplatform.shared.util.ApplicationActivity
class WindowStack(
startActivity : ApplicationActivity ,
private val sharedApplicationData : SharedApplicationData
) {
private var _activeWindow : MutableState<ApplicationActivity> = mutableStateOf( startActivity )
val activeWindow : ApplicationActivity
get() = _activeWindow.value
init {
startActivity.windowStack = this
startActivity.applicationData = sharedApplicationData
}
private var stack : ArrayList<ApplicationActivity> = arrayListOf(
startActivity
)
fun add( activity : ApplicationActivity ) {
activity.windowStack = this
activity.applicationData = sharedApplicationData
stack.add( activity )
_activeWindow.value = activity
}
fun addAll( vararg activities : ApplicationActivity ) {
activities.forEach { activity ->
add( activity )
}
_activeWindow.value = stack.last()
}
fun remove( activity: ApplicationActivity ) {
stack.remove( activity )
_activeWindow.value = stack.last()
}
fun removeAll( vararg activities : ApplicationActivity ) {
stack.removeAll(activities.toSet())
_activeWindow.value = stack.last()
}
@Composable
fun render() {
_activeWindow.value.onCreate()
}
} | Tanoshi-Multiplatform/composeApp/src/desktopMain/kotlin/tanoshi/multiplatform/desktop/util/WindowStack.kt | 1759843490 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.