【发布时间】:2013-09-16 23:21:11
【问题描述】:
我有一个在应用打开时启动的主要活动。活动启动后,它会从主活动 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>
【问题讨论】:
-
由于活动和片段的布局相同,因此将在按钮上设置单击侦听器(但这将来自活动布局),但是当您添加片段时,该按钮将被片段的布局覆盖,因此您不会收到点击事件。或者,我希望您不要尝试在片段布局中的按钮上设置点击侦听器。
-
@Luksprog 不,我正在尝试从主布局设置 Click 事件,如您在此处看到的。我能做些什么来解决我遇到的这个问题?
标签: android gridview android-fragments