【问题标题】:how to get id in different layout如何在不同的布局中获取 id
【发布时间】:2010-11-18 02:41:53
【问题描述】:

当我使用findVewById 时,我在single_item.xml 中有id "@+id/call"(布局setcontextview(R.layout.main))。应用程序崩溃。如何修复错误

【问题讨论】:

  • 请向我们展示确切的 single_item.xml,您使用 setContextView(..) 和 findViewById(..) 的行,并请查看异常的 logcat。我们可以更快地为您提供所需的帮助。根据目前的信息,我们不知道该去哪里寻找或如何为您提供帮助。

标签: android android-layout


【解决方案1】:

如果您想访问另一个布局(不是活动布局)中的视图,那么您可以扩展您想要使用的布局并以这种方式访问​​它。

例子:

View inflatedView = getLayoutInflater().inflate(R.layout.other_layout, null);
TextView text = (TextView) inflatedView.findViewById(R.id.text_view);
text.setText("Hello!");

更多关于膨胀布局的信息可以在here找到。

【讨论】:

  • 我试过但它不能正常工作这是 single_item.xml 中的按钮 这是我想要获取按钮的类中的一些代码 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
  • 查看 inflatedView = getLayoutInflater().inflate(R.layout.single_item, null);按钮调用 = (Button) inflatedView.findViewById(R.id.call); call.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //TODO 自动生成的方法存根 call(); } });
  • 我想用这个获取 id 按钮来拨打电话,因为 CustomSqlCursorAdapter 扩展类实现了 implecursoradapter 我不能用它来做活动,所以我想从 managecontact 获取这个
  • 当我点击按钮时没有任何反应:(
  • 所以这些是列表项中的按钮?
【解决方案2】:

您正试图在 R.layout.main 中的 R.layout.single_item 中找到声明的视图(R.id.call),所以我猜它会抛出空指针异常。

您应该在 main.xml 文件中声明“@+id/call”元素,或者将上下文视图设置为 R.layout.single_item

【讨论】:

  • 这里是 CustomSqlCursorAdapter 类
  • schemas.android.com/apk/res/android" android:orientation="horizo​​ntal" android:layout_width="fill_parent" android:layout_height="fill_parent" >
  • 你能用代码更新你的第一篇文章吗?如果没有缩进或格式,那么在 cmets 中没有缩进或格式化真的很难阅读代码,而且您的“CustomSqlCursorAdapter”类丢失了。
【解决方案3】:

从视图中获取id 的简单方法是:

String id = getResources().getResourceEntryName(view.getId());

【讨论】:

    【解决方案4】:

    如果要获取片段中的 id,请使用以下方法。 用这样的视图替换 return 语句。

     View view= inflater.inflate(R.layout.fragment_left, container, false);
     img=view.findViewById(R.id.image);
     return view;
    

    在返回视图之前调用所有方法。

    【讨论】:

      【解决方案5】:
      View parent = (View)view.getParent();
      ??? = (???)parent.findViewById(R.id.call);
      

      试试这个。希望对你有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多