如何将相对布局添加到视图

时间:2013-10-24 09:27:39

标签: android android-layout android-viewpager android-view

我有一个自定义的相对布局并添加了一个按钮

 RelativeLayout rel_layout = new RelativeLayout(mcontext);
 RelativeLayout.LayoutParams rel_param = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
 rel.setLayoutParams(rel_param);

 Button b = new Button(mcontext);
 RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
 b.setLayoutParams(params);
 b.setText("Test");
 rel_layout.addView(b);

现在,我想将此相对布局添加到视图中。我的View类看起来像是

public class CustomView extends View {

Context mcontext;

public CustomView(Context context) {
    super(context);

    this.mcontext = context;
}

}

在主要活动中我在setConentView()

中调用此视图
public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(new CustomView(this));
}

}

所以现在在屏幕上我应该有相应的布局和按钮。我不应该使用任何XMl。

我需要帮助来了解如何添加要添加到我的CustomView类的动态相对

希望我已经清楚地解释了我的问题。

3 个答案:

答案 0 :(得分:0)

您的自定义视图必须扩展ViewGroup,而不是View

答案 1 :(得分:0)

你不应该这样做。 RelativeLayoutViewGroupViewGroup是一个View,可以将一个或多个View作为孩子。您应该实施自己的ViewGroup而不是View 您可以在此处找到实施自定义ViewGroup的教程:
https://developer.android.com/reference/android/view/ViewGroup.html

另外,我建议你可能确实想要RelativeLayout直接放在Activity上,并在其上放置一些自定义小部件以及你提到的按钮。

答案 2 :(得分:0)

// try this 
custom_view.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/relCustomView"
    android:background="@android:color/darker_gray"
    android:padding="5dp">

</RelativeLayout>

public class CustomView extends View{
    private Context context;

    public  CustomView(Context context) {
        super(context);
        this.context=context;
    }
    public View getCustomView(){
        View v = LayoutInflater.from(context).inflate(R.layout.custom_view,null,false);

        RelativeLayout relCustomView = (RelativeLayout) v.findViewById(R.id.relCustomView);

        Button b = new Button(context);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        b.setLayoutParams(params);
        b.setText("Test");
        relCustomView.addView(b);
        return v;
    }
}

@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new CustomView(this).getCustomView());
}