2

我正在尝试使我在 Actionbarsherlock 的自定义布局中定义的图像视图可点击。我的活动首先设置了一个布局:

setContentView(R.layout.myLayout);

actionbar_layout 设置在同一个活动中,如下所示:

View cView = getLayoutInflater().inflate(R.layout.actionbar_layout,
            null);
    actionBar.setCustomView(cView);

实际的 actionbar_layout 如下所示:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:orientation="horizontal" >

<ImageView
    android:id="@+id/actionBarLogo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:paddingBottom="50dp"
    android:paddingLeft="10dp"
    android:paddingRight="50dp"
    android:paddingTop="50dp"
    android:scaleType="centerCrop"
    android:src="@drawable/logo" />

</LinearLayout>

添加这个:

actionBarLogo.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            //code 
        }
    });

导致此行出现 Nullpointer 异常:

actionBarLogo.setOnClickListener(new View.OnClickListener()

自定义布局工作正常,我只需要 imageview 是可点击的。任何想法如何解决这一问题?我的活动如何获得对我在 actionbar_layout.xml 中定义的 actionBarLogo id 的引用?

4

3 回答 3

3

尝试这样的事情:

//your code
View cView = getLayoutInflater().inflate(R.layout.actionbar_layout,
        null);
actionBar.setCustomView(cView);

ImageView actionBarLogo = (ImageView) cView.findViewById(R.id.actionBarLogo);

actionBarLogo.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        //code 
    }
});

它应该工作。

于 2013-01-31T17:19:06.520 回答
2

使用 ImageButton 而不是 ImageView

<ImageButton
    android:id="@+id/actionBarLogo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:paddingBottom="50dp"
    android:paddingLeft="10dp"
    android:paddingRight="50dp"
    android:paddingTop="50dp"
    android:scaleType="centerCrop"
    android:onClick="somemethod"
    android:src="@drawable/logo" />
于 2013-02-01T05:17:45.063 回答
0

据我了解您的问题,它无法访问所需的视图,因为它不是视图的一部分或窗口装饰的一部分。在此处查看此帖子,以找到解决方法:https ://stackoverflow.com/a/10187801/1965084

于 2013-01-31T16:20:03.547 回答