【发布时间】:2011-04-22 14:53:40
【问题描述】:
我想像这样添加相同的水平滚动按钮行
<HorizontalScrollView [...]>
<LinearLayout [...] android:orientation="horizontal">
<Button android:id="@+id/btn1" [..] />
<Button [..] />
[...]
</LinearLayout>
</HorizontalScrollView>
(toolbar.xml) 到我的应用程序中每个活动的底部。而不是必须为每个活动中的每个按钮指定单击侦听器,我希望能够在一个地方完成所有这些,然后每次只导入控件。我想我可以做类似的事情
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.example.ButtonBar android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_alignParentBottom="true"
android:layout_below="@+id/pagecontent" />
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/pagecontent">
<!-- the rest of each activity's xml -->
</LinearLayout>
在屏幕上包含按钮栏,然后执行类似的操作
package com.example;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.HorizontalScrollView;
public class ButtonBar extends HorizontalScrollView implements OnClickListener
{
public ButtonBar(Context context, AttributeSet attrs)
{
super(context, attrs);
LayoutInflater inflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.toolbar, null);
Button btn1 = (Button) view.findViewById(R.id.button1);
btn1.setOnClickListener(this);
// and so on for the rest of the buttons
addView(View);
}
@Override
public void onClick(View v)
{
Intent intent = null;
if (v.getId() == R.id.btn1)
{
intent = new Intent(getContext(), FirstScreen.class);
}
else if (v.getId() == R.id.btn2)
{
intent = new Intent(getContext(), SecondScreen.class);
}
// and so on
if (intent != null) getContext().startActivity(intent);
}
}
然后呢?我如何真正让它显示?我应该覆盖其他方法吗?有更好/更合适的方法吗?
【问题讨论】:
-
您当然可以按照您的描述进行操作,并且快速查看不会发现任何错误(尽管您的控件在某个地方称为
com.example.ToolBar,在其他地方称为com.example.ButtonBar)。从基本控件继承是一种很好的方法,因为它实现了控件的所有必需行为。回覆。 “我如何真正让它显示”,你试过吗?您为什么不认为这会导致显示自定义控件? -
主要是因为当我运行它时,它没有显示出来。
-
是的,就是这样。您可能希望为您的自定义视图创建一个特殊的单击侦听器,以便您可以在 Activity 内部指定按钮需要执行的操作,如果它们的功能发生变化。恕我直言,这也会更干净。
-
层次结构查看器对此有何评论?
-
@bigstones:好电话!层次结构查看器显示按钮栏肯定被添加到屏幕上,但在底部,所以我的 xml 一定是错误的地方。
标签: android layout views custom-view