2013-05-07 98 views
0

layout_main.xml:自定义视图从继承的LinearLayout不能显示

<RelativeLayout 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:background="#ffffff" 
    tools:context=".MainActivity" > 

    <com.example.testandroid.MainView 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 
</RelativeLayout> 

的MainView:

public class MainView extends ViewGroup { 
    public MainView(Context context, AttributeSet as) { 
     super(context); 
     addView(new ZoomController(context)); 
    } 
    @Override 
    protected void onLayout(boolean changed, int l, int t, int r, int b) { 
     for (int i = 0, len = getChildCount(); i < len; i++) { 
      View v = getChildAt(i); 
      v.layout(0, 0, r - l, b - t); 
     } 
    } 
} 

ZoomController:

public class ZoomController extends LinearLayout { 
    private Button zoomIn; 
    public ZoomController(Context context) { 
     super(context); 
     zoomIn = new Button(context); 
     zoomIn.setText("+"); 

     setOrientation(1); 
     addView(zoomIn); 
    } 
} 

当我运行应用程序时,我得到了一个空白屏幕。

为什么zoomIn按钮不可见?

+0

的一件事是,在的MainView,超(上下文)的构造应该是超(背景,如) – nlt 2013-05-07 04:50:11

回答

0

这可能不是你正在寻找的答案,但是如果你有MainView扩展LinearLayout而不是ViewGroup,它可以正常工作。

0

请您尝试一下..

公共类MainActivity扩展活动

{

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    LinearLayout linearLayout = (LinearLayout) findViewById(R.id.buttonLayout); 
    linearLayout.addView(new ZoomController(this)); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.activity_main, menu); 
    return true; 
} 

public class ZoomController extends LinearLayout { 
    private Button zoomIn; 

    public ZoomController(Context context) { 
     super(context); 
     zoomIn = new Button(context); 
     zoomIn.setText("+"); 

     setOrientation(1); 
     addView(zoomIn); 
    } 
} 

}