我想将一个ImageButton放在工具栏中,它的一个徽标,并配置它,以便用户点击它,它将它们带到一个网站。工具栏中的ImageButton对Click事件没有响应
我能够在所有3个片段上正确显示徽标,但如果我点击徽标则没有任何反应。
从activity_main的XML是什么样子:
<?xml version="1.0" encoding="utf-8"?><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
>
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/appbar_padding_top"
android:theme="@style/AppTheme">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/AppTheme">
<ImageButton
android:id="@+id/logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="@drawable/jclogo"
android:onClick="GoToLogo"/>
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
然后在OnActivityCreated的片段我设置OnClickListener:
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
myLogo = (ImageButton) getActivity().findViewById(R.id.logo);
myLogo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Uri uri = Uri.parse("http://somewebsite.co.uk");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
我也实施和OnClick方法:
public void GoToLogo(View v) {
v.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Uri uri = Uri.parse("http://somewebsite.co.uk");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
但没有任何反应。没有任何标识被点击。它没有响应,因为它在工具栏中?
非常感谢。
布局XML文件,过帐是从framgments或活动? –
@Bruno,它是活动的xml – user3079872
所以让onclickListener里面的活动创建方法。不片段OnActivityCreated方法。 –