美文网首页个人项目实践
Android打开程序时随机显示TextView背景图片

Android打开程序时随机显示TextView背景图片

作者: 不知鸟 | 来源:发表于2017-07-03 20:27 被阅读0次

    MainActivity代码:

    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            TextView button = (TextView) findViewById(R.id.change_img_button);
    
            int array[] = { R.drawable.img1, R.drawable.img2, R.drawable.img3, R.drawable.img4,
                    R.drawable.img5, R.drawable.img6, R.drawable.img7, R.drawable.img8,
                    R.drawable.img9, R.drawable.img10, R.drawable.img11, R.drawable.img12 };
            Random rnd = new Random();
            int index = rnd.nextInt(11);
            Resources resources = getBaseContext().getResources();
            Drawable cur = resources.getDrawable(array[index]);
            button.setBackgroundDrawable(cur);
        }
    }
    

    XML

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
        <TextView
            android:id="@+id/change_img_button"
            android:layout_width="match_parent"
            android:layout_height="100dp" />
    </LinearLayout>
    

    相关文章

      网友评论

        本文标题:Android打开程序时随机显示TextView背景图片

        本文链接:https://www.haomeiwen.com/subject/iqmzcxtx.html