如何从片段类中访问RecyclerView中的TextView ID?

huangapple go评论58阅读模式
英文:

How do I access a textview Id from recyclerView in fragment class?

问题

以下是您要翻译的内容:

"I have a recycler view and a XML file for the recycler view. I have used the recycler views inside the fragment layout. I want to access the textview id from the fragment activity for using fragment transactions.

var titleTextView = view.findViewById(R.id.tvTitle)

val subjectFragment = SubjectFragment()

println(titleTextView.text)

the above code provides a null pointer exception

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.samachar, PID: 7038
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference
        at com.example.samachar.NewsFragment.onViewCreated(NewsFragment.kt:86)
        at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:2987)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:546)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
        at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
        at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2100)
        at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002)
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3138)
        at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:3072)
        at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:251)
        at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:502)
        at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:248)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1435)
        at android.app.Activity.performStart(Activity.java:8024)
        at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3475)
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
        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)
I/Process: Sending signal. PID: 7038 SIG: 9

I want to use the fragment manager to use the transactions and switch layouts

// var fragment = parentFragmentManager?.beginTransaction()
// fragment?.replace(R.id.newsFrameLayout, subjectFragment)
// fragment?.commit()

but I cannot seem to access the textview id from the fragment class.

<?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/newsItem"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingHorizontal="16dp"
    android:paddingVertical="12dp">

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/title_eg"
        android:textColor="@color/purple_200"
        android:textSize="14sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tvDescription"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/description_eg"
        android:textSize="12sp"
        android:textColor="@color/black"
        android:maxLines="2"
        android:justificationMode="inter_word"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvTitle" />

    <TextView
        android:id="@+id/tvCategory"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/teal_700"
        android:padding="2dp"
        android:text="@string/category_eg"
        android:textColor="@color/white"
        android:textSize="10sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvDescription" />

    <TextView
        android:id="@+id/tvPublishedDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/pub_date_eg"
        android:textSize="10sp"
        app:layout_constraintBottom_toBottomOf="@+id/tvCategory"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvDescription" />

</androidx.constraintlayout.widget.ConstraintLayout>

This is the xml layout used in the recycler view of the app

EDIT***

Solved it by using the onClickListener on textview in the adapter class onBindViewHolder function and used activity context for calling the supportFragmentManager."

英文:

I have a recycler view and a XML file for the recycler view. I have used the recycler views inside the fragment layout. I want to access the textview id from the fragment activity for using fragment transactions.

    var titleTextView = view.findViewById&lt;TextView&gt;(R.id.tvTitle)
val subjectFragment = SubjectFragment()
println(titleTextView.text)

the above code provides a null pointer exception

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.samachar, PID: 7038
java.lang.NullPointerException: Attempt to invoke virtual method &#39;java.lang.CharSequence android.widget.TextView.getText()&#39; on a null object reference
at com.example.samachar.NewsFragment.onViewCreated(NewsFragment.kt:86)
at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:2987)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:546)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2100)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3138)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:3072)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:251)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:502)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:248)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1435)
at android.app.Activity.performStart(Activity.java:8024)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3475)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
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)
I/Process: Sending signal. PID: 7038 SIG: 9

I want to use the fragment manager to use the transactions and switch layouts

//            var fragment = parentFragmentManager?.beginTransaction()
//            fragment?.replace(R.id.newsFrameLayout, subjectFragment)
//            fragment?.commit()

but I cannot seem to access the textview id from the fragment class.

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
xmlns:tools=&quot;http://schemas.android.com/tools&quot;
android:id=&quot;@+id/newsItem&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;wrap_content&quot;
android:paddingHorizontal=&quot;16dp&quot;
android:paddingVertical=&quot;12dp&quot;&gt;
&lt;TextView
android:id=&quot;@+id/tvTitle&quot;
android:layout_width=&quot;0dp&quot;
android:layout_height=&quot;wrap_content&quot;
android:text=&quot;@string/title_eg&quot;
android:textColor=&quot;@color/purple_200&quot;
android:textSize=&quot;14sp&quot;
android:textStyle=&quot;bold&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;
&lt;TextView
android:id=&quot;@+id/tvDescription&quot;
android:layout_width=&quot;0dp&quot;
android:layout_height=&quot;wrap_content&quot;
android:text=&quot;@string/description_eg&quot;
android:textSize=&quot;12sp&quot;
android:textColor=&quot;@color/black&quot;
android:maxLines=&quot;2&quot;
android:justificationMode=&quot;inter_word&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toBottomOf=&quot;@+id/tvTitle&quot; /&gt;
&lt;TextView
android:id=&quot;@+id/tvCategory&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:background=&quot;@color/teal_700&quot;
android:padding=&quot;2dp&quot;
android:text=&quot;@string/category_eg&quot;
android:textColor=&quot;@color/white&quot;
android:textSize=&quot;10sp&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toBottomOf=&quot;@+id/tvDescription&quot; /&gt;
&lt;TextView
android:id=&quot;@+id/tvPublishedDate&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:text=&quot;@string/pub_date_eg&quot;
android:textSize=&quot;10sp&quot;
app:layout_constraintBottom_toBottomOf=&quot;@+id/tvCategory&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintTop_toBottomOf=&quot;@+id/tvDescription&quot; /&gt;
&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;

