How do I access the views inside the layout when I reuse it multiple times?

后端 未结 2 1738
孤街浪徒
孤街浪徒 2020-12-08 19:14

I have read the Android UI trick 2 on Android developers, which tells people how to include a layout in another layout file multiple times, and give these included layouts d

2条回答
  •  渐次进展
    2020-12-08 19:50

    I wanted to create TableRow layout and wanted to reuse it to my code in for loop. I was searching for the problem and at last found solution.

            TableLayout table = (TableLayout) findViewById(R.id.listTable);
            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            ImageButton[] button = new ImageButton[4];
            TableRow[] row = new TableRow[4];
    
            for(int i =0 ; i<4;i++){
    
                    row[i] = (TableRow) inflater.inflate(R.layout.list_row, null);
                    table.addView(row[i]);
                    button[i] = (ImageButton)row[i].findViewById(R.id.editBtn);
                    button[i].setOnClickListener(new OnClickListener() {
    
                        @Override
                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            Log.i(TAG,"Button Clicked");
                        }
                    });
    

    This way you can achieve the functionality of reusing the layout and also can access inner elements

提交回复
热议问题