How to inflate another xml on clicking a button

前端 未结 2 2030
北恋
北恋 2021-01-25 01:45

I have one Activity in that there are no Buttons but I have coded it in such a way that another Activity comes, now in this second A

相关标签:
2条回答
  • 2021-01-25 02:34

    I tried this code..hope helps to you..

    1.layout_existed.xml

      <?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>   
    

    2.layout_toinfliate.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="You inflated me..i added to u r layout"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      />
    </LinearLayout>
    

    3.LayoutInflateDemo.java

      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);
                    layoutToAdd.addView(view);
    
                }
            });
        }
    }
    
    0 讨论(0)
  • 2021-01-25 02:36

    Try using v.findViewByID()..

    Pass View v to callingMore()

    0 讨论(0)
提交回复
热议问题