Can we add a common button on all activity without add code in xml file.
we need to add some code in application class and button show in all activity of app.
CodePudding user response:
First create a BaseActivity. Then add this code to onCreate of that:
class BaseActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_nav_host)
//the layout of baseActivity
LinearLayout layout =(LinearLayout) findViewById (R.id.base_activity_layout);
//set the properties for button
Button btnTag = new Button(this);
btnTag.setLayoutParams(
new LayoutParams (LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT
));
btnTag.setText("Button");
btnTag.setId(some_random_id);
//add button to the layout
layout.addView(btnTag);
}
}
Then let other activities which you want to create being inherited from BaseActivity.
class FirstActivity : BaseActivity() {
//
//
}
class SecondActivity : BaseActivity() {
//
//
}
class ThirdActivity : BaseActivity() {
//
//
}
CodePudding user response:
class ButtonActivity: Activity() { protected var btnCommon: Button
override fun onCreate(saved: Bundle?) {
var layout = findViewById(R.id.layout) as ConstraintLayout
btnCommon = Button(this)
// set Button properties
layout.addView(button)
}
}
How to use
class MyActivity: ButtonActivity() {
onCreate() {
this.btnCommon.setOnClickListener...... // now you can use.
}
}
