我有一个在应用程序打开时启动的主要活动。活动启动后,它会从主活动 onCreate 打开一个 GridView 片段(此外,主活动和片段共享相同的 XML 布局)。
我遇到的问题是,每当我尝试将 onClick 事件添加到我的 Button 时,除非我从我的主要活动中删除打开 GridView 片段的代码,否则什么都不会发生。
注意:我正在为我的 GridView 使用片段,因为我同时显示大量图像,所以我设置了片段类来有效地处理它们而不影响性能。
有什么办法可以解决这个问题吗?提前欢呼。
主要活动:
public class ImageGridActivity extends FragmentActivity {
private static final String TAG = "ImageGridActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.image_grid_fragment);
if (BuildConfig.DEBUG) {
Utils.enableStrictMode();
//Whenever I remove this code here:
}
super.onCreate(savedInstanceState);
if (getSupportFragmentManager().findFragmentByTag(TAG) == null) {
final FragmentTransaction ft = getSupportFragmentManager()
.beginTransaction();
ft.add(android.R.id.content, new ImageGridFragment(), TAG);
ft.commit();
//To here, it works
Button B1 = (Button) findViewById(R.id.button1);
B1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.w("myApp", "no network");
}
});
}
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<GridView
android:id="@+id/gridView"
style="@style/PhotoGridLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="@dimen/image_thumbnail_size"
android:horizontalSpacing="@dimen/image_thumbnail_spacing"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="@dimen/image_thumbnail_spacing" >
</GridView>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Button" />
</RelativeLayout>