本文主要是介绍Android动态生成Relativelayout + button,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
要求:输入每行btn个数,输出一共200个btn。
直接上代码,参考了csdn上的博客 android:动态创建多个按钮
不需要任何XML文件即可显示出btn。
import androidx.appcompat.app.AppCompatActivity;import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;public class MainActivity extends AppCompatActivity {private EditText editNum;private Button addbtn;DisplayMetrics dm = new DisplayMetrics();//MainActivity().getMetrics(dm);int width = dm.widthPixels;int height = dm.heightPixels;Button[] btt = new Button[205];//RelativeLayout layout = new RelativeLayout(this);@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);final RelativeLayout rlayout = new RelativeLayout(this);RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT );RelativeLayout.LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);layoutParams2.addRule(RelativeLayout.ALIGN_PARENT_LEFT );rlayout.setLayoutParams(layoutParams);editNum = new EditText(MainActivity.this);editNum.setHint("请输入个数");editNum.setLayoutParams(layoutParams2);addbtn = new Button(MainActivity.this);addbtn.setWidth(100);addbtn.setHeight(40);addbtn.setText("add");addbtn.setLayoutParams(layoutParams);rlayout.addView(editNum);rlayout.addView(addbtn);addbtn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {int linenum = Integer.parseInt(editNum.getText().toString());DisplayMetrics dm = new DisplayMetrics();getWindowManager().getDefaultDisplay().getMetrics(dm);int width = dm.widthPixels;int height = dm.heightPixels;Button Btn[] = new Button[205];int j = -1;for (int i=0; i<200; i++) {Btn[i]=new Button(MainActivity.this);Btn[i].setId(i);Btn[i].setText("B"+i);RelativeLayout.LayoutParams btParams = new RelativeLayout.LayoutParams ((width-50)/linenum,120);if (i%linenum == 0) {j++;}btParams.leftMargin = 10+ ((width-50)/linenum+10)*(i%linenum);btParams.topMargin = 120 + 120*j; rlayout.addView(Btn[i],btParams); }}});setContentView(rlayout);}}
运行效果
参考博文:https://blog.csdn.net/lihengfang/article/details/8204238
这篇关于Android动态生成Relativelayout + button的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!