我仍然是新的android编程,我想做的是,我想创建5x5尺寸的TableLayout。我知道这可以通过使用gridviewbaseadapter使用充气服务来完成。但对于这一个,我尝试使用表格布局应用。下面是代码。我创建了一个新的TableLayout实例和一个新的Table row实例。在每个表行上,我创建了5 TextView的实例。但是一旦我打开模拟器或在我的手机中,没有TableRow创建,它只是空的空白表布局。也没有抛出异常。
GridView navIcon = (GridView) findViewById(R.id.content);navIcon。setAdapter(新ImageAdapter ());
navIcon.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View v, int position,long id) {
// TODO Auto-generated method stub
if (position==0){
try{
TableLayout calgrid = (TableLayout) findViewById(R.id.gridtable);
Context ctxt = v.getContext();
TextView[] tView = new TextView[25];
calgrid = new TableLayout(ctxt);
int dip = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,(float) 1, getResources().getDisplayMetrics());
int counter=1;
TableRow[] tr = new TableRow[5];
for(int j=0;j<5;j++){
tr[j] = new TableRow(ctxt);
for(int i=0;i<5;i++){
tView[i] = new TextView(ctxt);
tView[i].setText(String.valueOf(counter));
tView[i].setTextSize(15);
counter+=1;
tView[i].setWidth(50 * dip);
tView[i].setPadding(20*dip, 0, 0, 0);
tView[i].setTextColor(Color.rgb( 100, 200, 200));
Toast.makeText(getApplicationContext(), "tView["+i+"] value " + String.valueOf(tView[i].getText()), Toast.LENGTH_SHORT).show();
tr[j].addView(tView[i], 50, 50);
}
calgrid.addView(tr[j]);
}
}catch(Exception e){
Log.e("MainActivity", "Error in activity", e);
Toast.makeText(getApplicationContext(),e.getClass().getName() + " " + e.getMessage(),Toast.LENGTH_LONG).show();
}
}
}
});
首先,做calgrid = (TableLayout) findViewById(R.id.gridtable);
和calgrid = new TableLayout(ctxt);
是错误的,这基本上是说找到这个视图,现在将这个变量分配给完全不同的东西。删除第二条语句,它将从xml中加载表,这是你想要的。
第二,我认为为自己简化事情是个好主意,因为这里有很多事情要做。而不是在onClick
侦听器中完成所有这些工作,而是在onCreate
方法本身中完成。此外,你似乎正在使用GridView的上下文,这似乎很奇怪。也许如果你张贴你的xml布局文件,它可以帮助解释你正在尝试做什么?
还有一个问题,索引在TextViews数组,因为tView[i]
只会分配项目最多5,但数组包含25个项目。尝试使用tView[(j*5)+i]
代替。我不认为这是造成你的问题,但要确保你正确分配你的项目。
这是一个关于如何按照你想要的方式做某事的例子
setContentView(R.layout.grid);
TableLayout tl = (TableLayout) findViewById(R.id.gridtable);
for (int j = 0; j < 5; j++) {
TableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
for (int i = 0; i < 5; i++) {
TextView tView = new TextView(this);
tView.setText("TEXT" + String.valueOf((j * 5) + i + 1));
tView.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tr.addView(tView);
}
tl.addView(tr, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}
和grid.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridtable"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</TableLayout>
一旦你让它在活动本身工作,你可以试着把它放在一个监听器附加到GridView。希望这对你有帮助!