android 创建动态View

dynamic_view.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns: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:

package com.example.jsapp;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class DynamicActivity extends Activity {

private LinearLayout llLayout;
private Button btnClick;

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

setView();
}

private void setView() {

llLayout = (LinearLayout) findViewById(R.id.ll_layout);
btnClick = (Button) findViewById(R.id.btn_click);
llLayout.setOrientation(LinearLayout.HORIZONTAL);
btnClick.setOnClickListener(new OnClickListener() {
int count = 0;
@Override
public void onClick(View v) {
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//第一个参数为xml文件中view的id,第二个参数为此view的父组件,可以为null,android会自动寻找它是否拥有父组件
View view = inflater.inflate(R.layout.item, null);
TextView tvCaiLiao = (TextView) view.findViewById(R.id.tv_cai_liao);
TextView tvShuLiang = (TextView) view.findViewById(R.id.tv_shu_liang);

tvCaiLiao.setText("芹菜" + count);
tvShuLiang.setText("50g" + count);
llLayout.setOrientation(LinearLayout.VERTICAL);
llLayout.addView(view);
count++;
}
});
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值