[英]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.