【问题标题】:set button background image size (java code)设置按钮背景图片大小(java代码)
【发布时间】:2016-11-26 16:03:02
【问题描述】:

我创建了一个动态按钮来填充我的主要活动。 按钮工作正常。 但我想设置一个图像背景。

我已经测试了所有东西,但是img的结果太糟糕了。

如何将图片完美缩放到按钮大小?

我已经对此进行了测试,但无法正常工作,因为 getWidth 给我错误 >0

        int newWhidt=button.getWidth();
        int newHeight=button.getHeight();
        Bitmap originalbitmap= BitmapFactory.decodeResource(getResources(),R.drawable.trasparent);
        Bitmap scaleBitmap= Bitmap.createScaledBitmap(originalbitmap,newWhidt,newHeight,true);
        Resources resource=getResources();
        button.setBackgroundDrawable(new BitmapDrawable(resource, scaleBitmap));

这是我的代码

    private void creabottoni(){
    TableLayout table=(TableLayout) findViewById(R.id.tableforbuttons);
for(int row=0; row < NUM_ROWS; row++){
    TableRow tableRow=new TableRow(this);
    tableRow.setLayoutParams(new TableLayout.LayoutParams(
            TableLayout.LayoutParams.MATCH_PARENT,
            TableLayout.LayoutParams.MATCH_PARENT,
            1.0f));

    table.addView(tableRow);


    for(int col=0;col < NUM_COL; col++){
        final int FINAL_COL=col;
        final int FINAL_ROW=row;
        //Drawable immagine= getResources().getDrawable(R.drawable.trasparent);
        final int FINAL_ID=buttonid;// creo FINAL_ID PER PASSARE ID A ACTIVITY OPERATORE
        Button button=new Button(this);
        button.setLayoutParams(new TableRow.LayoutParams(
                TableRow.LayoutParams.MATCH_PARENT,
                TableRow.LayoutParams.MATCH_PARENT,
                1.0f));


        Cursor res =myDB.getnamebyidbutton(buttonid);
        buttonid++;
        res.moveToFirst();


        //**********METTO TESTO BOTTONI FUNZIONA RES DBHELPER****************************************************
        button.setText(res.getString(res.getColumnIndex("NOME")));




        //qui controllo quale bottone ho premuto

        button.setOnClickListener(new View.OnClickListener(){

            public void onClick(View v) {
                bottonepremuto(FINAL_ID);


            }
        });



    }//fine ciclo colonna
}//fine ciclo riga

}//fine creabottoni

【问题讨论】:

    标签: android image button background scale


    【解决方案1】:

    打开项目显示的项目视图和各种图像包,即:hdmi、xhdmi、xxhdmi 等。将不同大小的相同图像与相同名称放在 xml 中,只需将其引用为可绘制/“图像名称”

    【讨论】:

      【解决方案2】:

      你最好使用 9-patch 背景。 并在您的 java 文件中设置背景,如

      button.setBackground(your 9-patch);

      tutorial for 9-Patch

      【讨论】:

        【解决方案3】:

        如果您想提供可点击性,我建议使用 ImageButton 而不是 Button

        如果你使用ImageButton,你可以使用下面的代码来设置图片资源

        imageView.setBackgroundResource(R.drawable.your_drawable);
        

        对于图形,我建议使用矢量而不是图像。

        Vector Asset Studio Tutorial

        【讨论】:

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