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

rlc*_*rlc 8 android android-activity

我在所有布局中都有一个带有公共标题的应用程序.我希望每当用户点击带有id的ImageView时btn_home,应用程序将返回到特定的活动,例如我的"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>
Run Code Online (Sandbox Code Playgroud)

每个布局

...
<include layout="@layout/header" android:id="@+id/header"
        android:layout_height="wrap_content" android:layout_width="fill_parent" />
...
Run Code Online (Sandbox Code Playgroud)

Ash*_*Ash 15

您可以从标题中创建自定义组件,并在其中定义"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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

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
}
}
Run Code Online (Sandbox Code Playgroud)

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