适用于Android中所有活动的通用可点击标题

我在所有布局中都有一个带有公共标题的应用程序.我希望每当用户点击带有id btn_home的 ImageView时,应用程序将返回到特定的活动,例如我的“Main”.

最好的方法是什么?

我知道我可以为每个活动定义onClick(View v),但也许有更好的方法可以做到这一点.即使让每个活动成为一些(通过传统)其他具有onClick(View v)定义的声音也很糟糕.

header.xml

<RelativeLayout ...>
    <RelativeLayout android:id="@+id/relativeLayout1" ...>
        <ImageView android:id="@+id/logo_cats"></ImageView>
        <ImageView android:id="@+id/btn_home" ...></ImageView>
    </RelativeLayout>
</RelativeLayout>

每个布局

...
<include layout="@layout/header" android:id="@+id/header"
        android:layout_height="wrap_content" android:layout_width="fill_parent" />
...

解决方法

您可以从标题中创建自定义组件,并在其中定义“onClick()”.例如,创建一个新的类Header,它将扩展RelativeLayout并在那里膨胀header.xml.然后,而不是< include>标签你将使用< com.example.app.Header android:id =“@ id / header”....没有代码重复,标题变得完全可重用. UPD:这是一些代码示例 header.xml:
<merge xmlns:android="http://schemas.android.com/apk/res/android">
    <ImageView android:id="@+id/logo" .../>
    <TextView android:id="@+id/label" .../>
    <Button android:id="@+id/login" .../>
</merge>

activity_with_header.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" ...>
    <com.example.app.Header android:id="@+id/header" .../>
    <!-- Other views -->
</RelativeLayout>

Header.java:

public class Header extends RelativeLayout {
public static final String TAG = Header.class.getSimpleName();

protected ImageView logo;
private TextView label;
private Button loginButton;

public Header(Context context) {
    super(context);
}

public Header(Context context,AttributeSet attrs) {
    super(context,attrs);
}

public Header(Context context,AttributeSet attrs,int defStyle) {
    super(context,attrs,defStyle);
}

public void initHeader() {
        inflateHeader();
}

private void inflateHeader() {
    LayoutInflater inflater = (LayoutInflater) getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inflater.inflate(R.layout.header,this);
    logo = (ImageView) findViewById(R.id.logo);
    label = (TextView) findViewById(R.id.label);
    loginButton = (Button) findViewById(R.id.login);
}

ActivityWithHeader.java:

public class ActivityWithHeader extends Activity {
private View mCreate;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestwindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_with_header);

    Header header = (Header) findViewById(R.id.header);
    header.initHeader();
    // and so on
}
}

在这个例子中,Header.initHeader()可以在Header的构造函数中移动,但通常这个方法提供了传递一些有用的监听器的好方法.希望这会有所帮助.

相关文章

###实现效果*本实例主要实现用ViewPage和Fragment实现选项卡...
一、安装 JDK 下载JDK最新版本,下载地址如下: http://www....
这篇“android轻量级无侵入式管理数据库自动升级组件怎么实现...
今天小编给大家分享一下Android实现自定义圆形进度条的常用方...
这篇文章主要讲解了“Android如何解决字符对齐问题”,文中的...
这篇文章主要介绍“Android岛屿数量算法怎么使用”的相关知识...