2016-11-26 92 views
0

我已经创建了一个动态按钮来流行我的主要活动。 按钮正常工作。 但即时通讯设置图像背景。设置按钮背景图像大小(java代码)

我已经测试了一切,但img的结果是如此糟糕。

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

我已经测试了这一点,但东阳的getWidth不行给我errore> 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 

回答

0

公开赛在各种图像包项目展示和项目视图即:HDMI,xhdmi,xxhdmi等。把相同图像的不同大小的相同名称在xml中引用为可绘制/“图像名称”

0

您最好使用9补丁背景。在你的java文件 并设置背景一样

button.setBackground(your 9-patch);

tutorial for 9-Patch

0

,如果你想给可点击我会建议使用的ImageButton,而不是按钮

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

imageView.setBackgroundResource(R.drawable.your_drawable); 

对于图形,我会建议,而不是图像载体。

Vector Asset Studio Tutorial

Vector Asset Studio In Android Studio