使用 java 文件或 xml 文件创建表格布局
Step1:(Step 1有两种方式跟随任何一种)
/*create tablelayout in java no need for create activity that can be handle in java file if u want xml file use or condition loop*/
TableLayout tableLayout=new TableLayout(this);
tableLayout.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT));
setContentView(tableLayout);
/*Follow java code only then add the activity in manifest file then Go to step 2*/
XML:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/table"
android:layout_width="match_parent"
android:layout_height="match_parent">
</TableLayout>
爪哇:
setContentView(R.layout.table_layout);
TableLayout tableLayout= (TableLayout) findViewById(R.id.table);
第2步:
int colors[]=getResources().getIntArray(R.array.value);
List<String> str=new ArrayList<String>();
Collections.addAll(str, getResources().getStringArray(R.array.arrayvalues));
Log.d(TAG,str.toString());
for(int i=0;i<str.size();i++){
TableRow row=new TableRow(this);
row.setId(101+i);
row.setBackgroundColor(Color.BLACK);
row.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT));
TextView text=new TextView(this);
text.setId(201+i);
text.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,TableRow.LayoutParams.WRAP_CONTENT));
text.setText(str.get(i));
text.setPadding(0,10,0,10);
text.setTextColor(colors[i]);
row.addView(text);
tableLayout.addView(row);
}
字符串.xml
<resources>
<string-array name="arrayvalues">
<item>Red</item>
<item>Orange</item>
<item>Yellow</item>
<item>Green</item>
<item>Blue</item>
<item>Indigo</item>
<item>Violet</item>
</string-array>
<integer-array name="value">
<item>@color/Red</item>
<item>@color/Orange</item>
<item>@color/Yellow</item>
<item>@color/Green</item>
<item>@color/Blue</item>
<item>@color/Indigo</item>
<item>@color/Violet</item>
</integer-array>
</resources>
颜色.xml
<resources>
<color name="Red">#FF0000</color>
<color name="Orange">#FF7F00</color>
<color name="Yellow">#FFFF00</color>
<color name="Green">#00FF00</color>
<color name="Blue">#0000FF</color>
<color name="Indigo">#4B0082</color>
<color name="Violet">#9400D3</color>
</resources>
输出:
-------------------------------------------------- - - - - - - - - - - - -结束 - - - - - - - - - - - - - ----------------------
仅用于从 string.xml 文件中获取数组(不要遵循它仅用于从字符串文件中获取数组)
ArrayList<String> str=new ArrayList<String>();
String[] val=getResources().getStringArray(R.array.value);
str.addAll(Arrays.asList(val));
Log.d(TAG,str.toString());