开发者社区> 问答> 正文

如何通过单击图像按钮但图像按钮本身保持在其原始位置来随机放置按钮?

我在Android Studio中遇到问题。我想要的效果如下:

案例:单击图像按钮时,一些按钮会随机更改其位置和位置。所有按钮都位于风景屏幕的上半部分,并且允许它们仅在风景屏幕的上半部分而不是下半部分的屏幕上随机更改其位置。它们彼此不重叠。单击图像按钮后,所有按钮均会随机更改其位置,但图像按钮本身仍保持其原始位置。

希望你能帮助我。提前致谢!

主要活动代码:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_keyboard);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

Button buttons[] = new Button[5];
text = (TextView) findViewById(R.id.txt);
buttons[0] = (Button) findViewById(R.id.bt1);
buttons[0].setOnClickListener(this);
buttons[1] = (Button) findViewById(R.id.bt2);
buttons[1].setOnClickListener(this);
buttons[2] = (Button) findViewById(R.id.bt3);
buttons[2].setOnClickListener(this);
buttons[3] = (Button) findViewById(R.id.bt4);
buttons[3].setOnClickListener(this);
buttons[4] = (Button) findViewById(R.id.bt5);
buttons[4].setOnClickListener(this);
Imgbtn = (ImageButton) findViewById(R.id.Imgbtn);

}
@Override
public void onClick(View v) {
Random rand = new Random();
    View decorView = getWindow().getDecorView();
    int screenWidth = decorView.getWidth();
    int screenHeight = decorView.getHeight();
    v.setX(rand.nextInt(screenWidth - v.getWidth()));
    v.setY(rand.nextInt(screenHeight - v.getHeight()));}


Imgbtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if(text.getText().toString().equals("COC")){
            LayoutInflater li = getLayoutInflater();
            View layout = li.inflate(R.layout.correct_toast, (ViewGroup) 
findViewById(R.id.correct_toast_layout_id));
            Toast toast = new Toast(getApplicationContext());
            toast.setView(layout);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setView(layout);//setting the view of custom correct_toast layout
            toast.show();
            MediaPlayer ring= MediaPlayer.create(getApplicationContext(),R.raw.correct);
            ring.start();
        }else{
            LayoutInflater li = getLayoutInflater();
            View layout = li.inflate(R.layout.wrong_toast, (ViewGroup) findViewById(R.id.wrong_toast_layout_id));
            Toast toast = new Toast(getApplicationContext());
            toast.setView(layout);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setView(layout);//setting the view of custom correct_toast layout
            toast.show();
            MediaPlayer ring= MediaPlayer.create(getApplicationContext(),R.raw.wrong);
            ring.start();
        }
    }
});

展开
收起
几许相思几点泪 2019-12-05 15:49:13 351 0
0 条回答
写回答
取消 提交回答
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载