从xml创建自定义视图

时间:2011-04-22 14:53:40

标签: android layout views custom-view

我想添加相同的水平滚动行按钮

<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);     
  }    
}
然后呢?我如何实际显示它?还有其他方法我应该重写吗?有没有更好/更合适的方法呢?