我有一个自定义的android对话框,它有几个textViews。每个textview显示不同的文本。目的是当用户点击文本视图时,应关闭对话框并将该textview的textColor返回给父文件。
这是我的对话框布局。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff000000">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="White"
android:id="@+id/textView_white"
android:layout_gravity="center_horizontal"
android:textSize="30dp"
android:textIsSelectable="true"
android:clickable="true"
android:gravity="center"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:textColor="#fffffbfd" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Black"
android:id="@+id/textView_black"
android:layout_gravity="center_horizontal"
android:textSize="30dp"
android:textIsSelectable="true"
android:clickable="true"
android:gravity="center"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:textColor="#ffffffff"
android:password="false"
android:background="#ff000000" />
</LinearLayout>
我从父活动开始以这种方式启动对话框:
final Context context = MyWidgetConfigureActivity.this;
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.color_chooser);
dialog.setTitle("Choose Text Color");
dialog.show();
我想在对话框中的每个textView中添加相同的onClickListener。如何实现这一目标?对话框中有20多个textView,我不想手动为每个textViews添加onClickListener?还有更好的方法吗?
答案 0 :(得分:1)
我有两种方法,首先我会为每个TextView设置一个id,然后使用方法dialog.findViewById(id)
来获取每个TextView,并设置一个onClickListener,但我认为这种方式很痛苦。所以第二种方法是:首先给对话框布局根视图一个id,就像这样
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/dialog_root"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff000000">
然后java代码是:
LinearLayout rootLayout = (LinearLayout) dialog.findViewById(R.id.dialog_root);
for (int i = 0; i < rootLayout.getChildCount(); i++) {
TextView tv = (TextView) rootLayout.getChildAt(i);
tv.setOnClickListener(this);
}
... onClick方法是这样的。
@Override
public void onClick(View v) {
int color = ((TextView) v).getCurrentTextColor();
// TODO ...
}
答案 1 :(得分:0)
我建议改变你的做法。如果你有20多个TextViews可能看起来一样,为什么不使用ListView?看看here。
答案 2 :(得分:0)
OnClickListener click = new OnClickListener() {
@Override
public void onClick(View arg0) {
Toast.makeText(this,"You can use", Toast.LENGTH_LONG).show();
}
};
TextView t1 = (TextView)findViewById(id);
TextView t2 = (TextView)findViewById(id);
TextView t3 = (TextView)findViewById(id);
t1.setOnClickListener(click);
t2.setOnClickListener(click);
t3.setOnClickListener(click);