我有基本活动为我的应用程序的每个屏幕实现一些功能。然后,每个子活动都会使用其 XML 布局覆盖方法。
基础活动
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.base_screen);
View mFormView = findViewById(R.id.pnContent);
if (getContentAreaLayoutId() != 0) {
LayoutInflater inflater = LayoutInflater.from(this);
View contentLayout = inflater.inflate(getContentAreaLayoutId(), (ViewGroup) mFormView, false);
((ViewGroup) mFormView).addView(contentLayout, 0);
}
}
儿童活动
override fun getContentAreaLayoutId(): Int = R.layout.standard_content_settings
现在我想在我的子活动中使用视图绑定。我在想这样的事情:
override fun onCreate(savedInstanceState: Bundle?) {
val binding = StandardContentSettingsBinding.inflate(layoutInflater)
}
但是当我使用绑定(
binding.edURL.setText("test")
)时,视图不会改变并保持为空。我想我使用的视图绑定错误,必须用另一种方式来膨胀它?
您可以在
BaseActivity
中膨胀绑定对象并向子活动公开方法以获取绑定对象。
public abstract class BaseActivity extends AppCompatActivity {
//base binding
private BaseScreenBinding baseBinding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // always call base methods, your code didnt have those calls.
baseBinding = BaseScreenBinding.inflate(getLayoutInflater());
setContentView(baseBinding.getRoot());
//your existing code to inflate child content
View mFormView = baseBinding.pnContent;
if (getContentAreaLayoutId() != 0) {
LayoutInflater inflater = LayoutInflater.from(this);
View contentLayout = inflater.inflate(getContentAreaLayoutId(), (ViewGroup) mFormView, false);
((ViewGroup) mFormView).addView(contentLayout, 0);
}
}
protected BaseScreenBinding getBaseBinding() {
return baseBinding;
}
protected abstract int getContentAreaLayoutId();
}
您现在可以在子活动中使用 ViewBinding,您的布局由 BaseActivity 扩展,在子活动中您将绑定到它。
class ChildActivity : BaseActivity() {
private lateinit var binding: StandardContentSettingsBinding
override fun getContentAreaLayoutId(): Int = R.layout.standard_content_settings
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Layout was inflated in BaseActivity, so now only bind to it.
binding = StandardContentSettingsBinding.bind(getBaseBinding().pnContent)
//This should work now
binding.edURL.setText("test")
}
}
在子活动中,调用
StandardContentSettingsBinding.bind(View)
与 inflate()
不同,因为它不会创建新的视图层次结构,而是使用现有的视图层次结构,这正是本例中您想要的。
一些参考: https://developer.android.com/topic/libraries/data-binding/ generated-binding