问题
How Can I bind the views present inside the Layout which is dynamically added to the parent view with ButterKnife.
I have a LinearLayout say container. And I have a custom layout which contains two buttons say this layout as childview In activity I added the childview successfully to the parent LinearLayout container.
This is how I did to inflate the custom view and added to the LinearLayout
bubbleView = inflater.inflate(R.layout.child, null);
systemChatLayoutContainer.addView(bubbleView);
Now I want to bind the Button views present inside the child layout and add perform some action when the buttons present inside the child layout.
This is child.xml which is dynamically added to the parent container on Button click.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/btnCreateAccount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/btn_selector_green"
android:gravity="center"
android:padding="@dimen/_13sdp"
android:text="Create an account"
android:textAppearance="@style/TextAppearance.AppCompat.Small"
android:textColor="@color/white" />
<TextView
android:id="@+id/btnJstCheckingRate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/btn_selector_blue"
android:gravity="center"
android:padding="@dimen/_13sdp"
android:text="I'm just checking rates"
android:textAppearance="@style/TextAppearance.AppCompat.Small"
android:textColor="@color/white" />
<TextView
android:id="@+id/btnIhaveAccount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/transparent_btn_selector"
android:gravity="center"
android:padding="@dimen/_20sdp"
android:text="I've got an account"
android:textAppearance="@style/TextAppearance.AppCompat.Small"
android:textColor="@color/white" />
</LinearLayout>
回答1:
You can bind views with ButterKnife present inside the child layout using ViewHolder
, so add the inner class BubbleViewHolder
class BubbleViewHolder {
BubbleViewHolder(View view) {
ButterKnife.bind(this, view);
}
@OnClick(R.id.button_id)
void onMyButtonClicked(Button myButton) {
// Do your stuff here
}
}
And construct the BubbleViewHolder
after inflating it
View bubbleView = inflater.inflate(R.layout.child, null);
new BubbleViewHolder(bubbleView);
systemChatLayoutContainer.addView(bubbleView);
来源:https://stackoverflow.com/questions/37744720/bind-with-butterknife-to-dynamically-added-view-in-android