假设我有一个线性布局,我想在我的程序中,从Java代码中添加一个视图。使用什么方法?我问的不是如何在XML中完成它(我知道XML是如何完成的),而是如何沿着这个示例代码行完成一些事情?

(One View).add(Another View)

就像在Swing中一样。


当前回答

我发现最好的方法是使用View的充气静态方法。

View inflatedView = View.inflate(context, yourViewXML, yourLinearLayout);

yourViewXML类似于r。layout。myview

请注意,你需要一个ViewGroup来添加一个视图(这是任何你能想到的布局)

举个例子,假设你有一个片段,它的视图已经膨胀了,你知道根视图是一个布局,你想给它添加一个视图:

    View view = getView(); // returns base view of the fragment
    if (view == null)
        return;
    if (!(view instanceof ViewGroup))
        return;

    ViewGroup viewGroup = (ViewGroup) view;
    View popup = View.inflate(viewGroup.getContext(), R.layout.someView, viewGroup);

编辑:

上面例子的Kotlin代码(view是片段的getView())

(view as? ViewGroup)?.let {
        View.inflate(context, R.layout.add_credit_card, it)
}

其他回答

我发现最好的方法是使用View的充气静态方法。

View inflatedView = View.inflate(context, yourViewXML, yourLinearLayout);

yourViewXML类似于r。layout。myview

请注意,你需要一个ViewGroup来添加一个视图(这是任何你能想到的布局)

举个例子,假设你有一个片段,它的视图已经膨胀了,你知道根视图是一个布局,你想给它添加一个视图:

    View view = getView(); // returns base view of the fragment
    if (view == null)
        return;
    if (!(view instanceof ViewGroup))
        return;

    ViewGroup viewGroup = (ViewGroup) view;
    View popup = View.inflate(viewGroup.getContext(), R.layout.someView, viewGroup);

编辑:

上面例子的Kotlin代码(view是片段的getView())

(view as? ViewGroup)?.let {
        View.inflate(context, R.layout.add_credit_card, it)
}

LinearLayout是ViewGroup的子类,它有一个叫做addView的方法。addView方法应该是您想要的。

从活动中添加视图的另一种方法

ViewGroup rootLayout = findViewById(android.R.id.content);
rootLayout.addView(view);

调用addView是正确的答案,但是要使它工作,还需要做更多的工作。

如果你通过构造函数创建一个视图(例如,Button myButton = new Button();),你需要在新构造的视图上调用setLayoutParams,在你将新构造的子视图添加到父视图之前,传入父视图的LayoutParams内部类的实例。

例如,你可能在你的onCreate()函数中有以下代码,假设你的LinearLayout有id R.id.main:

LinearLayout myLayout = findViewById(R.id.main);

Button myButton = new Button(this);
myButton.setLayoutParams(new LinearLayout.LayoutParams(
                                     LinearLayout.LayoutParams.MATCH_PARENT,
                                     LinearLayout.LayoutParams.MATCH_PARENT));

myLayout.addView(myButton);

确保设置了LayoutParams很重要。每个视图至少需要一个layout_width和一个layout_height参数。获得正确的内部类也很重要。我努力将视图添加到TableRow以正确显示,直到我发现我没有传递TableRow的实例。子视图的setLayoutParams。

你们也应该确保当你重写onLayout时,你必须调用super。onLayout的所有属性,否则视图将不会被膨胀!