Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何仅使用Java编程(即不使用XML)创建ImageButton?_Java_Android_Eclipse_Android Studio_Imagebutton - Fatal编程技术网

如何仅使用Java编程(即不使用XML)创建ImageButton?

如何仅使用Java编程(即不使用XML)创建ImageButton?,java,android,eclipse,android-studio,imagebutton,Java,Android,Eclipse,Android Studio,Imagebutton,我一直在尝试通过Java创建ImageButtons,但是idk how,我只能在xml活动屏幕上完成。基本上,我希望一个新的ImageButton每秒出现在一个随机的位置,当单击时,每个ImageButton都会消失。你知道如何在Java上做到这一点吗?谢谢(顺便说一句,这是一款android应用程序) 我知道我必须导入android.widget.ImageButton 试试这个: 首先:找到要添加IB的视图组 例如: LinearLayout layout = (LinearLayout)

我一直在尝试通过Java创建ImageButtons,但是idk how,我只能在xml活动屏幕上完成。基本上,我希望一个新的ImageButton每秒出现在一个随机的位置,当单击时,每个ImageButton都会消失。你知道如何在Java上做到这一点吗?谢谢(顺便说一句,这是一款android应用程序)

我知道我必须导入android.widget.ImageButton

试试这个:

首先:找到要添加IB的视图组

例如:

LinearLayout layout = (LinearLayout) findViewById(R.id.mainlayout);
第二:创建并参数化IB

ImageButton ib = new ImageButton(this); //<-- this is the activity
ib.setImageResource(R.drawable.my_button_image);
ib.setLayoutParams(new LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
上下文对象可以是您的活动,在这种情况下,您应该将“this”作为参数传递(不带引号)。现在要让它出现在屏幕上,你应该像这样设置它的布局参数

LayoutParams params = new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
button.setLayoutParams(params);
现在你需要把按钮添加到屏幕上,你需要把它添加到你的主布局中,这样你就会有这样的东西

yourLayoutName.addView(button);

如何找到视图组?这就是我将IB放入的屏幕的xml文件吗?
LayoutParams params = new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
button.setLayoutParams(params);
yourLayoutName.addView(button);