gpt4 book ai didi

android - 从 XML 获取 View

转载 作者:行者123 更新时间:2023-11-29 18:19:57 26 4
gpt4 key购买 nike

在我的应用程序中,我有一个在 Activity 之间保持不变的导航菜单。为了让我的代码更容易修改,我将它放入自己的 xml 中,并一直在为我的每个屏幕导入我的布局。

为了设置按钮,我制作了一个类,我将其传递给我当前的 Activity 。新类可以毫无问题地找到按钮的 View ,但找不到菜单的封装布局,并在我尝试 findViewById() 时返回 null。由于按钮和布局在相同的 XML 中

public static void setup(Activity a){
myActivity = a;

//OFFENDING BIT OF CODE
View myLayout = (View) myActivity.findViewById(R.layout.navigation_bar);

Log.d(TAG, "layout: "+myLayout);

set_btn = (ImageButton) myActivity.findViewById(R.id.a_settings);
set_btn.setPressed(false);
set_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//TODO:
}
});

inbox_btn = (ImageButton) myActivity.findViewById(R.id.a_offers);
inbox_btn.setPressed(false);
inbox_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//TODO:
}
});

}

主屏幕 XML

<RelativeLayout android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/navigationBar"
android:layout_alignParentBottom="true">
<include android:layout_height="wrap_content"
android:id="@+id/include1"
layout="@layout/navigation_bar"
android:layout_width="wrap_content"></include>
</RelativeLayout>

菜单 XML

<RelativeLayout mlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/NavigationLayout">

<RelativeLayout android:id="@+id/buttonLayout"
android:layout_height="75dip"
android:layout_width="fill_parent"
android:layout_alignParentBottom="true">

<ImageButton android:id="@+id/a_settings"
android:layout_width="100dip"
android:background="@drawable/settings_button"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_height="fill_parent"
android:scaleType="fitXY">
</ImageButton>

<ImageButton android:id="@+id/a_wallet"
android:layout_width="100dip"
android:background="@drawable/wallet_button"
android:layout_toLeftOf="@+id/a_settings"
android:layout_alignBottom="@+id/a_settings"
android:layout_height="fill_parent"
android:scaleType="fitXY">
</ImageButton>

<ImageButton android:id="@+id/a_offers"
android:layout_width="100dip"
android:background="@drawable/offers_button"
android:layout_toRightOf="@+id/a_settings"
android:layout_alignBottom="@+id/a_settings"
android:layout_height="fill_parent"
android:scaleType="fitXY">
</ImageButton>

</RelativeLayout>

</RelativeLayout>

最佳答案

即使您的菜单布局确实名为 navigation_bar,您为包含的菜单布局指定了 include1 的 ID -> android:id="@+id/include1"。如果您想在 Activity 中解决它,请尝试使用 findViewById(R.id.include1)(或者只是尝试查找 ImageButtons,它们也是可见的)。

关于android - 从 XML 获取 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6063478/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com