カスタムしたレイアウトを繰り返し表示するには、inflateで取得して
getIdの中身に応じて処理を書くことで簡単に実装することが出来ます。
アクティビティでやることは、
メインアクティビティgetLayoutInflaterを使ってinflateに紐付けて
addViewするだけ。
forでidの違うボタンを作るには、addView毎にsetIdをしかけonClick内で
getTagを使って受け取ることで実装することができます。
配列で識別番号として使いたい時は、Integerで変換してあげること。
</pre> LinearLayout layout = activity.findViewById(R.id.layout); for(int i = 0; i < datas.length(); i++) { View view = activity.getLayoutInflater().inflate(R.layout.custom_list_layout, null); layout.addView(view); Button button = view.findViewById(R.id.detail); button.setTag(i); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int Index = Integer.parseInt(v.getTag().toString()); System.out.println(v.getTag()); } }); } <pre>
メインレイアウト部分
ここでは受け皿となるLinearLayoutを書くだけ。この中にカスタムレイアウトが
入ります。
</pre> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="#a3cfbd" android:orientation="vertical" android:gravity="center" tools:context="com.cpointlab.link.activity.MypageActivity" tools:ignore="RedundantNamespace,ScrollViewSize"> <LinearLayout android:id="@+id/layout" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginEnd="30dp" android:layout_marginStart="30dp" android:gravity="center" android:orientation="vertical"> </LinearLayout> </LinearLayout> <pre>
カスタムレイアウト。別にボタンでなくても試すなら何でも可。
</pre> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" xmlns:tools="http://schemas.android.com/tools" android:layout_marginStart="30dp" android:layout_marginEnd="30dp" android:orientation="vertical" android:background="#fff"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_marginStart="20dp" android:layout_marginEnd="20dp" android:layout_marginBottom="20dp" > <Button android:id="@+id/detail" android:layout_width="match_parent" android:layout_height="40dp" android:textColor="#fff" android:background="@drawable/shape_graybox" android:text="@string/detailBtn"/> </RelativeLayout> <View android:id="@+id/block" android:layout_width="fill_parent" android:layout_height="30dp" android:layout_marginTop="10dp" android:background="#a3cfbd" android:visibility="visible"/> </LinearLayout> <pre>
カスタムレイアウトはListViewでも回すことができますが、要素がデカくなる&
スクロールビューが生じるので、inflateを使ってレイアウトごとスクロール
できたほうがユーザーに優しいかも。