2014-02-23 22 views
0

我在.java文件中創建了一個LinearLayout對象,並試圖通過使用以下代碼將它與我的.xml layout連接起來,但它沒有響應。你能向我解釋爲什麼和這個代碼中有什麼錯誤?我已將.xml文件的LinearLayoutid命名爲「root」。將我的java佈局對象與android中的xml佈局鏈接

public class MainActivity extends Activity { 

    LinearLayout l; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     ImageView HelloWorldImageView = new ImageView(this); 
     TextView t=new TextView(this); 
     t.setText("hello"); 
     HelloWorldImageView.setImageResource(R.drawable.ic_launcher); 
     l=new LinearLayout(this); 
     l=(LinearLayout)findViewById(R.id.root); 
     l.addView(t); 
     l.addView(HelloWorldImageView); 
     setContentView(l); 
    } 
} 
+0

你有什麼問題?你爲什麼要初始化'l'兩次?另外,爲什麼你不把這些'View's放在你的xml中?那麼你不必用'new'來初始化它們。 – codeMagic

回答

0

首先摘你不需要newLinearLayout線。 findViewById()將返回一個實例化的版本。其他新產品View s也一樣。

其次 - 在撥打findViewById()之前,您想先做setContentView()。這樣,您設置了layout(通過傳遞它layoutid),Android將實例化您的layout中的所有View,並且您可以通過findViewById()獲取對它們的引用。

0

做到像這個 -

 setContentView(R.layout.yourxml); 
     ImageView HelloWorldImageView = new ImageView(this); 
     TextView t=new TextView(this); 
     t.setText("hello"); 
     HelloWorldImageView.setImageResource(R.drawable.ic_launcher); 
     l=(LinearLayout)findViewById(R.id.root); 
     l.addView(t); 
     l.addView(HelloWorldImageView); 

你必須設置XML文件中的setContentView(),其中有根線佈局在裏面。

+0

其實我正在嘗試不同的方法多數民衆贊成爲什麼這樣做。問題是,它停止工作,但現在,解決了,我明白了。感謝人們。 – user3342667

+0

所以,如果我的回答可以幫助你,那麼你可以將其標記爲已接受,所以它可以幫助其他人。 –