2010-02-14 48 views
0

我對Android開發還很陌生,而且我一直無法找到任何有關如何執行此操作的示例。在視圖擴展類中創建佈局

在我的Activity中,我使用「setContextView(new myViewClass)」來指定View-extended類作爲要加載的類。在加載視圖方面,一切正常,我根據許多條件創建各種元素(LinearLayouts,按鈕等)。不幸的是,我無法獲得任何這些元素實際出現在屏幕上。

我想我的問題是對視圖更好的理解。我見過的所有示例都關注將xml文件設置爲基本視圖,然後在代碼中對其進行更改。有沒有其他的辦法呢?

謝謝。

這是我一直在努力工作的一個示例代碼。還有其他的事情正在進行,但這是相關的信息。對於程序上下文,這個類是證實與setContextView(new createView(this))

public createView(Context c){ 
    super(c); 

    // Create a simple layout 
    LinearLayout layout = new LinearLayout(top.getContext()); 
    layout.setOrientation(LinearLayout.VERTICAL); 


    // Create test text 
    TextView mTestText = new TextView(c); 
    mTestText.setText("This is a test"); 

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.FILL_PARENT, 
      LinearLayout.LayoutParams.WRAP_CONTENT); 
    lp.setMargins(10, 10, 10, 10); 
    layout.addView(mTestText, lp); 
} 

回答

1

我認爲這個問題是你不增加布局,以你的CreateView的。但是,查看類沒有添加方法(請參閱http://developer.android.com/reference/android/view/View.html)。

由於的LinearLayout是您擴展視圖的基本視圖,可以擴展的LinearLayout,而不是和的TextView添加到您的擴展類。如果你這樣做,你的CreateView類可能看起來像這樣:

/** 
* Since the LinearLayout is the base layout, we'll extend it. 
*/ 
public class CreateView extends LinearLayout { 
    public CreateView(Context context) { 
     super(context); 
     setOrientation(LinearLayout.VERTICAL); 

     TextView mTestText = new TextView(context); 
     mTestText.setText("This is a test"); 

     LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
       LinearLayout.LayoutParams.FILL_PARENT, 
       LinearLayout.LayoutParams.WRAP_CONTENT); 
     lp.setMargins(10, 10, 10, 10); 
     addView(mTestText, lp); 
    } 
} 
+0

謝謝。但是現在我有了這個佈局,我該如何讓它出現在屏幕上呢?我的感覺是,在我的課堂上創建的視圖沒有被附加到屏幕上。我是否需要退貨,使用充氣器等? – duanemat 2010-02-15 01:01:22

+0

將視圖添加到屏幕上的另一個視圖或將其設置爲內容視圖。在您的活動中使用** setContentView **將其設置爲主視圖。如果你需要一個小例子,我已經在我的回答中爲班級做了一些小測試:http://www.box.net/shared/j9x3076702 – Klarth 2010-02-15 10:49:52