如何以编程方式在Android按钮设置drawableLeft? [英] How to programatically set drawableLeft on Android button?

查看:143
本文介绍了如何以编程方式在Android按钮设置drawableLeft?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我动态创建的按钮。我称呼他们先使用XML,而我试图把下面的XML,并使其programattic。

<按钮     机器人:ID =@ + ID / buttonIdDoesntMatter     机器人:layout_height =WRAP_CONTENT     机器人:layout_width =FILL_PARENT     机器人:文本=buttonName     机器人:drawableLeft =@可绘制/ imageWillChange     机器人:的onClick =监听器     机器人:layout_width =FILL_PARENT> < /按钮>

这是我到目前为止所。我能做的一切,但被拉伸。

线性=(的LinearLayout)findViewById(R.id.LinearView); Button按钮=新的按钮(这一点); button.setText(按钮); button.setOnClickListener(听众); button.setLayoutParams(     新的LayoutParams(         android.view.ViewGroup.LayoutParams.FILL_PARENT,         android.view.ViewGroup.LayoutParams.WRAP_CONTENT     ) ); linear.addView(按钮);

解决方案

您可以使用setCompoundDrawable方法来做到这一点。看到这个例子这里。我用这个不使用的setBounds和它的工作了。 ü可以尝试两种方式。

更新:在这里复制code柜面之间的链接断开

 可绘制IMG =的getContext()getResources()getDrawable(R.drawable.smiley)。
img.setBounds(0,0,60,60);
txtVw.setCompoundDrawables(IMG,NULL,NULL,NULL);
 

 可绘制IMG =的getContext()getResources()getDrawable(R.drawable.smiley)。
txtVw.setCompoundDrawablesWithIntrinsicBounds(IMG,NULL,NULL,NULL);
 

  txtVw.setCompoundDrawablesWithIntrinsicBounds(R.drawable.smiley,0,0,0);
 

I'm dynamically creating buttons. I styled them using XML first, and I'm trying to take the XML below and make it programattic.

<Button
    android:id="@+id/buttonIdDoesntMatter"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:text="buttonName"
    android:drawableLeft="@drawable/imageWillChange"
    android:onClick="listener"
    android:layout_width="fill_parent">
</Button>

This is what I have so far. I can do everything but the drawable.

linear = (LinearLayout) findViewById(R.id.LinearView);
Button button = new Button(this);
button.setText("Button");
button.setOnClickListener(listener);
button.setLayoutParams(
    new LayoutParams(
        android.view.ViewGroup.LayoutParams.FILL_PARENT,         
        android.view.ViewGroup.LayoutParams.WRAP_CONTENT
    )
);      

linear.addView(button);

解决方案

You can use the setCompoundDrawable method to do this. see the example here. I used this without using the setBounds and it worked for. u can try either way.

UPDATE: Copying the code here incase the link goes down

Drawable img = getContext().getResources().getDrawable( R.drawable.smiley );
img.setBounds( 0, 0, 60, 60 );
txtVw.setCompoundDrawables( img, null, null, null );

or

Drawable img = getContext().getResources().getDrawable( R.drawable.smiley );
txtVw.setCompoundDrawablesWithIntrinsicBounds( img, null, null, null);

or

txtVw.setCompoundDrawablesWithIntrinsicBounds( R.drawable.smiley, 0, 0, 0);

这篇关于如何以编程方式在Android按钮设置drawableLeft?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