我在 DialogFragment 中有一个自定义 SimpleCursorAdapter,我无法理解 setTag 和 getTag 的使用。从我的 LogCat 输出来看,我似乎在 LinearLayout 上设置标签并试图从 Button 中检索标签。如何定位正确的组件以访问 ClickListener 中的标签?
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
if (mCursor.moveToPosition(position)) {
ViewHolder holder;
final String label;
final int label_index = mCursor.getColumnIndex(ProfilesColumns.USERNAME);
label = mCursor.getString(label_index);
if (convertView == null) {
convertView = mInflater.inflate(layout, null);
holder = new ViewHolder();
holder.name = (Button) convertView.findViewById(R.id.title);
holder.logout = (Button) convertView.findViewById(R.id.logout);
holder.id = getItemId(position);
convertView.setTag(holder);
Log.d(DEBUG_TAG, "getView view " + convertView);//Returns LinearLayout
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.logout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
ViewHolder holder;
if (v == null) {
Log.d(DEBUG_TAG, "logout view null ");
} else {
Log.d(DEBUG_TAG, "logout view " + v);//Returns Button
holder = (ViewHolder) v.getTag();
if (holder == null) {
Log.d(DEBUG_TAG, "logout holder null ");
} else {
Log.d(DEBUG_TAG, "logout holder.id " + holder.id);
String[] argument = { "" + holder.id };
ContentResolver cr = getActivity().getContentResolver();
int count = cr.delete(ProfileProvider.URI_LOADEDPROFILETABLE, CommonDatabaseHelper._ID
+ "=?", argument);
Log.d(DEBUG_TAG, "logout count " + count);
}
}
}
});
}
return convertView;
}
这是布局,profileselect_list_item:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="0dp" >
<Button
android:id="@+id/title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<Button
android:id="@+id/logout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/logout" />
</LinearLayout>