Imagebutton from drawable in layer-list?

2019-07-10 00:13发布

问题:

I've looked for hours for the answer to this seemingly simple issue I'm having.

Basically, how do you make a certain drawable in a layer-list an imagebutton?

Eclipse doesn't mark this code with any errors yet when it runs I get a force close. What am I missing?

Also --

Do I use findViewById to reference resources even when they're in a layer-list?

Does the android:id in the XML file belong with the item tag or the bitmap tag?

EDIT: This code is just something I put together quickly to demonstrate my issue. I'm trying to make just the last layered drawable the active button. For example for a UI I am laying a bunch or graphics on top of one another, the last two layers will be buttons that I want to make active. Is that possible? Or maybe there's a better way to do what I'm trying to do?

Thanks.


layers.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
      <bitmap android:src="@drawable/android_red"
        android:gravity="center" />
    </item>
    <item android:top="10dp" android:left="10dp">
      <bitmap android:src="@drawable/android_green"
        android:gravity="center" />
    </item>
    <item android:id="@+id/blue_button" 
        android:top="20dp" android:left="20dp">
      <bitmap android:src="@drawable/android_blue"
        android:gravity="center" />
    </item>
</layer-list>

main.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" >

    <ImageView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:src="@drawable/layers" />

</LinearLayout>

Activity:

public class LayoutTestActivity extends Activity implements OnClickListener {

      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      requestWindowFeature(Window.FEATURE_NO_TITLE);
      getWindow().setFlags(WindowManager.LayoutParams.FILL_PARENT,WindowManager.LayoutParams.FLAG_FULLSCREEN);

      setContentView(R.layout.main);

      ImageButton imgStartButton = (ImageButton) findViewById(R.id.blue_button);
      imgStartButton.setOnClickListener(this);


      }

    public void onClick(View v) {


    }
}

回答1:

You do not put the id to the layer list drawable but to the Imageview.

<ImageView
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:src="@drawable/layers" 
    android:id="@+id/blue_button"/>

To access the drawable you use

ImageView imgStartButton = (ImageView) findViewById(R.id.blue_button);
imgStartButton.setOnClickListener(this);
imgStartButton.setBackgroundResource(R.drawable.layers);