我在所有布局中都有一个带有公共标题的应用程序.我希望每当用户点击带有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的构造函数中移动,但通常这个方法提供了传递一些有用的监听器的好方法.希望这会有所帮助.