setOnClickListener при ошибке компоновки второго фрагмента

#android #kotlin #web

#Android #kotlin #веб

Вопрос:

Я пытаюсь извлечь уроки из этого блога. Другое дело, что я пытаюсь установить его setOnClickListener во фрагменте, а не в основном действии.

Мой основной:

 package com.example.testingapp

import android.graphics.Color
import android.os.Bundle
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import android.view.inputmethod.EditorInfo
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Variable and constants declaration
        val btnShow = findViewById<Button>(R.id.btnShow)
        val editText = findViewById<EditText>(R.id.editText)
        val btnExit = findViewById<Button>(R.id.btnExit)
        val webview = findViewById<WebView>(R.id.webview)
        btnExit.setOnClickListener{
            finish()
        }

        // Function that runs when the showButton is clicked.
        // It takes one argument, which is the text entered by the user.
        // Then it loads a web page, using the text as a part of the url.
        btnShow.setOnClickListener{

            // Declare the text from editText
            val text = editText.text

            // Show the text from the user in a small toast window
            Toast.makeText(this, text, Toast.LENGTH_SHORT).show()

            // Make the webView
            webview.webViewClient = WebViewClient()
            webview.setBackgroundColor(Color.parseColor("#ffffff"))

        }
    }
}
 

Второй фрагмент:

 class SecondFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_second, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    view.findViewById<Button>(R.id.button_second).setOnClickListener {
        findNavController().navigate(R.id.action_SecondFragment_to_FirstFragment)
    }
}
 

}

fragment_second:

  <?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:id="@ id/btnUpdate"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    tools:context=".SecondFragment">

    <Button
        android:id="@ id/btnExit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginBottom="24dp"
        android:backgroundTint="@color/colorPrimary"
        android:textColor="@android:color/white"
        android:text="Exit"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <Button
        android:id="@ id/btnShow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="24dp"
        android:backgroundTint="@color/colorPrimary"
        android:text="show temp"
        android:textColor="@android:color/white"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent" />

    <WebView
        android:id="@ id/webview"
        android:layout_width="337dp"
        android:layout_height="386dp"
        android:layout_marginStart="32dp"
        android:layout_marginLeft="32dp"
        android:layout_marginEnd="32dp"
        android:layout_marginRight="32dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.581"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.213" />

    <EditText
        android:id="@ id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:ems="10"
        android:hint="Enter sensor name"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@ id/btnShow"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />



</androidx.constraintlayout.widget.ConstraintLayout>
 

Однако я застрял в этой ошибке и не смог выяснить, как это исправить:

 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.testingapp, PID: 10308
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testingapp/com.example.testingapp.MainActivity}: 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:3449)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:223)
    at android.app.ActivityThread.main(ActivityThread.java:7656)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at com.example.testingapp.MainActivity.onCreate(MainActivity.kt:59)
    at android.app.Activity.performCreate(Activity.java:8000)
    at android.app.Activity.performCreate(Activity.java:7984)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
 

Заранее благодарю вас!

Ответ №1:

в вашем button_second fragment_second

Комментарии:

1. Спасибо за ответ! Я просто немного новичок, и не могли бы вы дать мне несколько указаний по исправлению этого?

2. когда вы это делаете findViewById<Button>(R.id.button_second) , вы получаете null , потому что в вашем макете нет представления (компонента пользовательского интерфейса) с этим идентификатором fragment_second . К какой из двух кнопок вы пытаетесь ее добавить? Вам нужно использовать идентификатор, который вы назначили ему в XML, это ваш поиск

3. @cactustictacs Спасибо за ответ! Я пытаюсь добавить btnShow и btnExit. Как нужно сопоставить кнопку в правильном фрагменте? В этом блоге не показано, что нужно подходить к этому так, как это было только в основном….

4.Когда вы inflate R.layout.fragment_second в своем Fragment , он берет файл fragment_second.xml макета и создает все View s, перечисленные там, превращая их в такие вещи, как Button s и TextViews , со всеми добавленными вами настройками, включая id s для некоторых. Если вы хотите захватить один из этих View объектов (возможно, чтобы добавить прослушиватель кликов), вам нужно вызвать findViewById идентификатор объекта, который вы ищете. Итак, если вы пытаетесь установить действие щелчка для btnShow , вам нужно сделать findViewById<Button>(R.id.btnShow) , чтобы получить объект