如何检索以编程方式定义的视图的引用

时间:2013-05-09 18:18:57

标签: android android-view android-tablelayout

理想情况下,可以通过findViewById方法检索View引用(在xml文件中)。 但是我有一个类我已经实例化所有视图

    public View Initialise(Context context){

    private Button mBoardButtons[][] = new Button[gridSize][gridSize];
       private TableRow rowArr[] = new TableRow[gridSize];
        private TextView mInfoTextView;
        private TextView mPlayer;
        private TextView mPlayerCount;
     TableLayout tableLayout1 = new TableLayout(context);
        TableLayout.LayoutParams tableParams1 = new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        tableParams1.topMargin = 0;
        tableLayout1.setLayoutParams(tableParams1);

        for ( int i =0 ; i < gridSize ; i++){
            rowArr[i] = new TableRow(context);
            TableRow.LayoutParams rowParams = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
            rowParams.gravity=Gravity.CENTER_HORIZONTAL;
            rowArr[i].setLayoutParams(rowParams);
            for(int j = 0; j < gridSize ; j++){
                mBoardButtons[i][j] = new Button(context);
                mBoardButtons[i][j].setText(Integer.toString(i)+","+Integer.toString(j));
                mBoardButtons[i][j].setTextSize(150/gridSize);
                mBoardButtons[i][j].setMaxHeight(450/gridSize);
                mBoardButtons[i][j].setMaxWidth(600/gridSize);
                rowArr[i].addView(mBoardButtons[i][j]);

            }
            tableLayout1.addView(rowArr[i]);
        }


        mInfoTextView = new TextView(context);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            params.topMargin = 5;
            params.gravity=Gravity.CENTER;
        mInfoTextView.setLayoutParams(params);
        mInfoTextView.setText("Info");
        mInfoTextView.setTextSize(25);
        tableLayout1.addView(mInfoTextView);


        TableLayout tableLayout2 = new TableLayout(context);
        TableLayout.LayoutParams tableParams2 = new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        tableLayout2.setLayoutParams(tableParams2);

        TableRow tableRow = new TableRow(context);

        mPlayer = new TextView(context);

        mPlayer.setText("Player: ");
        tableRow.addView(mPlayer);

        mPlayerCount = new TextView(context);

        mPlayerCount.setText(" ");

        tableRow.addView(mPlayerCount);


    return tableLayout1;

}

上面的代码是在特定的类中定义的(假设它代替了xml文件)

现在我如何获取Activity类中所有这些View元素的引用。

是否有类似于findViewById方法的方法来检索编程定义的视图引用?

1 个答案:

答案 0 :(得分:0)

使用new创建它们时,您有参考。把它保存在某处。

或者您可以使用setID(),以便稍后使用findViewByID。但是,当你现在可以保存它时,这很难做到。