80,351
社区成员
发帖
与我相关
我的任务
分享
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="动态添加按钮Demo"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="添加"
android:id="@+id/Button_Add"
android:onClick="e_View_Clicked"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/RelativeLayout_Test"
>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮一"
android:layout_alignParentRight="true"
android:id="@+id/Button_One"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮二"
android:id="@+id/Button_Two"
android:layout_toLeftOf="@id/Button_One"
android:layout_alignTop="@id/Button_One"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮三"
android:id="@+id/Button_Three"
android:layout_toLeftOf="@id/Button_Two"
android:layout_alignTop="@id/Button_One"
/>
</RelativeLayout>
</LinearLayout>
package com.test.demo.demo_addbuttons;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRelativeLayoutTest = (RelativeLayout)findViewById(R.id.RelativeLayout_Test);
}
public void e_View_Clicked(View view){
int iViewID=view.getId();
switch (iViewID){
case R.id.Button_Add:
//动态添加按钮
f_add();
break;
}
}
private void f_add(){
RelativeLayout.LayoutParams vParams=new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
vParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
Button vButtonOne=new Button(this);
vButtonOne.setLayoutParams(vParams);
vButtonOne.setText("按钮一");
mRelativeLayoutTest.addView(vButtonOne);
//按钮二,按钮三要怎么做?
}
RelativeLayout mRelativeLayoutTest;
}