【发布时间】:2018-01-17 13:36:09
【问题描述】:
我想在工具栏中放置一个 ImageButton,它是一个徽标,并对其进行配置,以便用户点击它时,它会将他们带到一个网站。
我能够在所有 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" />
然后在 Fragment 中的 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或activity?
-
@Bruno,是Activity的xml
-
所以在活动oncreate方法中创建onclickListener。不是片段 OnActivityCreated 方法。
-
@Bruno,我试过了,它没有响应任何点击。
标签: android onclicklistener android-toolbar buttonclick android-imagebutton