How to inflate another xml on clicking a button

ぐ巨炮叔叔 提交于 2019-12-02 04:43:19
SBK

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);

            }
        });
    }
}

Try using v.findViewByID()..

Pass View v to callingMore()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!