简体   繁体   中英

Custom view doesn't update inside a Fragment

I have a project in which I have to build views inside a custom Layout. This layout represents the concept of View in MVP architecture and it lives in a Fragment. The view should be updated by the Presenter whenever an event happens, by calling the View and finally that will update TextViews inside the View . But it seems that after the View is initialized, nothing gets updated anymore.

If my presenter calls the View that contains my TextView - nothing. If I try to update the TextView directly, from the fragment then it works. I can't really understand what is happening and why it doesn't get updated from within the layout that contains that TextView .

MyCustomView:

class MyCustomView(fragment: MyFragment): MyViewInterface, FrameLayout(fragment.context) {

    init {
        View.inflate(context, R.layout.my_fancy_layout, this)
    }

    override fun getView(): View {
        return this
    }

    override fun setData(uiModel: UiModel) {
        textview_name.text = uiModel.name
    }
}

MyFragment:

class MyFragment : Fragment() {

    @Inject lateinit var view: MyViewInterface
    @Inject lateinit var presenter: MyCustomPresenter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ... dagger injection ...
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return this.view.getView()
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        presenter.setData(...some ID to fetch data from API...)
        //textview_name.text = "blue" //this works instead
    }
}

MyPresenter:

class MyPresenter @Inject constructor(
        private val repo: MyRepository,
        private val view: MyViewInterface
) {

    fun setData(productCode: String) {
        .. some code ...
        view.setData(it) //call to my view          
    }
}

MyViewInterface:

interface MyViewInterface {
    fun getView(): View

    fun setData(uiModel: UiModel)
}

Because of you just inflate when create view

    init {
        View.inflate(context, R.layout.my_fancy_layout, this)
    }

add invalidate view in update data function

  override fun setData(uiModel: UiModel) {
        textview_name.text = uiModel.name
         this.invalidate()
         this.requestLayout()

    }

All I can think of is the view's instance is not the same in your UI and presenter. I dont know your Dagger's code so I do not have any suggestions to fix it.

You could move the view away from MyPresenter's constructor and set it in MyFragment.onCreate after injection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM