java 动态添加内容的ViewBinding

nc1teljy  于 2023-09-29  发布在  Java
关注(0)|答案(1)|浏览(120)

我有一个基本的活动,为我的应用程序的每个屏幕实现一些功能。然后每个子活动用其XML布局重写方法。

BaseActivity

@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(binding.edURL.setText("test"))时,view并没有改变,而是保持为空。我想我使用的视图绑定错误,必须用另一种方式膨胀?

5jdjgkvh

5jdjgkvh1#

您可以在BaseActivity中膨胀绑定对象,并将方法公开给子Activity以获取绑定对象。

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();
}

你现在可以在你的子Activity中使用ViewBinding,你的布局被BaseActivity膨胀,在子Activity中你将绑定到它。

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")
    }
}

在子Activity中,调用StandardContentSettingsBinding.bind(View)inflate()不同,因为它不会创建新的视图层次结构,而是使用现有的视图层次结构,这正是您在本例中所希望的。
一些参考文献:https://developer.android.com/topic/libraries/data-binding/generated-binding

相关问题