attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$onClickListener)' - layout-inflater

I'm trying to implement LayoutInflater for a button, but after doing it I'm getting this error. I'm not sure whether it has been implemented correctly or not. I tried different solutions available for the same question, but still, being new to Android, I'm finding it difficult to solve this issue.
https://www.dropbox.com/s/s2k92n6ss4mtztg/Screenrecorder-2020-11-23-00-34-16-139.mp4?dl=0 (I apologize for not able to explain the workflow but please refer this clip for better understanding, the first activity is IntroductoryActivity & the last one where start button is there is onboardingfragment3)
Please shed some light on this problem. Thank You!
IntroductoryActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_introductory);
............
**//The button from fragment_on_boarding3**
start_l=findViewById(R.id.startb);
.............
**//Having issue with this part**
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layoutScreen = inflater.inflate(R.layout.fragment_on_boarding3,null);
start_l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mainActivity = new Intent(getApplicationContext(),MainActivity.class);
startActivity(mainActivity);
// I need to save a boolean value to storage so next time when the user runs the app,I could know that he has already checked the intro screen activity
// I'm going to use shared preferences forthat process
savePrefsData();
finish();
}
});
}
private boolean restorePrefData() {
SharedPreferences pref = getApplicationContext().getSharedPreferences("myPrefs",MODE_PRIVATE);
Boolean isIntroActivityOpnendBefore = pref.getBoolean("isIntroOpnend",false);
return isIntroActivityOpnendBefore;
}
private void savePrefsData() {
SharedPreferences pref = getApplicationContext().getSharedPreferences("myPrefs",MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("isIntroOpnend",true);
editor.commit();
}
}
OnBoardingFragment3.java:
public class OnBoardingFragment3 extends Fragment {
Context mContext ;
Button start;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup root=(ViewGroup) inflater.inflate(R.layout.fragment_on_boarding3,container,false);
return root;
}
fragment_on_boarding3.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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">
<Button android:id="#+id/startb"
android:layout_width="157dp"
android:layout_height="59dp"
android:fontFamily="#font/bungee"
android:text="Let's Start"
android:textSize="15dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.754" />
</androidx.constraintlayout.widget.ConstraintLayout>
Error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.liq/com.example.liq.IntroductoryActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946) at....................

findViewById is actually is called this:
this.findViewById(someId);
this refers to Activity (in your case IntroductoryActivity);
From the docs:
Finds a view that was identified by the android:id XML attribute that was processed in onCreate(Bundle).
This onCreate() method is onCreate method of Activity on which you are calling findViewById. In your case, that id (and View) belongs to fragment so Activity is unable to find view associated with that id and returns null and you get NPE when you want to setOnClickListener to start_l button.
You can set onClickListener to that button inside onViewCreated method of fragment:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
start_l=view.findViewById(R.id.startb);
start_l.setOnClickListener.......
}
Edit: suggestion by Prince Ali is also a possible and maybe better way to do it. You can initialize views inside onCreateView:
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup root=(ViewGroup) inflater.inflate(R.layout.fragment_on_boarding3,container,false);
start_l=root.findViewById(R.id.startb);
start_l.setOnClickListener.......
return root;
}
I also recommend looking at this post

Related

Unable to call SetOnClickListener

Unable to run OnSetClickLestiner
as I can see you cant find the button with the id. You have to options
1st option: go to ur code and use the line
val myButton: Button = findViewById(R.id.button)
myButton.setOnClickListener{
...
}
2nd option: go to gradle.app file and add into the plugins the line:
id 'kotlin-android-extensions'
and then keep the same code as you have
Follow this format when calling setOnClickListener
Always initialize your Button variables before calling them.
public class MyActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_layout_id);
Button button = findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses button
}
});
}
}

How to use one event handler fro multiple buttons in Kotlin (I've already seen java with switch statements)

<Button
android:id="#+id/firstButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="firstClicked"
android:text="Color 1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.117"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.499" />
This is is the code for one button, the other 2 look the same. What I can't seem to achieve is in MainActivity.kt to have only one event handler for all three. I have found java code and can't use it as a guide correctly to transfor it to kotlin successfully, any hints?
You need to implement the OnClickListener interface in your MainActivity with a switch statement that could help you identify which button is clicked.
public class SecondActivity extends AppCompatActivity implements View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Button b1 = findViewById(R.id.b1);
Button b2 = findViewById(R.id.b2);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.b1:
Intent in = new Intent(SecondActivity.this, MainActivity.class);
SecondActivity.this.startActivity(in);
break;
case R.id.b2:
Toast.makeText(this, "Yay", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
}
For kotlin:
class MainActivity : AppCompatActivity(), View.OnClickListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btn_start_second.setOnClickListener(this)
btn_start_toast.setOnClickListener(this)
}
override fun onClick(p0: View?) {
when (p0?.id) {
R.id.btn_start_toast -> {
Toast.makeText(this,"Toast", Toast.LENGTH_SHORT).show()
}
R.id.btn_start_second -> {
startSecondApp()
}
}
}
}

Passing arguments in BottomNavigationView with navigation Component

