添加布局我想知道如何創建方法將linearlayout添加到其他佈局。我想創建一個方法,當我在活動中使用此方法時,此方法在我的活動佈局頂部添加線性佈局。我怎樣才能做到這一點?在方法android
編輯: 我做這樣的事情:
public class SecondActivity extends Activity {
LinearLayout layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
layout = (LinearLayout) findViewById(R.id.lay);
Button next = (Button) findViewById(R.id.nextActivity);
layout.addView(addNewLinearLayout(getApplicationContext()));
next.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
startActivity(intent);
}
});
}
private View addNewLinearLayout(Context context) {
LinearLayout linearLayout = new LinearLayout(context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
linearLayout.setLayoutParams(params);
linearLayout.setBackgroundColor(getResources().getColor(R.color.black));
// Do something else here on your linear layout or to customize your linear layout
return linearLayout;
}
}
,這是XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/lay"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/nextActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_marginTop="100dp"
/>
</LinearLayout>
,但我的佈局並沒有改變自己的顏色。爲什麼?
你想要達到什麼目的,爲什麼不可能只是創建一個合適的XML佈局?你可以簡單地添加視圖view.AddView() –
創建一個LinearLayout的新對象,並使用addView方法的LinearLayout的父節點 – DevfaR
我想有方法,因爲我想在其他活動中使用它,所以我想使用全局方法將此視圖添加到每個佈局 – user1302569