android 创建动态View
dynamic_view.xml
<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="@+id/ll_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
<Button
android:id="@+id/btn_click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/ll_layout"
android:layout_marginTop="10dp"
android:text="添加"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
Activity:
packagecom.example.jsapp;
importandroid.app.Activity;
importandroid.content.Context;
importandroid.os.Bundle;
importandroid.view.LayoutInflater;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
importandroid.widget.LinearLayout;
importandroid.widget.TextView;
publicclassDynamicActivityextendsActivity{
privateLinearLayoutllLayout;
privateButtonbtnClick;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.dynamic_view);
setView();
}
privatevoidsetView(){
llLayout=(LinearLayout)findViewById(R.id.ll_layout);
btnClick=(Button)findViewById(R.id.btn_click);
llLayout.setOrientation(LinearLayout.HORIZONTAL);
btnClick.setOnClickListener(newOnClickListener(){
intcount=0;
@Override
publicvoidonClick(Viewv){
LayoutInflaterinflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//第一个参数为xml文件中view的id,第二个参数为此view的父组件,可以为null,android会自动寻找它是否拥有父组件
Viewview=inflater.inflate(R.layout.item,null);
TextViewtvCaiLiao=(TextView)view.findViewById(R.id.tv_cai_liao);
TextViewtvShuLiang=(TextView)view.findViewById(R.id.tv_shu_liang);
tvCaiLiao.setText("芹菜"+count);
tvShuLiang.setText("50g"+count);
llLayout.setOrientation(LinearLayout.VERTICAL);
llLayout.addView(view);
count++;
}
});
}
}