Java 在Android中,如何将数据从类传递到相应的布局/片段文件?

Java 在Android中,如何将数据从类传递到相应的布局/片段文件?,java,android,xml,android-layout,android-fragments,Java,Android,Xml,Android Layout,Android Fragments,背景:我正在编写一个安卓应用程序,主要是按照来自的说明编写的。我有一些编写Java代码的经验,但很少使用xml和Android 问题:我想将静态类“Placeholder fragment”(包含在“BoardContainer”类中)中的变量的信息传递到片段布局文件“fragment_board.xml”。占位符片段如下所示(大部分在Eclipse为我创建它之后未经编辑): (其他生命周期回调尚未实现) 现在,我的fragment_board.xml如下所示: <RelativeLayo

背景:我正在编写一个安卓应用程序,主要是按照来自的说明编写的。我有一些编写Java代码的经验,但很少使用xml和Android

问题:我想将静态类“Placeholder fragment”(包含在“BoardContainer”类中)中的变量的信息传递到片段布局文件“fragment_board.xml”。占位符片段如下所示(大部分在Eclipse为我创建它之后未经编辑):

(其他生命周期回调尚未实现)

现在,我的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>
ImageButton imgHandle = (ImageButton) findViewById(R.id.imageButton1);

if(nButtons == 7) {
    imgHandle.setImageResource(R.id.grid7);
}


这里我想使用
int
实例变量
nButtons
,例如,如果
nButtons==7
,那么我们得到
android:src=“@drawable/grid7
而不是
grid2
,或者布局文件将包含七个图像按钮而不是一个,以此类推。换句话说,如何使xml文件从其相应的类中读取和理解实例变量?

不幸的是,xml文件不能
从其相应的类中读取和理解变量。相反,我们可以通过在类文件中获取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>
ImageButton imgHandle = (ImageButton) findViewById(R.id.imageButton1);

if(nButtons == 7) {
    imgHandle.setImageResource(R.id.grid7);
}
在一个片段中,您需要在onCreateView方法内部使用rootView:

ImageButton imgHandle = (ImageButton)rootView.findViewById(R.id.imageButton1);

很好,我做到了这一点,但遗憾的是xml文件无法理解来自相应类的变量。例如,假设我在类中有一个布尔变量,如果它是真的,我将在片段文件中有一个特定的ImageButton,否则不会。有可能这样做吗?或者我只需要一堆不同的片段xml文件?一种处理方法是将ImageButton放入xml文件中,如果您决定不让它显示,您可以在类代码中获取对它的引用,并使用setVisibility函数对GONE常量进行设置,这样它就不会显示为Anks你的帮助。我试图理解如何实现一个复杂的布局系统,它根据用户的输入而变化。例如:有关卡的游戏,每个关卡使用不同大小的棋盘和不同的棋子。将其转化为应用程序的专业方法是什么?为每个级别使用不同的布局文件,或者使用您在这里建议的方法?如果我选择后一个选项,我需要解决这个问题:如何根据相应类文件中的实例变量在GridLayout中设置“app:columnCount”?我还没有用Android开发过游戏,所以我可能不是提供建议的最佳人选,请随时在此提出另一个问题,我相信更有资格的人会提供帮助。以下是我的后续问题: