2012-02-16 2 views
0

Я кодирую шахматную доску. Для макета я включаю несколько «объединенных» макетов. Я просто хотел бы получить доступ к «объединенным» компонентам из кода действия, чтобы изменить некоторые их свойства (imageView background_color, imageView путь к изображению ...).Android API 3: доступ к компонентам из объединенного макета

Редактирование: например, я хочу передать идентификатор строки (R.id.row_1) и инициализировать все компоненты из этого идентификатора строки с циклом for: 8 ячеек присваиваются каждому другому цвету фона.

@Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     initializeComponents(R.id.row_2); 
    } 

public initializeComponents(int id){ 
     /* inflates the given layout child components 
     * and set their properties 
     */ 
} 

Вот мой main.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" >  
<include layout="@layout/board"/> 
</LinearLayout> 

Вот мой board.xml

<?xml version="1.0" encoding="utf-8"?> 
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"> 
<include android:id="@+id/row_8" layout="@layout/board_line"/> 
<include android:id="@+id/row_7" layout="@layout/board_line"/> 
<include android:id="@+id/row_6" layout="@layout/board_line"/> 
<include android:id="@+id/row_5" layout="@layout/board_line"/> 
<include android:id="@+id/row_4" layout="@layout/board_line"/> 
<include android:id="@+id/row_3" layout="@layout/board_line"/> 
<include android:id="@+id/row_2" layout="@layout/board_line"/> 
<include android:id="@+id/row_1" layout="@layout/board_line"/> 

</TableLayout> 

Вот мой board_line.xml:

<?xml version="1.0" encoding="utf-8"?> 
<merge xmlns:android="http://schemas.android.com/apk/res/android"> 

<TableRow 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
> 
<ImageView 
     android:id="@+id/a" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:minWidth="@dimen/cell_dimension" 
     android:minHeight="@dimen/cell_dimension" 
     android:maxWidth="@dimen/cell_dimension" 
     android:maxHeight="@dimen/cell_dimension" 
    /> 
    <ImageView 
     android:id="@+id/b" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:minWidth="@dimen/cell_dimension" 
     android:minHeight="@dimen/cell_dimension" 
     android:maxWidth="@dimen/cell_dimension" 
     android:maxHeight="@dimen/cell_dimension" 
    /> 
    <ImageView 
     android:id="@+id/c" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:minWidth="@dimen/cell_dimension" 
     android:minHeight="@dimen/cell_dimension" 
     android:maxWidth="@dimen/cell_dimension" 
     android:maxHeight="@dimen/cell_dimension" 
    /> 
    <ImageView 
     android:id="@+id/d" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:minWidth="@dimen/cell_dimension" 
     android:minHeight="@dimen/cell_dimension" 
     android:maxWidth="@dimen/cell_dimension" 
     android:maxHeight="@dimen/cell_dimension" 
    /> 
    <ImageView 
     android:id="@+id/e" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:minWidth="@dimen/cell_dimension" 
     android:minHeight="@dimen/cell_dimension" 
     android:maxWidth="@dimen/cell_dimension" 
     android:maxHeight="@dimen/cell_dimension" 
    /> 
    <ImageView 
     android:id="@+id/f" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:minWidth="@dimen/cell_dimension" 
     android:minHeight="@dimen/cell_dimension" 
     android:maxWidth="@dimen/cell_dimension" 
     android:maxHeight="@dimen/cell_dimension" 
    /> 
    <ImageView 
     android:id="@+id/g" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:minWidth="@dimen/cell_dimension" 
     android:minHeight="@dimen/cell_dimension" 
     android:maxWidth="@dimen/cell_dimension" 
     android:maxHeight="@dimen/cell_dimension" 
    /> 
    <ImageView 
     android:id="@+id/h" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:minWidth="@dimen/cell_dimension" 
     android:minHeight="@dimen/cell_dimension" 
     android:maxWidth="@dimen/cell_dimension" 
     android:maxHeight="@dimen/cell_dimension" 
    /> 
</TableRow> 

Заранее благодарим за помощь.

+0

вы могли бы попробовать это так: 'findViewById (R.id. row_3) .findViewById (R.id.b) ' – zapl

+0

Спасибо. Но знаете ли вы, как я могу инициализировать все компоненты линии (R.id.row_2), не указывая вручную каждый дочерний компонент, но с циклом for/while? Заранее спасибо. – loloof64

ответ

0

Вы можете использовать LayoutInflater (или создавать Views полностью программно) и объединить все это с вашими потребностями. В следующем примере должна быть создана некоторая случайная цветная доска размером 5x5. Поскольку установка LayoutParams в коде является уродливой, я бы установил их в xml и Inflate layout.

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); 
    LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.main, null); 
    TableLayout tl = (TableLayout) ll.findViewById(R.id.tableLayout); 
    for (int j = 0; j < 5; j++) { 
     TableRow tr = (TableRow) inflater.inflate(R.layout.table_row, null); 
     for (int i = 0; i < 5; i++) { 
      ImageView iv = (ImageView) inflater.inflate(R.layout.image_view, null); 
      iv.setBackgroundColor(new Random().nextInt()); 
      tr.addView(iv); 
     } 
     tl.addView(tr); 
    } 
    setContentView(ll); 
} 

main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 
    <TableLayout 
     android:id="@+id/tableLayout" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" > 
    </TableLayout> 
</LinearLayout> 

table_row.xml

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

image_view.xml

just one of those you defined in board_line.xml: 
+0

Thnak вам очень нравится :) Я согласен, что это уродливый способ сделать по коду: но это потому, что я хочу сделать ChessBoard, и я все еще ищу лучшее графическое решение: полный код путем переопределения View или code and layout , (Я также хочу сделать «перетаскивание»: к сожалению, недоступно, как на api 3) – loloof64

Смежные вопросы