1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

AndroidStudioチートシート

Last updated at Posted at 2023-12-07

AndroidStudioチートシート

個人的な備忘録です.内容の薄さに関しては悪しからず.
変数として渡す際に面倒なので作りました.よく使うものを追加していきます.
Javaは長いためKotlinで記述しています

引数として渡す記述

Adapterはかなり無理やりです
UI関連は出来ればActivityとFragmentですることが望ましいです

Activity Fragment Adapter
view inflater.inflate itemView
ViewHolder(itemView: View)
findViewById findViewById view.findViewById itemView.findViewById
ViewHolder(itemView: View)
context this requireContext() holder.itemView.getContext()
onBindViewHolder(holder: ViewHolder,
application application requireActivity().appication

ViewModelへのアクセス

Roomを使用した場合

UserViewModel.kt
class UserViewModel(private val repository: UserRepository) : ViewModel(){
    val allUsers: LiveData<List<User>> = repository.allUsers.asLiveData()
    
    private val _newId = MutableLiveData<List<Long>>()
    val insertAll(users: User) = viewModelScope.launch(Dispatchers.IO){
        val newDatas = repository.insertAll(users)
        // 格納したデータのidを戻り値に指定した場合は以下を記述
        withContext(Dispatchers.Main){
            _newId.value = newDatas
        }
    }
}
MainActivity.kt
class MainActivity : AppCompatActivity() {
    private val mUserViewModel: UserViewModel by viewModels {
        UserViewModelFactory((application as UsersApplication).repository)
    }
    // 中略
    fun hogehoge(dataSet: User){
        mUserViewModel.insertAll(User(
            id = null,    // id=0またはnullにするとautoGenerateされる
            name = dataSet.name
            address = dataSet.address,
            // 以下略
        ))

        var requestId: Int = 0
        mUserViewModel.newId.observe(this){newIds ->
            for(id in newIds){
                requestId = id.toInt()
            }
        }
    }
}
UserFragment.kt
class UserFragment : Fragment() {
    private val mUserViewModel: UserViewModel by viewModels {
        UserViewModelFactory((requireActivity().application as UsersApplication).repository)
    }
    override fun onCreateView(inflater: LayoutInflater,
                        container: ViewGroup?, savedInstanceState: Bundle?): View {
        // 中略
        mUserViewModel.allUsers.observe(viewLifecycleOwner){ users ->
            users.let{ adapter.submitList(it) }
        }
        return view
    }
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?