New to coding; Can't get button to link to new activity in Kotlin - kotlin

It opens the first activity on the emulator, but fails on button click. I created the second activity (AddProductActivity), so maybe I did something wrong there. I've tried all the variables I could find online to change how the button operates.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.content_main)
val button = findViewById<Button>(R.id.goToAddProduct)
button.setOnClickListener {
val intent = Intent(this, AddProductActivity::class.java)
startActivity(intent)
}
}
}
class AddProductActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.add_product)
}
}
on content_main.xml:
<Button
android:id="#+id/goToAddProduct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/add_to_inventory"/>

Make sure you have registered your new activity in the manifest. This is a common mistake by newcomers.
If that is not the case before you click on the button open your logcat view in android studio. Once you click on the button please investigate the crash issue from here.

Related

how to navigate to fragment inside recycler view?

I have an activity that is controlled with a navigation component, it has few fragments, inside one of these fragments there is a recyclerView that has some items, when I click on an Item I want it to navigate me to another fragment that has additional information about the item, I don't know how to use navigation component inside a recycelerView, when I type findNavController it has some parameters that am not sure what to put in or if its even the right function, I also tried to do it by code like this:
val fm = (context as AppCompatActivity).supportFragmentManager
fm.beginTransaction()
.replace(R.id.fragmentContainer, fragment)
.addToBackStack(null)
.commit()
by the way this is the code that asks for other parameters:
// it asks for a (fragment) or (activity, Int)
findNavController().navigate(R.id.action_settingsFragment_to_groupUnits)
the problem is when I navigate out of this fragment or use the drawer navigation (nav component for the other fragments), this fragment that I navigated to stays displayed in the screen, I see both fragments at the same time, I assume its a fragment backStack issue but I don't know how to solve it, thanks for the help and your time in advance
You do not need to navigate from RecyclerView item click to AdditionalDetails fragment directly.
You can do this same thing by help of interface.
Steps:
Create an interface with a method declaration.
Extend Interface from the fragment where you are using your RecyclerView and Implement interface method.
Pass this interface with the adapter.
Using the interface from adapter you just pass object when click on item.
Finally from your fragment you just navigate to AdditionalDetails fragment with argument.
Lets see sample code from my current project:
Interface
interface ChatListClickListener {
fun onChatListItemClick(view:View, user: User)
}
Adapter Class
class UserAdapter(val Users: List<User>, val chatListClickListener: ChatListClickListener) : RecyclerView.Adapter<UserAdapter.UserViewHolder>() {
inner class UserViewHolder(
val recyclerviewUsersBinding: RecyclerviewChatlistBinding
) : RecyclerView.ViewHolder(recyclerviewUsersBinding.root)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
val vh = UserViewHolder(
DataBindingUtil.inflate(
LayoutInflater.from(parent.context),
R.layout.recyclerview_chatlist,
parent,
false
)
)
return vh
}
override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
holder.recyclerviewUsersBinding.user = Users[position]
holder.recyclerviewUsersBinding.root.setOnClickListener{
chatListClickListener.onChatListItemClick(it,Users[position])
}
}
override fun getItemCount(): Int {
return Users.size
}
}
My fragment
class FragmentChatList : Fragment(), ChatListClickListener {
lateinit var binding: FragmentChatListBinding
lateinit var viewModel: ChatListViewModel
lateinit var listener: ChatListClickListener
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val args: FragmentChatListArgs by navArgs()
binding = FragmentChatListBinding.inflate(layoutInflater, container, false)
val factory = ChatListFactory(args.user)
viewModel = ViewModelProvider(this, factory).get(ChatListViewModel::class.java)
binding.viewModel = viewModel
listener = this
lifecycleScope.launch {
viewModel.addUserWhenUserConnect()
}
viewModel.userList.observe(viewLifecycleOwner, Observer { data ->
binding.rvChatList.apply {
layoutManager = LinearLayoutManager(requireContext())
setHasFixedSize(true)
adapter = UserAdapter(data, listener)
}
})
return binding.root
}
override fun onChatListItemClick(view: View, user: User) {
Toast.makeText(requireContext(), user.name + "", Toast.LENGTH_SHORT).show()
// here you navigate to your fragment....
}
}
I guess this will be helpful.

why onClickListener does not work in my fragment activity?

