[英]In Android, how to pass data from class to corresponding layout/fragment file?
背景 :我正在编写一个Android应用程序,主要是按照官方开发人员指南中的说明进行的 。 我在编写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文件从相应的类读取并理解实例变量?
不幸的是,XML文件无法read and understand the variables from its corresponding class
。 相反,我们可以通过获取类文件中XML文件中包含的组件的句柄并进行如下更改来以编程方式更改它们:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.