簡體   English   中英

基於LinearLayout創建自定義組件,以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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM