从java创建UI到选项卡

1.java创建UI

public class JavaCreateViewActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FrameLayout frameLayout = new FrameLayout(this);
        frameLayout.setBackgroundResource(R.mipmap.bg);
        setContentView(frameLayout);

        TextView text = new TextView(this);
        text.setText("开始游戏");
        text.setTextSize(TypedValue.COMPLEX_UNIT_SP,18);
        text.setTextColor(Color.WHITE);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER;
        text.setLayoutParams(params);
        text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(JavaCreateViewActivity.this).setTitle("系统提示")
                        .setMessage("确定进入?")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(JavaCreateViewActivity.this,"确定",Toast.LENGTH_SHORT).show();
                                dialog.dismiss();
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(JavaCreateViewActivity.this,"取消",Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }
                }).show();
            }
        });

        frameLayout.addView(text);
    }
}

2.java和xml创建UI

布局:

<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/grid_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:rowCount="3"
    android:columnCount="4"
    android:padding="15dp">
</GridLayout>

java:

public class JavaAndXmlActivity extends AppCompatActivity {

    private ImageView[] img = new ImageView[12];
    private int[] imagePath = new int[]{
        R.mipmap.bg,R.mipmap.bg,R.mipmap.bg,R.mipmap.bg,
        R.mipmap.bg,R.mipmap.bg,R.mipmap.bg,R.mipmap.bg,
        R.mipmap.bg,R.mipmap.bg,R.mipmap.bg,R.mipmap.bg
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_java_and_xml);
        GridLayout layout = findViewById(R.id.grid_layout);
        for(int i = 0;i < imagePath.length;i++){
            img[i] = new ImageView(JavaAndXmlActivity.this);
            img[i].setImageResource(imagePath[i]);
            img[i].setPadding(2,2,2,2);
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(116, 68);
            img[i].setLayoutParams(params);
            layout.addView(img[i]);
        }
    }
}

3.自定义view

MyView.java:

public class MyView extends View {
    public float bitmapX;
    public float bitmapY;


    public MyView(Context context) {
        super(context);
        bitmapX = 220;
        bitmapY = 110;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.mipmap.toast_img);
        canvas.drawBitmap(bitmap,bitmapX,bitmapY,paint);
        if(bitmap.isRecycled()){
            bitmap.recycle();
        }
    }
}

activity:

  public class MyViewActivity extends AppCompatActivity {

        private FrameLayout frameLayout;
        private MyView myView;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_my_view);
              frameLayout = findViewById(R.id.framelayout);
              myView = new MyView(this);
              myView.setOnTouchListener(new View.OnTouchListener() {
              @Override
              public boolean onTouch(View v, MotionEvent event) {
                    myView.bitmapX = event.getX();
                    myView.bitmapY = event.getY();
                    myView.invalidate();
                    return true;
                }
            });

              frameLayout.addView(myView);
        }
    }

4.日期选择器

布局:

<?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"
    android:orientation="vertical"
    android:gravity="center">

    <DatePicker
        android:id="@+id/date_picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

activity:

public class DatePickerActivity extends AppCompatActivity {

    private int year,month,day;
    private DatePicker datePicker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_date_picker);
        datePicker = findViewById(R.id.date_picker);

        Calendar calendar = Calendar.getInstance();//获取日历对象实例
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH);
        day = calendar.get(Calendar.DAY_OF_MONTH);

        datePicker.init(year, month, day, new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                DatePickerActivity.this.year = year;
                DatePickerActivity.this.month = monthOfYear;
                DatePickerActivity.this.day = dayOfMonth;
                //月份默认从0开始
                ToastUtil.showMsg(DatePickerActivity.this,year+"年"+(month+1)+"月"+day+"日");
            }
        });
    }
}

5.时间选择器

布局:

<?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"
    android:orientation="vertical">

    <TimePicker
        android:id="@+id/time_picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

activity:

    TimePicker timePicker = findViewById(R.id.time_picker);
    //timePicker.setIs24HourView(true);//设置是否为24小时制
    timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
        @Override
        public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
            String str = hourOfDay+"时"+minute+"分";
            ToastUtil.showMsg(TimePickerActivity.this,str);
        }
    });

6.计时器

布局:

<?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"
    android:orientation="vertical">
    <Chronometer
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/chronometer"
        android:format="已用时间:%s"
        android:textColor="@color/colorAccent"
        android:gravity="center"/>
</LinearLayout>

activity:

    chronometer = findViewById(R.id.chronometer);
    chronometer.setBase(SystemClock.elapsedRealtime());    
    //chronometer.setFormat("两秒停止:%s");设置显示格式
    chronometer.start();
    chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
        @Override
        public void onChronometerTick(Chronometer chronometer) {
            if(SystemClock.elapsedRealtime()-chronometer.getBase()>=2000){
                chronometer.stop();
            }
        }
    });

7.拖动条

布局:

<?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"
  android:orientation="vertical"
  android:background="#505050">

  <SeekBar
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/seekbar"
    android:max="255"
    android:progress="255"
    android:thumb="@mipmap/toast_img"/>
<!-- thumb设置拖动条的图标-->

  <ImageView
    android:id="@+id/img"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@mipmap/bg"
    android:scaleType="centerCrop"/>
</LinearLayout>

activity:

    seekBar = findViewById(R.id.seekbar);
    img = findViewById(R.id.img);

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            ToastUtil.showMsg(SeekBarActivity.this,"当前进度:"+progress);
            img.setImageAlpha(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            ToastUtil.showMsg(SeekBarActivity.this,"开始触摸");
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            ToastUtil.showMsg(SeekBarActivity.this,"停止触摸");
        }
    });
}

