游戏得有活动的场景:代码中生成多行多列的LinearLayout布局
生活随笔
收集整理的這篇文章主要介紹了
游戏得有活动的场景:代码中生成多行多列的LinearLayout布局
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
既然是江湖,總得有一些可以到處跑的地兒。
咱是新手,那就排的簡單點,排個幾行幾列的就完事了。至于到底排個幾行幾列的,這個倒也說不準。
得,那就不能直接在layout/xml里面直接畫了。咋辦?也好辦,在activity里面通過代碼生成布局就可以了。
activity_scene_fight.xml 如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><LinearLayoutandroid:id="@+id/layout_scene"android:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="vertical"android:layout_gravity="center_horizontal"/><TextViewandroid:id="@+id/t_fight_log"android:layout_width="match_parent"android:layout_height="wrap_content" /></LinearLayout>在activity中添加了一個子布局linearlayout:layout_scene和一個textview。layout_scene中將用于展示接下來由代碼生成的各種場景的控件。
首先,得能生成單獨一行的場景:
/*** @param clomuns 單行顯示的場景數(shù)* @return 返回單行顯示的LinearLayout*/ private LinearLayout rowsLayout(int clomuns){LinearLayout rl= new LinearLayout(this);//設置LayoutParamsLayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);//設置為水平布局rl.setOrientation(LinearLayout.HORIZONTAL);rl.setLayoutParams(lp);//循環(huán)添加場景buttonfor (int j = 0; j < clomuns; j++) {Button b_scene = new Button(this);//設置場景按鈕的名稱b_scene.setText("場景"+j);//綁定點擊事件b_scene.setOnClickListener(clickListener);//添加到創(chuàng)建的線性布局中rl.addView(b_scene);}//添加到顯示的父線性布局中return rl; }/*** 點擊事件*/ private OnClickListener clickListener = new OnClickListener() {@Overridepublic void onClick(View v) {t_fight_log.append("你來到了"+((TextView)v).getText()+"\n");} };?下一步,生成多行的場景控件,代碼如下:
/*** @param sceneNums活動場景數(shù)量* @return 返回自定義的場景布局*/private LinearLayout sceneLayout(int sceneNums,int colnum ){LinearLayout sly=new LinearLayout(this);LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);//設置為垂直布局sly.setOrientation(LinearLayout.VERTICAL);sly.setLayoutParams(lp);int rows=sceneNums/colnum;int surplus=sceneNums%colnum;if (surplus==0) {//如果能夠被整除for (int i = 0; i < rows; i++) {sly.addView(rowsLayout(colnum));}}else{//如果不能夠被整除int i;for ( i=0 ; i < rows; i++) {sly.addView(rowsLayout(colnum));}//創(chuàng)建最后剩下的,不足一行的布局sly.addView(rowsLayout(surplus));}return sly;}?FightSceneActivity.java代碼如下:
protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_scene_fight);//獲取場景列表,生成頁面各元素fightSceneLayout=(LinearLayout)this.findViewById(R.id.layout_scene);fightSceneLayout.addView(sceneLayout(11,4));t_fight_log=(TextView) findViewById(R.id.t_fight_log); }最終效果如下:
?
轉載于:https://www.cnblogs.com/zzqm-gamelife/p/10254466.html
總結
以上是生活随笔為你收集整理的游戏得有活动的场景:代码中生成多行多列的LinearLayout布局的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 「NOI2017」泳池
- 下一篇: WPF入门(四)-线形区域Path内容填