This is the xml layout used in the recycler view of the app

EDIT***

Solved it by using the onClickListener on textview in the adapter class onBindViewHolder function and used activity context for calling the supportFragmentManager.

答案1

得分: 0

当您使用一个recyclerview时,没有可用的唯一tvtitle id。对于recyclerview中的每个项目,都有一个tvtitle。尽管您可以从recyclerview适配器中访问它们中的每一个。

英文:

When you use a recyclerview there isn't a unique tvtitle id available. For each item in the recyclerview there is a tvtitle.
Although you can aceess each of them from the recyclerview adapter.

答案2

得分: 0

如果您想访问RecyclerView的任何项,那么您需要在onBindViewHolder中创建一个事件。
使用接口或Lambda函数来获取活动或片段中的每个视图。
如果您想要在点击事件发生时获取视图,请实现点击监听器。

英文:

If you want to access any item of recyclerview then you need to create a event at onBindViewHolder .
Use interface or lambda funtion for getting every view inside activity or fragment.

if you want views when click event happen then implement clickListener.

答案3

得分: 0

以下是已翻译的内容:

在你的适配器类中,你应该有一些项目点击监听器,如下所示:

interface ItemClickListener {
fun onClick(dataYouWantInFragment:String) // or of any type
}

然后,你应该在适配器类中要求实现你的碎片的接口,如下所示:

class YourRVAdapter(private val listener:ItemClickListener) {
override fun onBindViewHolder(holder:YourViewHolder,position:Int) {
holder.bindData(dataForPosition(position),listener)
}
class YourViewHolder(private val view:View) : RecyclerView.ViewHolder(view) {
private val tvTitle = view.findViewById<TextView>(R.id.tvTitle)
fun bindData(data:String,listener:ItemClickListener) {
tvTitle.text = data
view.setOnClickListener {
listener.onClick(tvTitle.text.toString())// pass the data you want in fragment
}
}
}
// 如果你使用了绑定,
class YourViewHolder(private val binding:YourBinding) : RecyclerView.ViewHolder(binding.root) {
fun bindData(data:String,listener:ItemClickListener) {
binding.tvTitle.text = data
binding.root.setOnClickListener {
listener.onClick(tvTitle.text.toString())// pass the data you want in fragment
}
}
}
}

在你的碎片类中,你应该像下面这样实现该监听器接口:

class YourFragmentClass() : ItemClickListener {
override fun onCreateView(...) {
..
recyclerView.adapter = YourRVAdapter(this)
..
}
override fun onClick(dataYouWant:String) {
// use this data for your fragment transaction
childFragmentManager.beginTransaction().add/replace()....commit()
}
}

现在,当你点击一个 RecyclerView 项时,你应该能够在你的碎片类中获得带有所需数据的 onClick() 回调。

英文:

You should have some item click listner in your adapter class this way:

interface ItemClickListener {
fun onClick(dataYouWantInFragment:String) // or of any type
}

Then you should ask for the interface implementation of your fragment in your adapter class like below:

class YourRVAdapter(private val listener:ItemClickListener) {
override fun onBindViewHolder(holder:YourViewHolder,position:Int) {
holder.bindData(dataForPosition(position),listener)
}
class YourViewHolder(private val view:View) : RecyclerView.ViewHolder(view) {
private val tvTitle = view.findViewById&lt;TextView&gt;(R.id.tvTitle)
fun bindData(data:String,listener:ItemClickListener) {
tvTitle.text = data
view.setOnClickListener {
listener.onClick(tvTitle.text.toString())// pass the data you want in fragment
}
}
}
// If you used binding,
class YourViewHolder(private val binding:YourBinding) : RecyclerView.ViewHolder(binding.root) {
fun bindData(data:String,listener:ItemClickListener) {
binding.tvTitle.text = data
binding.root.setOnClickListener {
listener.onClick(tvTitle.text.toString())// pass the data you want in fragment
}
}
}
}

in your fragment class, you should implement that listener interface like below:

class YourFragmentClass() : ItemClickListener {
override fun onCreateView(...) {
..
recyclerView.adapter = YourRVAdapter(this)
..
}
override fun onClick(dataYouWant:String) {
// use this data for your fragment transaction
childFragmentManager.beginTransaction().add/replace()....commit()
}
}

Now, you should be able to get the onClick() callback in your fragment class with you desired data when you click on a recycler view item.

huangapple
  • 本文由 发表于 2023年1月6日 10:27:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75026350.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定