I'm currently writing an app with the new (to me) navigation component. I've got the basics down with a single navigation graph to navigate around my app, I've got a fragment with a BottomNavigationView in which has 3 seperate fragments, I've managed to update this to use the navigation component (as far as my problem) using the menu with ids that match the navigation items. My fragments which all previously used newInstance methods to pass a bundle to the onCreate are obviously now not used but I still need to pass a bundle to my fragments.
I haven't been able to find any examples of this being done, as the fragments are implicitly created.
My code is structured as ClientFragment which is the host fragment for the navigation drawer etc which is;
class ClientFragment : Fragment() {
private val viewModel: ClientViewModel by viewModel()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_client, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.client = arguments?.getParcelable(ARG_CLIENT)!!
toolbar_client.title = viewModel.client.name
toolbar_client.setNavigationOnClickListener { Navigation.findNavController(view).navigateUp() }
}
}
This class previously held on onclick listener to my fragments, with a newInstance method which tool viewModel.client.
My fragments in the nav_graph are all similar. The first fragment;
class ClientDetailsFragment : Fragment() {
private val viewModel: ClientViewModel by viewModel()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_client_details, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// viewModel.client = arguments?.getParcelable(ARG_CLIENT)!!
initClientDetails()
}
private fun initClientDetails() {
// text_client_details_name.text = viewModel.client.name
// text_client_details_account_number.text = viewModel.client.accountNumber
// text_client_details_mobile_number.text = viewModel.client.mobileNumber
// text_client_details_landline_number.text = viewModel.client.landlineNumber
// text_client_details_email.text = viewModel.client.email
// text_client_details_address.text = "NOT YET IMPLEMENTED"
//
// text_client_description_body.text = viewModel.client.description
// text_client_system_details_body.text = viewModel.client.systemDetails
}
}
The app crashes on the commented out line;
// viewModel.client = arguments?.getParcelable(ARG_CLIENT)!!
My navigation graph and menu are;
nav graph;
<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="#+id/client_nav_graph"
app:startDestination="#id/clientDetailsFragment">
<fragment
android:id="#+id/clientCustomersFragment"
android:name="com.management.engineering.alarm.alarmengineermanagement.features.client.ClientCustomersFragment"
android:label="ClientCustomersFragment"
tools:layout="#layout/fragment_client_customers" />
<fragment
android:id="#+id/clientDetailsFragment"
android:name="com.management.engineering.alarm.alarmengineermanagement.features.client.ClientDetailsFragment"
android:label="ClientDetailsFragment"
tools:layout="#layout/fragment_client_details"/>
<fragment
android:id="#+id/clientJobHistoryFragment"
android:name="com.management.engineering.alarm.alarmengineermanagement.features.client.ClientJobHistoryFragment"
android:label="ClientJobHistoryFragment"
tools:layout="#layout/fragment_client_job_history" />
</navigation>
menu;
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/clientDetailsFragment"
android:icon="#drawable/ic_launcher_foreground"
android:title="Details"/>
<item
android:id="#+id/clientJobHistoryFragment"
android:icon="#drawable/ic_launcher_foreground"
android:title="Job History"/>
<item
android:id="#+id/clientCustomersFragment"
android:icon="#drawable/ic_launcher_foreground"
android:title="Customers"/>
</menu>
I have found that you can add arguments to the navigation graph, but have found nothing about where to put them for this specific scenario, I'm also aware of being able to manual add bundles when navigating using .navigate.
Is there a way for me to set in my ClientFragment the arguments for each of these fragments to be
viewModel.client
Update:
My argument issue was solved by using a view model that's shared between all of the fragments in the BottomNavigationView (I realised this as I was typing the issue out to my friend) and the navigation itself I added this to the ClientFragment;
bottom_nav_client.setupWithNavController(
Navigation.findNavController(
view.findViewById<View>(R.id.fl_client_nav_container)
)
)
and my xml for fragment_client;
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar_client"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navigationIcon="?attr/NavigationBackIconLight"
app:titleTextColor="#color/white" />
<fragment
android:id="#+id/fl_client_nav_container"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#id/bottom_nav_client"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/toolbar_client"
app:navGraph="#navigation/client_nav_graph" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_nav_client"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="?android:attr/windowBackground"
app:itemBackground="#color/colorPrimary"
app:itemIconTint="#drawable/bottom_nav_color"
app:itemTextColor="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/client_menu" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is combined with the same navigation graph and menu as shown above.
The Codelabs referred to in the accepted answer don't mention passing arguments to fragments in the BottomNavigationView.
Override the OnNavigationItemSelectedListener set by the setupWithNavController() with a custom one:
val args = Bundle()
bottomNavigationView.setupWithNavController(navController)
bottomNavigationView.setOnNavigationItemSelectedListener { item ->
navController.navigate(item.itemId, args)
true
}
if you are using NavigationComponent :
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
NavigationUI.onNavDestinationSelected(menuItem, navController);
}
you use this function, inside onNavDestiationSelected function you can see that navigation component passes null to args, so if you wanna pass argument to bottomNavigation fragments, simply you can write navigation function byyourselft and the only change is pass your arguments. as follow:
create a package level function :
fun onNavDestinationSelected(item: MenuItem, navController: NavController, args: Bundle?): Boolean {
val builder = NavOptions.Builder().setLaunchSingleTop(true).setRestoreState(true)
if (
navController.currentDestination!!.parent!!.findNode(item.itemId)
is ActivityNavigator.Destination
) {
builder.setEnterAnim(R.anim.nav_default_enter_anim)
.setExitAnim(R.anim.nav_default_exit_anim)
.setPopEnterAnim(R.anim.nav_default_pop_enter_anim)
.setPopExitAnim(R.anim.nav_default_pop_exit_anim)
} else {
builder.setEnterAnim(R.animator.nav_default_enter_anim)
.setExitAnim(R.animator.nav_default_exit_anim)
.setPopEnterAnim(R.animator.nav_default_pop_enter_anim)
.setPopExitAnim(R.animator.nav_default_pop_exit_anim)
}
if (item.order and Menu.CATEGORY_SECONDARY == 0) {
builder.setPopUpTo(
navController.graph.findStartDestination().id,
inclusive = false,
saveState = true
)
}
val options = builder.build()
return try {
// TODO provide proper API instead of using Exceptions as Control-Flow.
navController.navigate(item.itemId, args, options)
// Return true only if the destination we've navigated to matches the MenuItem
navController.currentDestination?.hierarchy?.any { it.id == item.itemId } == true
} catch (e: IllegalArgumentException) {
false
}
}
and use it inside onNavigationItemSelected function as follow :
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
OnNavDestinationSelectKt.onNavDestinationSelected(menuItem, navController, yourArgument);
}
The Navigation Architecture Component documentation shows how to define destination arguments, in your concrete case you should create a custom Parcelable class (i.e. Client) and include it as an argument of the corresponding fragment.
<fragment
android:id="#+id/clientCustomersFragment"
android:name="com.management.engineering.alarm.alarmengineermanagement.features.client.ClientCustomersFragment"
android:label="ClientCustomersFragment"
tools:layout="#layout/fragment_client_customers" >
<action
android:id="#+id/client_to_details"
app:destination="#+id/clientDetailsFragment" />
</fragment>
<fragment
android:id="#+id/clientDetailsFragment"
android:name="com.management.engineering.alarm.alarmengineermanagement.features.client.ClientDetailsFragment"
android:label="ClientDetailsFragment"
tools:layout="#layout/fragment_client_details">
<argument
android:name="client"
app:argType="com.management.engineering.alarm.alarmengineermanagement.features.client.Client" />
</fragment>
The 'androidx.navigation.safeargs' gradle plugin will generate the classes ClientToDetails and ClientDetailsFragmentArgs which can be used to pass.retrieve the parameter client.
Source
val client: Client = TODO()
val navController: NavController = TODO()
navController.navigate(ClientToDetails(client))
Destination
val client = ClientDetailsFragmentArgs.fromBundle(arguments).client
This codelabs exactly what you want to do :
https://codelabs.developers.google.com/codelabs/android-navigation/index.html?index=..%2F..index#0
Docs : https://developer.android.com/topic/libraries/architecture/navigation/

