Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android view binding. How implement binding in Basic Activity/Fragment?

I am working on view binding. Kindly guide me is it possible to derive the binding logic in basic activity and how to create that? Thanks. I am trying to do this, but this code does not compile.

public class BasicActivity<Т extends ViewBinding> extends AppCompatActivity {

    private Т binding;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        binding = T.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
    }
}
like image 483
Hayo_Ghuka Avatar asked Nov 06 '19 13:11

Hayo_Ghuka


1 Answers

You can only do it with the abstract method I think. I use a similar thing like the below.

abstract class BaseActivity<V : ViewBinding> : AppCompatActivity() {
    protected open var binding: V? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        makeFullScreen()
        setContentView(getInflatedLayout(layoutInflater))
        setup()
        SharePreferenceUtil.setListenerFlutter(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        this.binding = null
        SharePreferenceUtil.removeListenerFlutter(this)
    }


    //internal functions
    private fun getInflatedLayout(inflater: LayoutInflater): View {
        this.binding = setBinding(inflater)


        return binding?.root
                ?: error("Please add your inflated binding class instance")
    }

    //abstract functions
    abstract fun setBinding(layoutInflater: LayoutInflater): V

    abstract fun setup()
}

and if you want the fragment abstract you can do like the below

abstract class BaseFragment<T : ViewBinding, A : Any> : Fragment() {
    protected var handler: A? = null //It's base activity

    protected open var binding: T? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        @Suppress("UNCHECKED_CAST")
        this.handler = this.activity as? A
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        this.binding = this.setBinding(inflater,container)
        return binding!!.root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding = null
    }
    abstract fun setBinding(inflater: LayoutInflater, container: ViewGroup?): T
}

and then you set the binding in your fragment;

override fun setBinding(inflater: LayoutInflater, container: ViewGroup?): ActivityMainBinding = ActivityMainBinding.inflate(inflater, container, false)
like image 93
Umut ADALI Avatar answered Oct 04 '22 02:10

Umut ADALI