android - 带有两个 TextView 的自定义按钮

标签 android

我正在尝试在一个按钮中使用两个具有不同字体的 TextView 来自定义按钮。为此,我只是扩展了 Button 并在构造函数中编写了以下代码,

LayoutInflater layoutInflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.custom_button,
        (ViewGroup) findViewById(R.id.custom_button_view));

TextView firstTextView = (TextView) layout
        .findViewById(R.id.firstTextView);
TextView secondTextView = (TextView) layout
        .findViewById(R.id.secondTextView);

在布局 custom_button 中,我放置了两个具有不同字体和文本的 TextView,custom_button_view 是该 LinearLayout 的 ID,我得到的是一个没有文本的空按钮。

任何想法,谢谢。

最佳答案

您可以通过将自定义按钮样式设置为布局来将布局用作按钮,并可以向其添加两个 TextView ,方法如下:

<LinearLayout android:id="@+id/customButtonLayout"
    android:layout_height="wrap_content" style="@android:style/Widget.Button"
    android:layout_width="wrap_content">
    <TextView android:text="First" android:id="@+id/firstTextView"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:textColor="#000"></TextView>
    <TextView android:textColor="#000" android:text="Second"
        android:layout_height="wrap_content" android:id="@+id/secondTextView"
        android:layout_width="wrap_content" android:layout_marginLeft="10dp"></TextView>
</LinearLayout>

在 Activity 中你可以设置不同的字体:

    Typeface font=Typeface.createFromAsset(getAssets(),"ARIALN.TTF") ;   
    Typeface font2=Typeface.createFromAsset(getAssets(), "COMPCTAN.TTF");

    TextView firstTextView = (TextView)findViewById(R.id.firstTextView);
    TextView secondTextView = (TextView)findViewById(R.id.secondTextView);

    firstTextView.setTypeface(font);
    secondTextView.setTypeface(font2);

    LinearLayout btnLayout=(LinearLayout) findViewById(R.id.customButtonLayout);
    btnLayout.setOnClickListener(this);

关于android - 带有两个 TextView 的自定义按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7328890/

相关文章:

java - 使用 new Button(this) 有什么好处?

android - 为多个屏幕规划自定义屏幕布局

android - 适用于所有 Samsung Galaxy Tabs 的应用程序,如何制作可绘制对象和布局

android - REST API 的推荐 Observable 类型

iphone - 在网络移动设备上购买电子商务

android - 无法与 Sherlock 一起使用标签

android - 用户定义的 ActionBar Action View : getting the width right

android - 配置 Sequoyah 调试 JNI 代码

android - gradle:Android Studio 继承 buildtype

Android 检查 wifi 连接