添加&删除Activity Java代码中的自定义布局元素

时间:2012-03-07 10:08:33

标签: android android-layout android-activity android-intent

我有一个主要活动

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

              //HOW TO: dynamically add or remove <com.my.custom.MyCustomLayout>
        }
}

上述主要活动的内容为:

main.xml中

<FrameLayout ...>

    <LinearLayout ...>

    <com.my.custom.MyCustomLayout
          android:id="@+id/custom">

<FrameLayout>

如上所述,我有一个自定义布局元素,这是一个Java类扩展LinearLayout,如下所示:

public class MyCustomLayout extends LinearLayout{
          ...
}

在我的活动 java代码中,我想在 main.xml 添加或删除自定义布局元素<com.my.custom.MyCustomLayout> >布局。 如何在我的活动Java代码中执行此操作?

3 个答案:

答案 0 :(得分:1)

使用自定义视图创建不同的布局文件,如:

difflayout.xml:

<com.my.custom.MyCustomLayout
          xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/custom">

在代码部分中引用容器LinearLayout。使用LayoutInflater课程的addView()removeAllViews()以及ViewGroup(此处为LinearLayout

答案 1 :(得分:1)

首先考虑一下你是否真的要从布局中删除视图或者只是完全隐藏它。你需要有充分的理由去寻找后者。

只隐藏您在活动中执行的视图

findViewById(R.id.custom).setVisibility(View.GONE) // to hide
// or
findViewById(R.id.custom).setVisibility(View.VISIBLE) // to show

如果您确实要从布局中完全删除视图,可以

View customView = findViewById(R.id.custom);
ViewGroup parentView = (ViewGroup) customView.getParent();
parentView.removeView(customView)

答案 2 :(得分:0)

您必须已为自定义布局定义了id。在java代码中使用此id 例如:customLayout = (LinearLayout)findViewById(id);
现在用customLayout调用布局