如何访问android中TableRow中的子元素?

时间:2014-08-16 07:08:14

标签: android android-layout

我的布局文件的结构如下:

<TableRow>
    <LinearLayout >

       <LinearLayout >
          <IconTextView />            
       </LinearLayout>

       <TextView />

    </LinearLayout>

    <!-- The above linear layout is repeated 4 times in a table row -->
</TableRow>

由于某种原因,表格行中的所有元素都没有ID。那么如何访问每个IconTextView内的TextViewTableRow

我在TableRowgetChildCount()函数的帮助下访问每个getChildAt()内的每个子项(外部LinearLayout)。

现在,我希望以类似的方式访问子项中的不同元素(例如IconTextViewTextView

2 个答案:

答案 0 :(得分:0)

设置ID并使用它们来识别视图,因为您以编程方式创建视图,您应该能够轻松地为其分配ID。

解决方案是将IconTextViews id设置为1并将TextViews id设置为2,您可以通过在直接父容器上调用View.findViewById(int id)轻松地检索它们 - 在这种情况下每个TableRow。因此,要检索每个IconTextView,请调用currentTableRow.findViewById(1)。

最好使用getChildCount()和getChildAt()循环遍历TableRows。当然,您的视图层次结构中存在重复的ID,但如果您相对于TableRow调用findViewById(id),则不会出现问题。

答案 1 :(得分:-1)

你可以在xml中使用 机器人:ID = “@ + ID / diplay” 然后在主java文件中你应该写

public class Arithmatic2 extends ActionBarActivity {
 TextView display;
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_arithmatic2);

    display=(TextView) findViewById(R.id.diplay);
        }