android - 从 xml 创建自定义 View

标签 android layout view custom-view

我想添加相同的水平可滚动按钮行,如下所示

<HorizontalScrollView [...]>
  <LinearLayout [...] android:orientation="horizontal">
    <Button android:id="@+id/btn1" [..] />
    <Button [..] />
     [...] 
  </LinearLayout>
</HorizontalScrollView>

(toolbar.xml) 到我的应用程序中每个 Activity 的底部。我希望能够在一个地方完成所有这些操作,然后每次都导入控件,而不是必须为每个 Activity 中的每个按钮指定单击监听器。我想我可以做类似的事情

<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);     
  }    
}

但是然后呢?我如何真正让它显示出来?还有其他我应该重写的方法吗?有更好/更合适的方法吗?

最佳答案

关于android - 从 xml 创建自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5756642/

相关文章:

css - 6列流体布局

c++ - 如何通过单击 MainFrame 中的按钮来更改 MFC View

java - 使用 SharedPreferences 的 ClassCastException

android - 如何从 JNI 调用 C++ 方法

android - 在布局中动态添加布局?

java - 如何以编程方式使 View 在布局上居中?

java - 在 fragment 布局中创建动态 View 时出现问题

swift - 如何重新加载 ui View 的内容 Swift

java - 在 Android 中更改 TextView 的值

android - Gradle 同步失败 - 将 Android Studio 更新到 3.2 后