公司最近的需求是在界面中添加一个表格,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>
看看效果图!不会做动图勉强看看!!