如何使TextView看起来像按钮?

问题描述

| 我在Android中有一个ListActivity。每行只是一个项目,该项目以某种资源开始另一个活动。认情况下,这当然是TextView。 我想要(和“我想要\”,我的意思是“客户坚持”),TextView看起来像一个按钮。如果我实际上将它们设置为Button,则认列表单击处理程序将不再起作用-即使它们不能集中显示-因此我必须编写代码以手动为包含按钮的视图充气并设置单击处理程序。 有什么方法可以使TextView看起来像一个Button,而没有Button的任何行为吗?     

解决方法

您应该能够只在布局XML文件中设置样式。 有关内置平台样式的列表,请参见http://developer.android.com/reference/android/R.style.html。不知道它会如何工作,但是它相当容易做到。尝试这个:
<TextView android:layout_height=\"wrap_content\" style=\"@android:style/Widget.Button\" android:layout_marginRight=\"5sp\" android:text=\"\" android:layout_width=\"fill_parent\"></TextView>
编辑:问题是默认按钮样式设置了“ 1”属性。尝试添加
android:clickable
属性并将其设置为false:
<TextView android:layout_height=\"wrap_content\" style=\"@android:style/Widget.Button\" android:layout_marginRight=\"5sp\" android:text=\"\" android:clickable=\"false\" android:layout_width=\"fill_parent\"></TextView>
    ,您应该只能够创建按钮的
Drawable
,并在
TextView
上使用
setBackgroundDrawable()
。 或者,您可以使用
android:background
XML属性。     ,从我的项目中获得以下完整布局:
<?xml version=\"1.0\" encoding=\"utf-8\"?>

<!-- Solution 1: New Button appearance -->
<!--TextView xmlns:android=\"http://schemas.android.com/apk/res/android\"
    android:layout_width=\"match_parent\"
    android:layout_height=\"match_parent\"
    style=\"@android:style/Widget.DeviceDefault.Button\"
    android:textAllCaps=\"false\"
    android:focusable=\"false\"
    android:clickable=\"false\" /-->

<!-- Solution 2: Old Button appearance -->
<TextView xmlns:android=\"http://schemas.android.com/apk/res/android\"
      android:layout_width=\"match_parent\"
      android:layout_height=\"match_parent\"
      android:background=\"@android:drawable/btn_default\"
      android:gravity=\"center_vertical|center_horizontal\" />
没有clickable = false的onItemClick()不会在ListView / GridView等中触发。 没有focusable = false,当您按下TextView按钮时,您没有按下按钮的效果。     ,在XML textview中设置:
android:clickable=\"true\"
并在Java文件集中设置:
TextView youtTextView=(TextView)findViewById(R.id.yourTxt);

youtTextView.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
       //code your button click action/event
    }
});