0

I would like to make a button, a simple button, having the default Search icon that is used in Android. However, I do not want to make my own xml file and put the images in the Drawable folder, because i know they already exist in the Android sdk.

  • So why not making use of them?

I tried to make something like this:

android:background="@android:drawable/...." but there in this directory it seems that all the files are png file not xml file able to interact with the user (on button pressed, etc..)

I hope an expert can help solving this problem.

4

1 回答 1

2

按钮工作不需要 xml 文件。可绘制对象中的 png 文件仅用于图像。您可以以编程方式或在 xml 中创建一个按钮,但您仍然必须在某处创建它,因为Button实例是用于 xml 的onClick()而不一定是 xml。无论哪种方式,您都必须有一个 xml 文件供您Layout使用,setContentView()以便您可以Button在该布局文件中放置一个或在您的 Java 代码中创建它,但无论哪种方式,您都必须创建一个Button

XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent" 
              android:layout_height="fill_parent" 
              android:orientation="vertical" >
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Hello, I am a TextView" />
    <Button android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello, I am a Button" />
</LinearLayout>

在这个Button你可以设置背景或使用一个ImageButton代替并设置 `android:src="@drawable/..."

然后在您的代码中,您仍然必须获取按钮实例

按钮 btn1 = (Button) findViewById(R.id.button)

在你调用你的布局之后

setContentView(R.layout.your_layout_file);

如果您使用ImageButtonjust replace Buttonwith ImageButtonwhich 这听起来像是您想要的。希望这有助于它对你更有意义

于 2013-02-28T23:19:23.127 回答