2013-12-11 50 views
0

我正在使用擴展視圖來設置活動的內容。發生了什麼,它顯示空白活動。而不是設置文本。setContentView通過使用擴展視圖類

public class ThreadCheck extends Activity{ 
     MyView view; 
     /* (non-Javadoc) 
     * @see android.app.Activity#onCreate(android.os.Bundle) 
     */ 
     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      // TODO Auto-generated method stub 
      super.onCreate(savedInstanceState); 
      Context ctx = getApplicationContext(); 
      view=new MyView(ctx); 
      setContentView(view); 
     } 
    } 

public class MyView extends View{ 
      TextView tvThread; 
      public MyView(Context context) { 
       super(context); 
       tvThread=new TextView(context); 
       tvThread.setText("Hello This Is Myview"); 
       // TODO Auto-generated constructor stub 
      } 

     } 

回答

2

更改此

view=new MyView(ctx); 

view=new MyView(ThreadCheck.this); 

,並切換到

public class MyView extends TextView{ 

    public MyView(Context context) { 
     super(context); 
     this.setText("Hello This Is Myview"); 
    } 

} 

編輯:在評論中的問題。您需要添加視圖的ViewGroup。

public class MyView extends RelativeLayout{ 

     public MyView(Context context) { 
      super(context); 


      RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
      this.setLayoutParams(layoutParams); 

      RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 

      TextView tv = new TextView(context); 
      tv.setText("hello"); 
      tv.setId(1); 

      Button b = new Button(context); 
      params1.addRule(RelativeLayout.BELOW, tv.getId()); 
      b.setText("Hi"); 
      b.setId(2); 

      this.addView(tv); 
      this.addView(b, params1); 

     } 
    } 
+1

或者,您可以使用'addView(view)'將您的自定義視圖添加到現有的佈局。 – NitroNbg

+0

感謝它解決了我的一半問題..我正在尋找的是有一個類來設置活動的佈局,而不是使用R.layout.xml。在該類我可以有按鈕textview等..這個特殊的解決方案只添加textview ...我的想法是有一個觀點,而不是像添加按鈕,文本,編輯等不同的東西...我不知道我做對了。 – PraveenPandey

+0

@PraveenPandey你需要有一個自定義的視圖。這是一個不同的問題。請問一個新問題。每個帖子一個問題,請。閱讀由Reto Meier撰寫的專業Android開發書。 – Raghunandan