我正在尝试将clickListener添加到动态添加的LinearLayout内的ImageButton中,这是另一个(包装器)LinearLayout的一部分:
打包机:
<LinearLayout
android:id="@+id/persons_wrapper"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
将LinearLayout动态添加到上面的包装器中:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:id="@+id/person_row"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<ImageButton
android:id="@+id/share_with_person"
android:src="@drawable/share_with"
android:layout_weight="0"
android:layout_marginTop="5dp"
android:layout_width="35dp"
android:layout_height="35dp"
android:scaleType="fitCenter"
android:layout_marginRight="5dp"
/>
<TextView
android:id="@+id/person_name"
android:textColor="@color/secondary_text_color"
android:hint="@string/person_name_hint"
android:layout_marginTop="@dimen/margin_between_form_elements"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/person_amount"
android:textColor="@color/secondary_text_color"
android:hint="10.20"
android:layout_marginTop="@dimen/margin_between_form_elements"
android:layout_weight="0"
android:layout_width="90dp"
android:layout_height="fill_parent" />
</LinearLayout>
用于在上面的布局中将clickListener添加到ImageButton的Java代码:
ViewGroup parentView = (ViewGroup) findViewById(R.id.persons_wrapper);
for (int i = 0; i < parentView.getChildCount(); i++) {
//get the parent's childview, which is the linear layout wrapped around the name and amount for a person
final View childView = parentView.getChildAt(i);
Log.i("for loop", "looping");
ImageButton shareWithPerson = (ImageButton) childView.findViewById(R.id.share_with_person);
shareWithPerson.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.i("clicked", "share");
shareTextWithChosenApp(childView);
}
});
shareWithPerson.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
Log.i("clicked", "long click");
return false;
}
});
}
没有错误或者没有错,但是点击ImageButton之后根本没有任何反应。
我检查过的事情:
parentView
不是null childView和shareWithPerson
不为null,是所需的视图提前致谢,
编辑:
shareTextWithChosenApp方法:
private void shareTextWithChosenApp(View personRow) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
TextView personAmount = (TextView) personRow.findViewById(R.id.person_amount);
String shareBody = personAmount.getText().toString();
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Rekening delen");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Delen met: "));
}