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

时间:2017-04-23 14:33:04

标签: android inheritance

我有一个以编程方式生成的TextView(而不是在xml布局文件中)。

TextView myTextView = new TextView(this);

如何通过代码应用此TextView的父级的所有属性(不是以编程方式创建的,并且它存储在xml中)? (如何以编程方式继承?)

1 个答案:

答案 0 :(得分:0)

假设您的Root 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>

您想要动态地向此视图添加视图。然后将父级的布局参数设置为子级并设置所需的所有其他属性。最后将视图添加到root并享受。在您的Activity / Fragment中使用这样的代码 -

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,并相应地使用其他布局。