个人项目实践

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

2017-07-03  本文已影响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>
上一篇 下一篇

猜你喜欢

热点阅读