在我的 Android 项目中,我需要通过标签而不是 ID 在我的 Activity 中查找视图。(如果你问我为什么不简单地使用findViewById
,这不是我的偏好,而且描述起来很复杂,但目前我不能依赖R.id.
常量!)
到目前为止,为了在我的代码中找到视图,我已经设法使用这成功:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.index);
mainViewGroup = (ViewGroup)getWindow().getDecorView();
TextView indexCaption = (TextView) mainViewGroup.findViewWithTag("index_caption");
// Now I have my TextView and can use it without problem
}
但现在,问题是我在同一个活动中的自定义 ArrayAdapter:
class IconicAdapter extends ArrayAdapter<String> {
IconicAdapter() {
// How I can use Tag instead of R.layout.index_row_caption here?!!!
super(IndexActivity.this, R.layout.index_row, R.id.index_row_caption, arrayList);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
// Some customizations...
return (row);
}
}
index_row.xml
对于那个 IconicAdapter
:
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/content_bg" >
<TextView
android:id="@+id/index_row_caption"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="@+id/index_row_icon"
android:layout_toRightOf="@+id/index_row_search"
android:gravity="right"
android:tag="index_row_caption"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ImageView
android:id="@+id/index_row_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:tag="index_row_icon" />
<ImageView
android:id="@+id/index_row_search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:src="@drawable/index_row_search"
android:tag="index_row_search" />
如何避免R.id.index_row_caption
在构造函数中使用并将其替换为与其标签相关的内容?
编辑:最后,我已经完成了这段代码,并且效果很好:(在这方面帮助我的 pawelzieba 获得了学分和赏金)
class IconicAdapter extends ArrayAdapter<String> {
IconicAdapter() {
super(IndexActivity.this, R.layout.index_row, 0, arrayList);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater mInflater = IndexActivity.this.getLayoutInflater();
view = mInflater.inflate(R.layout.index_row, parent, false);
} else {
view = convertView;
}
//find views
TextView text = (TextView) view.findViewWithTag("index_row_caption");
//fill views with data
text.setText(arrayList.get(position));
return view;
}
}