Im new in programming, and i got stuck with adding onClickListener in my FragmentHome.kt
i added this code to my existing activity:
val exc = this.findViewById<Button>(R.id.execute)
exc.setOnClickListener {
Toast.makeText(this, "You clicked me.", Toast.LENGTH_SHORT).show()
}
I tried set onClicklistener on a blank activity and it worked, but when i added it to an existing
Fragment activity it does nothing (it should display a toast with some text)
I see no error messages so i don't know where the problem could be.
Thank you for your responses.
enter code here
public class FragmentHome : Fragment() {
public class HomeFragmentElements : AppCompatActivity() {
private lateinit var spinView: Spinner
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.fragment_home)
val exc = this.findViewById<Button>(R.id.execute)
exc.setOnClickListener {
Toast.makeText(this, "You clicked me.", Toast.LENGTH_SHORT).show()
}
spinView = findViewById(R.id.spinner)
spinView.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
TODO("Not yet implemented")
}
override fun onNothingSelected(parent: AdapterView<*>?) {
TODO("Not yet implemented")
}
}
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false)
}
}
enter code here
Try to put your code into "onViewCreated":
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val exc = this.findViewById<Button>(R.id.execute)
exc.setOnClickListener {
Toast.makeText(this, "You clicked me.", Toast.LENGTH_SHORT).show()
}
}
onViewCreated is executed after "onCreateView". View bindings and initializations should be into onViewCreated
change the following in your onCreateView
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view: View = inflater.inflate(R.layout.fragment_home, container, false)
collectId(view)
return view
}
fun collectId(view: view){
val exc = view.findViewById<Button>(R.id.execute)
exc.setOnClickListener {
Toast.makeText(this, "You clicked me.", Toast.LENGTH_SHORT).show()
}
}
You can consider viewBinding instead of findViewById
It looks like you have defined an AppCompatActivity subclass inside your Fragment class's definition, kind of like this:
class MyFragment: Fragment {
class MyActivity: AppCompatActivity() {
//...
}
}
The ability to define a non-inner class in a nested way is purely a code organization tool. There is absolutely no connection between your Fragment and Activity classes here. The code above is no different than if you did this, with each class in a completely different file:
class MyFragment: Fragment {
}
class MyActivity: AppCompatActivity() {
}
It also doesn't make sense to think of an Activity as a child of a Fragment. A Fragment is a piece of an Activity, so it's the other way around.
All the code that you have in this Activity's onCreate should be put in the Fragment's onViewCreated() function, except for the call to setContentView(), because that's what your overriding of onCreateView() does. And remove the unused nested Activity class.
Also, you don't need to override onCreateView if you're simply inflating a layout and returning it. You can put the layout directly in the super-constructor call like this:
public class FragmentHome : Fragment(R.layout.fragment_home) {
private lateinit var spinView: Spinner
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// your view setup code
}
}

Kotlin: How do I add an actionbar menu on a tabbed activity?

I have a tabbed activity with fragments. Now I just need to add an actionbar menu. I am guessing I add the action bar in the mainactivity. How can I do this?
I have tried adding an action bar for each fragment but looks like that cannot be done in kotlin. I am new to android development but I was able to perform this task with java. I am converting my small projects to Kotlin which is supposed to be easier than java.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val sectionsPagerAdapter = SectionsPagerAdapter(this, supportFragmentManager)
val viewPager: ViewPager = findViewById(R.id.view_pager)
viewPager.adapter = sectionsPagerAdapter
val tabs: TabLayout = findViewById(R.id.tabs)
tabs.setupWithViewPager(viewPager)
val fab: FloatingActionButton = findViewById(R.id.fab)
fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.mainmenu, menu)
return true
}
}
}
Actually figured it out. My question was basically senseless. It should have been how to add a menu in an AppBarLayout. My app is using a tabbed activity.
All I had to do was under my main activity layout, I needed to add a toolbar under the Appbarlayout.
then under the Main activity Oncreate, I added
setSupportActionBar(toolbar)
val actionBar = supportActionBar
Then call the oncreateoptionsmenu
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu to use in the action bar
val inflater = menuInflater
inflater.inflate(R.menu.mainmenu, menu)
return super.onCreateOptionsMenu(menu)
}

Issue overriding onDrawerOpened() - Kotlin

I'm working on a Kotlin coded app using the Navigation Drawer Layout with a list of items. When I open the drawer using the icon at the top left I want it to notifyDataSetChanged so that the list is updated from outside the MainActivity. This includes pressing the back button, swiping open the drawer, or clicking the stacked lines icon at the top left
Here's a simplified version of my code, but it's essentially a Navagation Drawer Activity with a recyclerView for the context of my question:
class MainActivity : AppCompatActivity() {
lateinit var drawerLayout: DrawerLayout
lateinit var navView: NavigationView
lateinit var toolbar: Toolbar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
toolbar = findViewById(R.id.app_bar_toolbar)
setSupportActionBar(toolbar)
drawerLayout = findViewById(R.id.drawer_layout)
navView = nav_view
val toggle = ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
}
I've spent several hours trying anything I can, but primarily I can't get this to work:
override fun onDrawerOpen(view:View){
... myAdapter.notifyDataSetChanged()
super.onDrawerOpen(view)
}
it gives me the hint "overrides nothing" or "unused", and if I try to add it to any of my code in onCreate it states "Modifier 'override' not applicable to local function.
What am I doing wrong? Is there a better way to notify a data change when the drawer is opened?
The Question is old, but to whom has the same problem:
Just Create new class that implements DrawerListener and write your logic inside appropriate method:
private inner class MyDrawerListener(): DrawerListener {
override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
}
override fun onDrawerOpened(drawerView: View) {
}
override fun onDrawerClosed(drawerView: View) {
}
override fun onDrawerStateChanged(newState: Int) {
}
}
Now add listener as:
drawerLayout.addDrawerListener(MyDrawerListener())

