android 動態實現表格佈局
阿新 • • 發佈:2019-01-31
公司最近的需求是在介面中新增一個表格,TabLayout 好久沒用過了~趕緊上網找了下度娘!發現有很多帖子但是都不能滿足我的需求.結合網上的自己在總結了一下(本文只限於個人學習).具體程式碼如下~~
public class MainActivity extends AppCompatActivity {
private final int H = ViewGroup.LayoutParams.WRAP_CONTENT; private final int W = ViewGroup.LayoutParams.MATCH_PARENT; private TableLayout tab; private ArrayList<String> tabCol = new ArrayList<>(); private ArrayList<String> tabH = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); for (int i = 1;i<=10;i++){ tabCol.add("第 ("+i+") 列"); tabH.add("第 ("+i+") 行"); } tab = (TableLayout) findViewById(R.id.tab_01); //控制行數 for (int row = 0; row < tabH.size(); row++) { TableRow tabRow = new TableRow(this); //控制列數 for (int col = 0 ; col<tabCol.size(); col++){ TextView tv = new TextView(this); tv.setText(tabCol.get(col)+tabH.get(row)); tv.setGravity(Gravity.CENTER); tv.setBackgroundResource(R.drawable.tab_bg); tabRow.addView(tv); } tab.addView(tabRow,new TableLayout.LayoutParams(W,H)); } }
}
佈局檔案就很LOW了:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableLayout
android:id="@+id/tab_01"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</HorizontalScrollView>
</LinearLayout >
看看效果圖!不會做動圖勉強看看!!