java - Android - findViewWtihTag 返回 null

标签 java android android-listview android-identifiers

此 Activity 中的 findViewWithTag 返回 null,但 CustomExpandableListAdapter 中的日志输出正确。我在这里做错了什么?

public class CustomExpandableListAdapter extends BaseExpandableListAdapter {

//normal stuff

public View getGroupView(int groupPosition, boolean isLastChild,
View view, ViewGroup parent) {

    CustomObject group = (CustomObject) getGroup(groupPosition);
    //normal stuff

    LinearLayout toggle = (LinearLayout) view.findViewById(R.id.toggle);
//group.getId() returns an int
    toggle.setTag("toggle" + group.getId());
    Log.i("BBBBBtoggleadapterBBBBBB", toggle.getTag().toString());


    return view;
}


}



public class MainActivity extends BaseListActivity {

//normal stuff

//this is an xml onClick
public void toggleView(View view) {

  String groupId = view.getTag().toString();
  //LinearLayout toggle = (LinearLayout) view.findViewWithTag("toggle " + groupId);
   Log.i("BBBBBBBBBtoggleactivityBBBBBBBBBB", "toggle" + groupId);

    /*if (toggle == null) {
    Toast.makeText(getBaseContext(), "null", Toast.LENGTH_LONG).show();
    }*/

}

}

编辑:更新代码,在 Activity 和适配器中记录“toggle”+ id,它们是相同的

最佳答案

我明白了。 findViewWithTag 查找匹配的子标签。我试图识别的 LinearLayout 不是 onClick 触发的toggleView 按钮的子级。因此,我需要向上(在本例中为 2 层)才能找到它。

View parent = (View) view.getParent().getParent();
LinearLayout toggle = (LinearLayout) parent.findViewWithTag("toggle" + groupId);

关于java - Android - findViewWtihTag 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20550928/

相关文章:

android - 如何将从网络下载的图像存储在缓存中?

java - 如何处理从 servlet 中的 Angular 应用程序发送的预检请求?

android - 无法在android中的xmpp服务器中连接

java - 许可基于 Java Web 的应用程序

android - Nox App Player 无法连接到 Android Studio

java - Fragments 和 Activity 中自定义对象是按值传递还是按引用传递?

android - 禁用 Android ListView 'blue' 背景

android - 如何处理搜索建议点击项目

java - 如何使用Java从MySQL数据库输出前10个字符串

java - 未显示滚动条时如何摆脱 SWT ScrolledComposite 中的浪费空间