[英]Create custom layout in XML to initialize in code or in another layout xml
[英]Create custom component based on LinearLayout, declaring layout in XML
我一直在嘗試在Android 1.5中創建一個復合控件(如此處所述 ),但是沒有找到任何關於如何使用XML文件指定布局的好例子。 我可以創建一個Activity,然后在構造函數中使用以下代碼加載xml文件:
setContentView(R.layout.main);
但是,我想在LinearLayout的子類中執行此操作 - 因此我可以在其他XML布局中使用此復合組件。 有點像:
public class CustomView extends LinearLayout
{
public CustomView(Context context) {
super(context);
setupView();
}
public CustomView(Context context, AttributeSet attrs)
{
super(context, attrs);
setupView();
}
public void setupView()
{
setContentView(R.layout.custom); // Not possible
}
}
這樣做的正確方法是什么?
您必須為自定義視圖“膨脹”布局:
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater.inflate(R.layout.custom, this, true);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.