Exepting member declaration [duplicate]

I'm trying to finish an activity from another (android) with kotlin. I know the wat to do it with java is with the following code (https://stackoverflow.com/a/10379275/7280257)
at the first activity:
BroadcastReceiver broadcast_reciever = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
String action = intent.getAction();
if (action.equals("finish_activity")) {
finish();
// DO WHATEVER YOU WANT.
}
}
};
registerReceiver(broadcast_reciever, new IntentFilter("finish_activity"));
On the other activity:
Intent intent = new Intent("finish_activity");
sendBroadcast(intent);
For some reason converting the java activity to kotlin doesn't give a valid output, if someone could give me the correct syntax to do it properly with kotlin I will appreciate it
kotlin output (first activity) [OK]:
val broadcast_reciever = object : BroadcastReceiver() {
override fun onReceive(arg0: Context, intent: Intent) {
val action = intent.action
if (action == "finish_activity") {
finish()
// DO WHATEVER YOU WANT.
}
}
}
registerReceiver(broadcast_reciever, IntentFilter("finish_activity"))
kotlin output (2nd activity) [OK]
val intent = Intent("finish_activity")
sendBroadcast(intent)
ERROR: http://i.imgur.com/qaQ2YHv.png
FIX: THE CODE SHOWN IS RIGHT, YOU JUST NEED TO PLACE IT INSIDE THE onCreate FUNCTION
Simple code to finish a particular activity from another:
class SplashActivity : AppCompatActivity(), NavigationListner {
class MyClass{
companion object{
var activity: Activity? = null
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MyClass.activity = this#SplashActivity
}
override fun navigateFromScreen() {
val intent = Intent(this,LoginActivity::class.java)
startActivity(intent)
}
}
Now call SplashActivity.MyClass.activity?.finish() from another activity to finish above activity.
The error Expecting member declaration is there because you wrote a statement (the function call) inside a class. In that scope, declarations (functions, inner classes) are expected.
You have to place your statements inside functions (and then call those from somewhere) in order for them to be executed.

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)
}