如何在android中以编程方式创建动态图像按钮设置文本

时间:2014-03-12 11:03:46

标签: android imagebutton

我正在创建一个应用程序,我需要在动态上添加imagebutton, 在那个图像按钮下我想设置一些文字。我尝试过发布代码,但我在L.addView(btn);发出异常 Plz建议......

 for (int i = 1; i <= SplashScreenActivity.num; i++)
 {

LinearLayout L = new LinearLayout(this);  
LayoutParams params_1 = new LayoutParams(241,137);
params_1.width=(int)(scaleX*241);
params_1.height=(int)(scaleY*137);
L.setLayoutParams(params_1);

ImageButton btn = new ImageButton(this);
File file= new File(Environment.getExternalStoragePublicDirectory("Android/data") + "/" + getApplicationContext().getPackageName()+"/CoverImages/skc_"+i+".jpg");
Bitmap bm = BitmapFactory.decodeFile(file.getPath());
btn.setImageBitmap(bm);
btn.setScaleType(ScaleType.FIT_XY);
btn.setBackgroundColor(80000000);

btn.setId(i);
 LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(241, 137);
layoutParams.width=(int)(scaleX*241);
layoutParams.height=(int)(scaleY*137);
layoutParams.setMargins(24, 0, 24, 0);

ll.addView(btn, layoutParams);
TextView tv = new TextView(this);  
tv.setGravity(Gravity.BOTTOM);  
tv.setTextColor(Color.BLUE);    
name = "purchased";
tv.setId(i);
tv.setText(name);  
L.setOrientation(LinearLayout.HORIZONTAL);  
btn.setMaxWidth(mButtonWidth);  
btn.setMaxHeight(mButtonHeight);  
L.addView(btn);  
L.addView(tv);  
ll .addView(L);
final int id_ = btn.getId();
btn = ((ImageButton) findViewById(id_));
btn.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) 
    {  

        utils.playTapSound();

        File myDirectory = new File(Environment.getExternalStoragePublicDirectory("Android/data") + "/" + getApplicationContext().getPackageName() + "/ComicBook/comic"+MainPage.get_id+"/skc"+MainPage.get_id+".zip");
        if(myDirectory.exists())
        {                                 
             Intent intent = new Intent(MainPage.this,
                FullScreenViewActivity.class);
                startActivityForResult(intent, 0);
        }
        else
        {
    startService(new Intent(getApplicationContext(), BillingService.class));
           Intent intent = new Intent(MainPage.this,InAppActivity.class);
           startActivityForResult(intent, 0);
        }               
    }
});

0 个答案:

没有答案