我在.java文件中創建了一個LinearLayout
對象,並試圖通過使用以下代碼將它與我的.xml layout
連接起來,但它沒有響應。你能向我解釋爲什麼和這個代碼中有什麼錯誤?我已將.xml文件的LinearLayout
的id
命名爲「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);
}
}
你有什麼問題?你爲什麼要初始化'l'兩次?另外,爲什麼你不把這些'View's放在你的xml中?那麼你不必用'new'來初始化它們。 – codeMagic