2012-11-21 34 views
1

我真的在嘗試一些非常簡單的事情,不過android和java讓我的生活變得不容易。這個想法是滾動到表格佈局中的指定的孩子。tablelayout getchildat滾動到那個孩子

我使用的是Layoutinflater的條目添加到像表佈局如下:

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

    LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View itemView = inflater.inflate(R.layout.element_news, null); 

    TextView firstname = (TextView) itemView.findViewById(R.id.tvname); 
    firstname.setText(FN + " " + iLN); 

    TextView date = (TextView) itemView.findViewById(R.id.tvdate); 
    date.setText(newPD); 

    TextView post = (TextView) itemView.findViewById(R.id.tvpost); 
    post.setText(c.getString(iP)); 
    post.setFocusable(true); 

    tl.addView(itemView, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT)); 

我試圖用getChildAt()爲tablelayout和我得到這個孩子,但是當我使用孩子返回一切爲「0」的孩子。

例如代碼:

LinearLayout row = (LinearLayout) tl.getChildAt(1); 
TextView tv = (TextView) row.getChildAt(1); 
tv.requestFocus(); 
Log.w("news", Integer.toString(tv.getHeight())); 

對於TextView的高度則返回「0」儘管它已經包含多個線和requestFocus()方法也不起作用。

那麼如何滾動到表格佈局中的孩子?

在此先感謝您的幫助。

回答

1

該代碼示例不起作用,因爲您可能在onCreate方法中使用它,並且此時UI尚未繪製,因此視圖沒有任何尺寸。如果是這樣的話,你可以簡單地張貼在您的視圖之一Runnable推遲了一下尺寸聚集,直到onCreate方法是這樣後:

// post the Runnable 
tl.post(new Runnable() { 

     @Override 
     public void run() { 
      LinearLayout row = (LinearLayout) tl.getChildAt(1); 
          // get the top position relative to the parent 
      int top = tr.getTop(); 
          // scroll to that top position the wrapping ScrollView 
      sv.scrollTo(0, top);     
     } 

    }); 

有一些奇怪的代碼(從我的觀點查看),如果上面的代碼不起作用,你應該發佈更多關於你的佈局文件和使用場景的細節。

+0

非常感謝它爲我工作。 – Max

+1

只要22小時過去了,我就會給你+50的聲望點。 – Max

相關問題