2017-09-23 48 views
-3

我有一個ButtonMainActivity想要在按鈕單擊事件上添加另一個XML。如何在單個活動中使用多個XML文件?

請幫幫我。這將是一個很好的你。

+2

你到目前爲止嘗試過什麼? – mrid

+0

發佈你到目前爲止的工作 –

+0

我什麼也沒做,我只是不知道如何通過按鈕來獲得多個XML。 –

回答

2

只需做一件事在你的代碼中定義一個LayoutXML您要擺在運行時在XML,然後使該佈局的對象類和膨脹的另一個XML在此Layout對象任何形式的View

試試這個代碼膨脹另一個XML在運行時間:

LayoutInflater inflater = LayoutInflater.from(getApplicationContext()); 

// Put another XML name here with R.layout 
    View view = inflater.inflate(R.layout.**XML**, null); 

// Your Layout object 
    **layoutObject**.addView(view); 
1

MainActivity.java

public class MainActivity extends AppCompatActivity { 

Button button2; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    button2 = (Button)findViewById(R.id.button2); 

    button2.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      setContentView(R.layout.layout); 
     } 
    }); 
} 

@Override 
public void onBackPressed() 
{ 
    // Instead of setcontentview() i am restarting the activity. 
    Intent i = new Intent(getApplicationContext(),MainActivity.class); 
    startActivity(i); 
} 
} 

Layout.java

public class Layout extends Fragment{ 


public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

    View v = inflater.inflate(R.layout.layout, container, false); 

    return v; 
} 
} 

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?> 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/RL"> 

    <Button 
     android:text="Button" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_centerHorizontal="true" 
     android:id="@+id/button2" /> 


</RelativeLayout> 

layout.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:background="#fbb"> 

<TextView 
    android:text="TextView" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/textView" 
    android:layout_centerVertical="true" 
    android:layout_centerHorizontal="true" 
    /> 
</RelativeLayout> 

注:創建其它XML片段Java類(在這種情況下layout.xml)是必要的,否則的setContentView(R.layout.YourLayout)將無法正常工作和應用程序會崩潰立即打開時。

+0

如果我想回到activity_main XML按回按鈕然後我需要做什麼? –

+0

看看編輯的MainActivity.java –

+0

是的,它的工作,但有問題。當它通過activity_main返回時,後退按鈕和我們創建的按鈕不再起作用。 –

相關問題