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

时间:2011-09-14 16:27:32

标签: android android-activity

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

最好的方法是什么?

我知道我可以为每项活动定义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" />
...

2 个答案:

答案 0 :(得分:14)

您可以从标题中创建自定义组件,并在其中定义“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的构造函数中移动,但通常这个方法提供了传递一些有用的监听器的好方法。希望这会有所帮助。

答案 1 :(得分:3)

扩展Activity类并构建一个MyActivity类。在此MyActivity类中,您可以包含onClick的代码。

现在创建一个只保存标题的布局。在活动布局中包含该布局。

将您的所有活动从MyActivity扩展 - 就是这样。

如果在ListActivities中需要相同的行为,也可以创建MyListActivity。

相关问题