Button onClick attribute is none if activity written in Kotlin

Follow this tutorial: Android - Start Another Activity if I made MainActivity.java button OnClick attribute has the sendMessage() method.
But if I made MainActivity.kt button OnClick attribute has nothing to show, just a none.
Is this an Android Studio 3 bug or I missed something for Kotlin?
Java mainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** Called when the user taps the Send button */
public void sendMessage(View view) {
// Do something in response to button
}
}
Kotlin mainActivity:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
/** Called when the user taps the Send button */
fun sendMessage(view: View) {
// Do something in response to button
}
}
XML layout (Java and Kotlin project are the same)
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ir.bigbang.vahid.myapplication.MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
tools:layout_editor_absoluteX="148dp"
tools:layout_editor_absoluteY="81dp" />
</android.support.constraint.ConstraintLayout>
It seems like the designer does not support Kotlin yet. Here are some solution:
XML (Not Recommended)
Add the following line to your Button tag. This is exactly what the designer will do.
android:onClick="sendMessage"
Old Fashion
No need to add anything.
val button = findViewById<Button>(R.id.Button)
button.setOnClickListener {
}
kotlin-android-extensions (Recommended)
Add apply plugin: "kotlin-android-extensions" to your build.gradle
// button is the Button id
button.setOnClickListener {
}
Your code will like this:
button.setOnClickListener(){
Toast.makeText(this#MainActivity, "Its toast!", Toast.LENGTH_SHORT).show();
}
Here import will:
import kotlinx.android.synthetic.main. activity_main.*
Here "button" is the id of that Button in .xml file. Here the advantage is no need to create Button object in your java class.
Once defined the sendMessage class as :
/** Called when the user taps the Send button */
fun sendMessage(view: View) {
setContentView(R.layout.activity_second)
// Do something in response to button
}
And also defined a second activity as:
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
}
}
I added the SendMessage to the OnClick function:
And then it worked.
You can easily define this inside the XML itself. But using the android:onClick attribute is still a little expensive.
Instead you could consider using the Kotlin Android Extensions and synthetic properties:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener {
// Do something in response to button
}
}
Button OnClick implementation it's can be done by some ways in Android
some of the possible ways are below in sample:
1>Using OnClickListener as a interface
Here we implement our main activity with OnClicklistener
and override the function onClick
override fun onClick(v: View?) {
when (v?.id){
(R.id.btn1) -> {
toastmsg("Button1");
}
R.id.btn2 -> {
toastmsg("Button2");
}
}
}
2>And create a function and pass the OnClickListener with
variable sample:
findViewById<Button>(R.id.btn3).setOnClickListener(btnClick);
var btnClick =
OnClickListener {
Toast.makeText(this, "BtnClick", Toast.LENGTH_SHORT).show() ;
}
3>Create OnClickListener in Oncreate()
btn1=findViewById(R.id.btn1);
btn1?.setOnClickListener {
toastmsg("test button1");
}
full sample Code of the example it contains all the possible implementation of the Button OnClickListener :
class MainActivity : AppCompatActivity() , OnClickListener{
lateinit var tv1:TextView;
lateinit var tv2:TextView;
lateinit var tv3:TextView;
var btn1: Button? =null;
var btn2: Button? =null;
var btn3: Button? =null;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btn1=findViewById(R.id.btn1);
btn1?.setOnClickListener {
toastmsg("test button1");
}
findViewById<Button>(R.id.btn2).setOnClickListener(this);
findViewById<Button>(R.id.btn3).setOnClickListener(btnClick);
}
var btnClick =
OnClickListener {
Toast.makeText(this, "BtnClick", Toast.LENGTH_SHORT).show() ;
}
override fun onClick(v: View?) {
when (v?.id){
(R.id.btn1) -> {
toastmsg("Button1");
}
R.id.btn2 -> {
toastmsg("Button2");
}
}
}
private fun toastmsg(msg: String){
Toast.makeText(this, "DaggerTest" + msg, Toast.LENGTH_SHORT).show();
}
}
Here's the solution I came up with in the MainActivity.kt file.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
sendMessage()
}
}
/** Called when the user taps the Send button */
private fun sendMessage() {
val editText = findViewById<EditText>(R.id.editText)
val message = editText.text.toString()
val intent = Intent(this, DisplayMessageActivity::class.java).apply
{
putExtra(EXTRA_MESSAGE, message)
}
startActivity(intent)
}