【问题标题】:How to set the button background image through code如何通过代码设置按钮背景图片
【发布时间】:2011-09-13 06:41:32
【问题描述】:

我正在使用使用以下代码创建的Button

LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);

Button btn = new Button(this);
btn.setOnClickListener(newtodobtn);
btn.setText("New Todo");

btn.setBackgroundDrawable(new Button(this).getBackground());

ll.addView(btn);

我在路径@drawable/new_todo_image 中有一张图片设置为按钮的背景。如何以编程方式将其设置为Button

【问题讨论】:

    标签: java android button


    【解决方案1】:

    为可绘制文件夹中的按钮设置背景图像,然后使用下面的代码

    btn.setBackgroundResource(R.drawable.new_todo_image);
    

    【讨论】:

      【解决方案2】:

      试试这个:

      btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.new_todo_image));
      

      【讨论】:

      • 自 2014 年起,已弃用。
      【解决方案3】:

      试试这个:

      btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.new_todo_image));
      

      【讨论】:

      • 我收到以下错误:View 类型中的方法 setBackgroundDrawable(Drawable) 不适用于参数 (int)
      • btn.setBackgroundResource(R.drawable.new_todo_image);此代码符合要求。并感谢您提供更好的建议
      • btn.setBackgroundResource(R.drawable.new_todo_image);
      【解决方案4】:

      这样试试

      final int sdk = android.os.Build.VERSION.SDK_INT;
          if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN)
           {
            mBtn.setBackgroundDrawable( getResources().getDrawable(R.drawable.new_todo_image) );
           } 
          else
             {
             mBtn.setBackground( getResources().getDrawable(R.drawable.new_todo_image));
             }
      

      【讨论】:

        【解决方案5】:

        在android studio中设置Button背景图片如下代码:

        int image_resid = getApplicationContext().getResources().getIdentifier("image_name", "drawable", getApplicationContext().getPackageName());
        button.setBackgroundResource(image_resid);
        

        【讨论】:

          【解决方案6】:

          你应该把你的 png 文件放到 Drawable 文件夹中,然后试试这些代码:

          Button buttonSES = (Button) findViewById(R.id.buttonSES)    
          buttonSES.setBackgroundResource(R.drawable.image1);  //image1.png 
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2015-10-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多