0

我想实现一个HUD显示到我的中弹键盘。 HUD将包含成对的键/值。我需要编程创建一个TableLayout并在我的画布上绘制它。为了做到这一点,我重写keyboardview的onDraw()方法:Android - 动态TableLayout没有出现

@Override 
public void onDraw(Canvas canvas) { // In the custom MyKeyboardView class 
    MyHUD hud = new MyHUD(getContext()); 
    super.onDraw(canvas); 
    hud.tl.draw(canvas); //tl being the TableLayout to draw 
} 

MyHUD类:

public class MyHUD { 

    public TableLayout tl; 
    private MyData mData; 

    public MyHUD(Context context) { 

     TableRow.LayoutParams trParams = new TableRow.LayoutParams(
     TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT); 
     TableLayout.LayoutParams tlParams = new TableLayout.LayoutParams(
     TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT); 

     tl = new TableLayout(context); 
     tl.setLayoutParams(tlParams); 

     for (int i = 0; i < 10; i++) { 

     TableRow tr = new TableRow(context); 
     tr.setId(100+i); 
     tr.setLayoutParams(trParams); 

     TextView charTV = new TextView(context); 
     charTV.setId(200+i); 
     charTV.setText("Hello " + i); 
     charTV.setTextColor(Color.RED); 
     //charTV.setLayoutParams(trParams); 
     tr.addView(charTV); 

     TextView keyTV = new TextView(context); 
     keyTV.setId(300+i); 
     keyTV.setText("world " + i); 
     keyTV.setTextColor(Color.CYAN); 
     //keyTV.setLayoutParams(trParams); 
     tr.addView(keyTV); 

     tl.addView(tr, tlParams); 
     }  
    } 
} 

(请注意,目前没有数据抓取,只是一个 “Hello World” 为测试目的)。 我已经注释掉了TextView的布局,就像在其他几篇文章中看到的那样,但这似乎不是问题所在。


替代选项:

而是通过一个构造instanciating的TableLayout的,我已经试过类似:

tl = (TableLayout) findViewById(R.id.my_hud); 

随着下面的XML:

<?xml version="1.0" encoding="utf-8"?> 
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:stretchColumns="0,1" 
     android:id="@+id/my_hud" > 
</TableLayout> 

的问题是findViewById方法对于我的自定义类是未定义的。

任何想法为什么它不能正确绘制TableLayout?

+0

嗡嗡声我只是想过:是否正确使用keyboardview的上下文来实现布局元素的实例化? –

回答

0

我没想到会是这样简单,但这里少了什么:

hud.tl.measure(canvas.getWidth(), canvas.getHeight()); 
    hud.tl.layout(0, 0, canvas.getWidth(), canvas.getHeight()); 

现在TableLayout正确绘制。成功。