背景:我正在编写一个 Android 应用程序,主要遵循 the official developer guides 的说明.我有一些编写 Java 代码的经验,但很少有 xml 和 Android 的经验。
问题:我想将信息从我的静态类“PlaceholderFragment”(包含在我的“BoardContainer”类中)中的变量传递到我的 fragment 布局文件“fragment_board.xml”。 PlaceholderFragment 看起来像这样(在 Eclipse 为我创建后大部分未经编辑):
public static class PlaceholderFragment extends Fragment {
public int nButtons = 2;
public static class PlaceholderFragment extends Fragment {
private int nButtons = 2;
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_board,
container, false);
return rootView;
}
}
(其他生命周期回调暂未实现)
现在我的 fragment_board.xml 是这样的:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.exampletest.MainGame$PlaceholderFragment" >
<ImageButton
android:id="@+id/imageButton1"
android:layout_width="49dp"
android:layout_height="49dp"
android:contentDescription="@null"
android:onClick="buttonPressed" //not yet implemented
android:src="@drawable/grid2" />
</RelativeLayout>
在这里我想使用 int
实例变量 nButtons
这样,例如,如果 nButtons==7
,那么我们得到android:src="@drawable/grid7
而不是 grid2
,或者布局文件将包含七个 ImageButton 而不是一个,等等。换句话说,如何我如何使 xml 文件读取并理解其对应类中的实例变量?
最佳答案
不幸的是,XML 文件无法读取和理解其对应类中的变量
。相反,我们可以通过获取类文件中 XML 文件中包含的组件的句柄并像这样更改它们来以编程方式更改它们:
ImageButton imgHandle = (ImageButton) findViewById(R.id.imageButton1);
if(nButtons == 7) {
imgHandle.setImageResource(R.id.grid7);
}
在 fragment 中,您需要在 onCreateView 方法中使用 rootView:
ImageButton imgHandle = (ImageButton)rootView.findViewById(R.id.imageButton1);
关于java - 在Android中,如何将数据从类传递到相应的布局/fragment 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24972200/