【问题标题】:How do I change a button with onclick in android?如何在android中使用onclick更改按钮?
【发布时间】:2017-12-27 23:43:48
【问题描述】:

我有这个按钮,当我从
state1state2 反之亦然。

心脏是 2 个不同的可绘制对象(@drawable/ic_fav_dish_color 和 @drawable/ic_fav_dish_grey),文本是 2 个不同的字符串(@string/dish_faved 和 @string/dish_not_faved)

我使用该代码在 xml 中制作了按钮:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:id="@+id/fav_dish_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/ic_fav_dish_color"
        android:gravity="start|center_vertical"
        android:text="@string/dish_faved"
        android:textAlignment="center"
        android:layout_margin="8dp"/>
</LinearLayout>

【问题讨论】:

    标签: android xml button onclick


    【解决方案1】:

    你可以用这个,你应该有两张图片,一张是填充的,另一张是 不是

    final Button btn = (Button)(findViewById(R.id.fav_dish_button));
    final Drawable drawable = getResources().getDrawable(R.drawable.your_fill_heart_image_name);
    btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
    
    
                btn.setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null);
    
            }
        });
    

    【讨论】:

      【解决方案2】:

      你应该在你的按钮上做一个点击监听器,如下所示:

      Button mButton=(Button)findViewById(R.id.fav_dish_button);
      
      mButton.setOnClickListener(new OnClickListener() {
          public void onClick(View v) {
             mButton.setText(getResources().getString(R.string.dish_not_faved);); 
             mButton.setBackgroundResource(R.drawable.ic_fav_dish_grey);
          } 
      });
      

      更新:

      如果你想改变drawable left,试试下面的代码:

              // Left, top, right, bottom drawables
      Drawable[] drawables = mButton.getCompoundDrawables();
              // get left drawable.
      Drawable leftCompoundDrawable = drawables[0];
              // get desired drawable.
      Drawable img = getContext().getResources().getDrawable(R.drawable.ic_fav_dish_grey);
              // set image size (don't change the size values)
      img.setBounds(leftCompoundDrawable.getBounds());
              // set new drawable
      mButton.setCompoundDrawables(img, null, null, null);
      

      【讨论】:

      • 如果我这样做,图标将显示为按钮的整个背景,而不是仅显示在左侧
      • 如果我再次点击,如何实现反之亦然?
      • 您可以创建一个变量作为标志来维护状态。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 2020-07-08
      • 2021-06-04
      • 1970-01-01
      相关资源
      最近更新 更多