【发布时间】:2014-09-18 06:43:48
【问题描述】:
背景:我正在编写一个 Android 应用程序,主要是按照 the official developer guides 的说明进行操作。我有一些编写 Java 代码的经验,但很少使用 xml 和 Android。
问题:我想将静态类“PlaceholderFragment”(包含在“BoardContainer”类中)中变量的信息传递给我的片段布局文件“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,或者布局文件将包含七个ImageButtons而不仅仅是一个,等等。也就是说,如何让xml文件从其对应的类中读取并理解实例变量?
【问题讨论】:
标签: java android xml android-layout android-fragments