如何以编程方式将布局继承应用于Android视图



我有一个通过编程生成的文本视图(而不是XML布局文件(。

TextView myTextView = new TextView(this);

如何通过代码将本TextView的所有属性应用于本textView的所有属性(不是通过编程性创建,并将其存储在XML中(?(我如何以编程性继承?(

假设您的根XML是 -

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
</LinearLayout>

您想动态添加视图到此视图。然后将父的布局参数设置为孩子,并设置所需的所有其他属性。最后,将视图添加到根部并享受。在您的活动/片段中使用这样的代码 -

LinearLayout rootLayout = (LinearLayout) findViewById(R.id.root_layout);
TextView textView = new TextView(context);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.CENTER;
textView.setLayoutParams(layoutParams);
textView.setGravity(Gravity.CENTER);
textView.setText("Hello");
rootLayout.addView(textView);

注意:如果您的根布局是Relativelayout,则应使用Relativelayout.layoutparams,并相应地使用。

最新更新