android:自定义视图未显示

时间:2015-05-26 09:33:13

标签: android android-layout

我在创建自定义视图时遇到了问题。

如果我的理解是正确的,我希望有一个复合视图,其中像Switch这样的ui元素可以合并到自定义视图中。这意味着一个模态视图,它显示了一系列具有保存和放大功能的开关。具有相对操作的后退按钮,与应用内表单目的相关。

在其他示例/问题中,人们提到this.addView(View childView)但是当我尝试使用此功能时,我从android studio获得了一个未解决的符号错误。执行时,应用程序显示为空白。

public class NewView extends View {
private Switch switchOne;
private Switch switchTwo;

public NewView(Context context){
    super(context);
    init(null, 0);
}

public NewView(Context context, AttributeSet attrs){
    super(context);
    init(attrs, 0);
}

public NewView(Context context, AttributeSet attrs, int defStyle){
    super(context);
    init(attrs, defStyle);
}

private void init(AttributeSet attrs, int defStyle) {

    //LayoutInflater.from(getContext()).inflate(R.layout.customview, (ViewGroup) this.getParent(), true); //First attempted this approach
    ((Activity) getContext()).getLayoutInflater().inflate(R.layout.customview, (ViewGroup) this.getParent()); //then attempted this approach

    this.switchOne = (Switch) findViewById(R.id.firstSwitch);
    this.switchTwo = (Switch) findViewById(R.id.secondSwitch);
}

@Override
public void onDraw(Canvas canvas){
    super.onDraw(canvas);
}

}

customview.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/mainView">

    <Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/firstSwitch"/>
    <Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/secondSwitch"/>

</LinearLayout>

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <com.example.simonaddicott.customviewone.NewView
        android:layout_height="match_parent"
        android:layout_width="match_parent"

        android:id="@+id/myNewView"
        />

</LinearLayout>

1 个答案:

答案 0 :(得分:1)

从ViewGroup扩展,覆盖onLayout并提供实现。或者,因为您似乎只想垂直布局开关,只需从LinearLayout扩展以重用其布局规则并在activity_main.xml中设置NewView的方向,或者如果要覆盖xml,则在代码中设置方向设置并强制执行垂直布局。

将customview.xml中的根LinearLayout替换为merge

充气时,使用this而非this.getParent()作为第二个参数