【问题标题】:How to change an Image in a button on clicking the button?单击按钮时如何更改按钮中的图像?
【发布时间】:2017-09-25 05:33:19
【问题描述】:

我有一个图像 (image1) 和一个按钮中的文本,我需要更改图像 点击后到(image2)。怎么做?

【问题讨论】:

标签: c# android xamarin xamarin.android


【解决方案1】:

Xamarin/C# 方式:

var button = FindViewById<Button>(Resource.Id.myButton);
button.Click += delegate { 
    button.Text = "Some New Text";

    // If your image is a Drawable
    button.SetBackgroundResource(Resource.Drawable.button_background);

    // From an asset
    button.Background = Drawable.CreateFromStream(Assets.Open("button_asset.jpg"), null);

    // From an arbitrary path
    button.Background = Drawable.CreateFromPath("/sdcard/Download/downloaded_file.jpg");
};

更新:

如果您在布局中使用drawableLeftdrawableRight 等...,您可以通过SetCompoundDrawablesWithIntrinsicBounds (int left, int top, int right, int bottom) 更改这些:

button.SetCompoundDrawablesWithIntrinsicBounds(0, 0, Resource.Drawable.button_background, 0);

如果您要设置多个可绘制对象,您可以通过以下方式保留和更改其中一些:

var drawables = button.GetCompoundDrawables();
button.SetCompoundDrawablesWithIntrinsicBounds(drawables[0], drawables[1], Resources.GetDrawable(Resource.Drawable.button_background, this.Theme), drawables[3]);

【讨论】:

  • 如果我将图像(这是一个可绘制对象)设置在文本的右侧,如何在单击时将该图像更改为另一个图像? @SushiHangover
  • @Arso 您使用的是ImageButtonButton 还是?
  • 我正在使用一个按钮@SushiHangover
  • @Arso 我更新了我的答案,但你需要在你的问题中充分解释你从哪里开始以及你想要实现的目标,即添加布局 axml 文件的按钮部分会大大澄清事情否则每个人都只是猜测您使用的是drawableRight
  • 给您带来的不便,我深表歉意,以后会这样做。成功了,谢谢你的帮助:)
【解决方案2】:

试试这个

  btn.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View view) {
           btn.setBackgroundResource(R.drawable.your_image);
       }
   });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-15
    • 2013-07-24
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 2017-01-21
    • 2011-12-14
    相关资源
    最近更新 更多