2012-11-10 44 views
1

我在表格佈局中添加了textview的動態行,並且還希望該textview的xy座標。爲此,我使用了view.getLocationOnScreen(loc)方法。如何獲取ANDROID中的表格佈局單元格的位置

但是隻顯示最後一個項目的座標,我想顯示所有項目的座標。

這是我的源代碼,請幫助我。

謝謝你。

public class MainActivity extends Activity { 
TextView tv1, tv2; 
TableRow row; 
TextView txt; 
TableLayout tl; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    tl = (TableLayout) findViewById(R.id.tableLayout1); 
    for (int i = 0; i <= 15; i++) { 
     row = new TableRow(this); 
     txt = new TextView(this); 

     tl.addView(row); 
     row.addView(txt); 
     readLocation(); 
    } 
} 

@Override 
public void onWindowFocusChanged(boolean hasFocus) { 
    // TODO Auto-generated method stub 
    super.onWindowFocusChanged(hasFocus); 
    readLocation(); 
} 

private void readLocation() { 
    int[] locationOnScreen = new int[2]; 
    txt.getLocationOnScreen(locationOnScreen); 
    txt.setText(locationOnScreen[0] + " : " + locationOnScreen[1]); 
} 

} 

和我下面的XML

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="vertical" > 

<ScrollView 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 

    <TableLayout 
     android:id="@+id/tableLayout1" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" > 
    </TableLayout> 
</ScrollView> 

回答

1

你不應該試圖讓那些座標onCreate方法以這種方式,因爲佈局的程序還沒有在這一點上完成。

這裏是你的代碼做一點修改的示範基地:

public class MainActivity extends Activity { 

ArrayList<TextView> txt = new ArrayList<TextView>(); 
TableLayout tl; 

Handler _h = new Handler(); 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    tl = (TableLayout) findViewById(R.id.tableLayout1); 
    for (Integer i = 0; i <= 15; i++) { 
     TableRow therow = new TableRow(this); 
     TextView thetxt = new TextView(this); 

     therow.addView(thetxt); 
     tl.addView(therow); 

     txt.add(thetxt); 

     thetxt.setText("stub"); 
    } 

    tl.requestLayout(); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.activity_main, menu); 
    return true; 
} 

@Override 
protected void onResume() { 
    super.onResume(); 
    _h.postDelayed(new Runnable() { 

     @Override 
     public void run() { 

      for (Integer i = 0; i <= 15; i++) { 

       TextView thetxt = txt.get(i); 

       int[] locationOnScreen = new int[2]; 
       thetxt.getLocationOnScreen(locationOnScreen); 
       thetxt.setText(locationOnScreen[0] + " : " + locationOnScreen[1]); 
      }   


     } 
    }, 1000); 

} 

}

的關鍵點是在onResume,讓系統能夠正確定位所有視圖postDelayed

+0

謝謝......它爲我工作.... –

相關問題