當我單擊按鈕時,我需要幫助更改Android Studio中Activity的佈局。Android Studio活動版面更改
但我不希望打開新的活動我想通過點擊按鈕,徹底改變佈局和設計上的當前活動。可能嗎 ?
當我單擊按鈕時,我需要幫助更改Android Studio中Activity的佈局。Android Studio活動版面更改
但我不希望打開新的活動我想通過點擊按鈕,徹底改變佈局和設計上的當前活動。可能嗎 ?
是的,它可以通過使用setContentView()
方法。但是,您必須確保您沒有使用當前版面上不可用的任何視圖(例如,按ID查看)。
您可以在button
點擊充氣另一個佈局:
public class LayoutInflateDemo extends Activity {
private LinearLayout layoutToAdd;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_existed);
layoutToAdd = (LinearLayout) findViewById(R.id.existedlayout);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
LayoutInflater inflater = LayoutInflater
.from(getApplicationContext());
View view = inflater.inflate(R.layout.layout_toinfliate, null);
//Add the inflated layout to your existing view
layoutToAdd.addView(view);
}
});
}
}
佈局膨脹XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/mytext"
android:text="Inflated layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
這是你的現有佈局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/existedlayout"
>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Clicck to inflate view"
android:id="@+id/button"
/>
</LinearLayout>
最好的辦法是片段和FragmentActivityhttps://developer.android.com/guide/components/fragments.html
如何在單個活動上有多個按鈕時在佈局之間切換? – user3102147
只是在多個按鈕點擊時膨脹不同的佈局...並將它們添加到您現有的佈局 – rafsanahmad007
我是全新的android工作室。對不起,愚蠢的問題。但充氣Xml我會創建或它已經在那裏,我會添加此代碼? – user3102147