[Android] [ListView] Не удается отобразить ListView во фрагменте - PullRequest
0 голосов
/ 24 февраля 2019

Язык: kotlin target: sdk latest

Итак, что на самом деле здесь происходит,

У меня есть нижняя панель навигации с четырьмя вкладками и фрагментом для каждой вкладки.

В первом фрагменте я пытаюсь отобразить статический ListView, который заставляет приложение закрываться.

MainActivity.kt

import android.os.Bundle
    import android.widget.ArrayAdapter
    import android.widget.ListView
    import androidx.appcompat.app.AppCompatActivity
    import com.google.android.material.bottomnavigation.BottomNavigationView
    import android.widget.TextView
    import androidx.fragment.app.Fragment
    import android.content.ClipData.Item
    import android.widget.ListAdapter
    import kotlinx.android.synthetic.main.fragment_rough_calc.*


    class MainActivity : AppCompatActivity() {

        private lateinit var fragment: Fragment
        private lateinit var listView: ListView
        private val onNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
            when (item.itemId) {
                R.id.navigation_rough -> {
                    //supportFragmentManager.beginTransaction().replace(R.id.fragment_in_rough_calc, PolishCalcFragment()).commit()
                    supportFragmentManager.beginTransaction().replace(R.id.fragment_container, RoughCalcFragment()).commit()
                    return@OnNavigationItemSelectedListener true
                }
                R.id.navigation_polish -> {
                    supportFragmentManager.beginTransaction().replace(R.id.fragment_container, PolishCalcFragment()).commit()
                    return@OnNavigationItemSelectedListener true
                }
                R.id.navigation_saved -> {
                    supportFragmentManager.beginTransaction().replace(R.id.fragment_container, SavedFragment()).commit()
                    return@OnNavigationItemSelectedListener true
                }
                R.id.navigation_settings -> {
                    supportFragmentManager.beginTransaction().replace(R.id.fragment_container, SettingsFragment()).commit()
                    return@OnNavigationItemSelectedListener true
                }
            }
            true
        }

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

            val navView: BottomNavigationView = findViewById(R.id.nav_view)
            navView.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener)
            listView = findViewById<ListView>(R.id.part_list)
            val partList = ArrayList<String>()//Creating an empty arraylist
            partList.add("Part A")
            partList.add("Part B")
            partList.add("Part C")
            partList.add("Part D")
            partList.add("Part E")

            var partAdapterStatic = ArrayAdapter<String>(this, R.layout.part_view, partList)

            listView.adapter = partAdapterStatic

            supportFragmentManager.beginTransaction().replace(R.id.fragment_container, RoughCalcFragment()).commit()

        }

    }

activity_main.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:id = "@+id/container"
        android:layout_width = "match_parent"
        android:layout_height = "match_parent"
        tools:context = ".MainActivity">

    <FrameLayout
            android:id = "@+id/fragment_container"
            android:layout_width = "match_parent"
            android:layout_height = "wrap_content"
            app:layout_constraintEnd_toEndOf = "parent"
            app:layout_constraintBottom_toTopOf = "parent"
            app:layout_constraintTop_toTopOf = "parent"
            app:layout_constraintStart_toStartOf = "parent"/>

    <com.google.android.material.bottomnavigation.BottomNavigationView
            style = "@style/Widget.MaterialComponents.BottomNavigationView.Colored"
            android:id = "@+id/nav_view"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            app:layout_constraintBottom_toBottomOf = "parent"
            app:layout_constraintLeft_toLeftOf = "parent"
            app:layout_constraintRight_toRightOf = "parent"
            app:menu = "@menu/bottom_nav_menu"
            android:elevation = "0px"
            app:itemIconTint = "@drawable/bottom_navigation_colors"
            app:itemTextColor = "@drawable/bottom_navigation_colors"/>

</androidx.constraintlayout.widget.ConstraintLayout>

фрагмент_1.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        xmlns:android = "http://schemas.android.com/apk/res/android"
        xmlns:tools = "http://schemas.android.com/tools"
        android:layout_width = "match_parent"
        android:layout_height = "match_parent"
        xmlns:app = "http://schemas.android.com/apk/res-auto"
        android:background = "@color/colorPrimary"
        android:paddingTop="175dp"
        android:paddingLeft="15dp"
        android:paddingRight="15dp">

    <com.google.android.material.textfield.TextInputLayout
            style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox"
            android:id="@+id/rawStoneWeight"
            app:boxCornerRadiusBottomEnd ="10dp"
            app:boxCornerRadiusBottomStart="10dp"
            app:boxCornerRadiusTopStart="10dp"
            app:boxCornerRadiusTopEnd="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/rough_weight_input_hint"
            app:hintAnimationEnabled="true">

        <com.google.android.material.textfield.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="numberDecimal"
                android:autoSizeMaxTextSize="5dp"
                android:textStyle="bold"
                android:maxLength="6"/>

    </com.google.android.material.textfield.TextInputLayout>

    <androidx.appcompat.widget.AppCompatTextView
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:text="@string/rough_weight_input_suffix"
            android:layout_alignParentEnd="true"
            android:paddingTop="35dp"
            android:paddingEnd="17dp"
            android:paddingStart="17dp"
            android:textStyle="bold" />

    <ListView
            android:id="@+id/part_list"
            android:layout_below="@id/rawStoneWeight"
            android:paddingBottom="90dp"
            android:layout_width = "match_parent"
            android:layout_height = "wrap_content" >

    </ListView>

</RelativeLayout>

Ошибка в журнале:

2019-02-24 17:51:26.876 22239-22239/in.navkargems.tools E/AndroidRuntime: FATAL EXCEPTION: main
    Process: in.navkargems.tools, PID: 22239
    java.lang.RuntimeException: Unable to start activity ComponentInfo{in.navkargems.tools/in.navkargems.tools.MainActivity}: java.lang.IllegalStateException: findViewById<ListView>(R.id.part_list) must not be null
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2951)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3086)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1816)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6718)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.IllegalStateException: findViewById<ListView>(R.id.part_list) must not be null
        at in.navkargems.tools.MainActivity.onCreate(MainActivity.kt:48)
        at android.app.Activity.performCreate(Activity.java:7144)
        at android.app.Activity.performCreate(Activity.java:7135)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2931)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3086) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1816) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:193) 
        at android.app.ActivityThread.main(ActivityThread.java:6718) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 

Пожалуйста, помогите мне решить эту проблему Спасибо всем за ваше время (:

Ответы [ 2 ]

0 голосов
/ 24 февраля 2019

Переместите свой код ниже в RoughCalcFragment

listView = findViewById<ListView>(R.id.part_list)
        val partList = ArrayList<String>()//Creating an empty arraylist
        partList.add("Part A")
        partList.add("Part B")
        partList.add("Part C")
        partList.add("Part D")
        partList.add("Part E")

        var partAdapterStatic = ArrayAdapter<String>(this, R.layout.part_view, partList)

        listView.adapter = partAdapterStatic

А также его не listView = findViewById (R.id.part_list) , но listView = view.findViewById (R.id.part_list) в вашем RoughCalcFragment

0 голосов
/ 24 февраля 2019

Ваша проблема здесь

        listView = findViewById<ListView>(R.id.part_list)

ваш список находится во фрагменте, а не в активности

, поэтому listView будет иметь значение Null

Так что вы должны определить свой список Посмотреть во фрагментеИ начальное оно

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...