转载自http://www.tuicool.com/articles/NbaQBj
之前在看fragment的时候,看到有一个人在一篇博文的评论区中讲,相对于fragment他更喜欢使用addView,我没怎么用过addView,就找来看看,如上网址
看完之后自己也仿照着抄了抄
布局代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/ill"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<Button
android:id="@+id/btn_add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="添加按钮" />
</LinearLayout>
MainActivity.java代码:
package com.example.addviewdemo01;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
private LinearLayout ill;
private Button btn;
private TextView text;
private static int countId = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ill = (LinearLayout) findViewById(R.id.ill);
findViewById(R.id.btn_add).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (countId % 2 == 0) {
text = new TextView(MainActivity.this);
addText(countId, text, "------------------------" + "我是间隔线"+"------------------------", ill);
} else {
btn = new Button(MainActivity.this);
addButton(countId, btn, "按钮" + countId, ill);
}
countId++;
}
});
}
private void addButton(int Id, final Button name, String text,
final LinearLayout layout) {
name.setText(text);
name.setId(Id);
layout.addView(name);
findViewById(Id).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
layout.removeView(name);
}
});
}
private void addText(int Id, final TextView name, String text,
final LinearLayout layout) {
name.setText(text);
name.setId(Id);
layout.addView(name);
findViewById(Id).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
layout.removeView(name);
}
});
}
}
效果图:
也希望博友能安利我几篇这方面的能量高的博文,谢谢!!!