8.星级评分条

布局:

<RatingBar
    android:id="@+id/ratingbar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:numStars="5"    //设置星星数量
    android:rating="2"      //当前评分
    android:stepSize="1"//默认0.5,每次评分一颗
    android:isIndicator="false"/> //设置是否可评分,true则点击无反应

activity:

    ratingbar = findViewById(R.id.ratingbar);
    String rating = String.valueOf(ratingbar.getRating());
    ToastUtil.showMsg(this,"Rating:"+rating);
    String stepSize = String.valueOf(ratingbar.getStepSize());
    ToastUtil.showMsg(this,"stepSize:"+stepSize);
    String progress = String.valueOf(ratingbar.getProgress());
    ToastUtil.showMsg(this,"Progress:"+progress);

9.图像切换器

布局:

<ImageSwitcher
    android:id="@+id/image_switcher"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"/>

activity:

public class ImageSwitchActivity extends Activity {

    private ImageSwitcher imageSwitcher;
    private int[] arrayPic = new int[]{
            R.mipmap.bg,R.mipmap.bg2,R.mipmap.bg,R.mipmap.bg2,
            R.mipmap.bg,R.mipmap.bg2,R.mipmap.bg,R.mipmap.bg2,
            R.mipmap.bg,R.mipmap.bg2,R.mipmap.bg,R.mipmap.bg2
    };
    private int index = 0;//图片索引
    private float touchDownX; //手指按下的横坐标
    private float touchUpX; //手指抬起的横坐标
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_switch);
        //设置全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

        imageSwitcher = findViewById(R.id.image_switcher);
        imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,android.R.anim.slide_out_right));
        imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left));
        imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                ImageView imageView = new ImageView(ImageSwitchActivity.this);
//                imageView.setImageResource(R.mipmap.bg);
                imageView.setImageResource(arrayPic[index]);
                imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                return imageView;
            }
        });

        //实例
        imageSwitcher.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_DOWN){
                    touchDownX = event.getX();
                    return true;
                }else if(event.getAction() == MotionEvent.ACTION_UP){
                    touchUpX = event.getX();
                    //向右划
                    if(touchUpX - touchDownX > 100){
                        index = index == 0?arrayPic.length-1:index-1;
                        imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(ImageSwitchActivity.this,android.R.anim.slide_in_left));
                        imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(ImageSwitchActivity.this,android.R.anim.slide_out_right));
                        imageSwitcher.setImageResource(arrayPic[index]);
                      
                    }
                    //向左划
                    else if(touchDownX - touchUpX > 100){
                        index = index == arrayPic.length-1?0:index+1;
                        imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(ImageSwitchActivity.this,R.anim.slide_in_right));
                        imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(ImageSwitchActivity.this,R.anim.slide_out_left));
                        imageSwitcher.setImageResource(arrayPic[index]);
                    }
                    return true;
            }
            return true;
            }
        });
        //测试
        /*imageSwitcher.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((ImageSwitcher)v).setImageResource(R.mipmap.bg2);
            }
        });*/
    }
}

10.下拉列表

布局:

<Spinner
    android:id="@+id/spinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
    <!--android:entries="@array/ctype"/>   //通过布局设置下拉列表选项 --> 

arrays.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="ctype">
        <item>全部</item>
        <item>电影</item>
        <item>图书</item>
        <item>游戏</item>
    </string-array>
</resources>

activity:

    String[] ctype = new String[]{"全部","电影","音乐","体育"};

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,ctype);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinner = findViewById(R.id.spinner);
    spinner.setAdapter(adapter);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
          //ToastUtil.showMsg(SpinnerActivity.this,spinner.getSelectedItem().toString());
            ToastUtil.showMsg(SpinnerActivity.this,spinner.getItemAtPosition(position).toString());
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

11.选项卡

主页面布局:(再布局两个子页面,均放上一个imageview)

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <!-- 使用系统提供的id-->

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </LinearLayout>
</TabHost>

activity:

    TabHost tabHost = findViewById(android.R.id.tabhost);
    tabHost.setup();
    LayoutInflater inflater = LayoutInflater.from(this);
    inflater.inflate(R.layout.tab_1,tabHost.getTabContentView());
    inflater.inflate(R.layout.tab_2,tabHost.getTabContentView());
    tabHost.addTab(tabHost.newTabSpec("tab_1").setIndicator("选项1").setContent(R.id.tab1));
    tabHost.addTab(tabHost.newTabSpec("tab_2").setIndicator("选项2").setContent(R.id.tab2));
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1.什么是Activity?问的不太多,说点有深度的 四大组件之一,一般的,一个用户交互界面对应一个activit...
    JoonyLee阅读 5,867评论 2 51
  • Day1: 在代码中通过R.string.hello_world可以获得该字符串的引用; 在XML中通过@stri...
    冰凝雪国阅读 1,651评论 0 5
  • 一、简历准备 1、个人技能 (1)自定义控件、UI设计、常用动画特效 自定义控件 ①为什么要自定义控件? Andr...
    lucas777阅读 5,394评论 2 54
  • 1.下列哪些语句关于内存回收的说明是正确的? (b )A、 程序员必须创建一个线程来释放内存B、内存回收程序负责释...
    悠悠我心_4a00阅读 611评论 0 2
  • 「2017-07-08观影记录☞心灵捕手」 心灵捕手,谁是? 带着这样一个问题,我乔装成一个侦探,蹩脚的搜查,煞有...
    芮灵翾阅读 315评论 2 1

友情链接更多精彩内容