Android Studio 9일차

2021. 11. 11. 18:09Android Development

viewpager2활용

더보기

 

위 클래스랑 layout resource 파일생성

package com.example.test19;

public class DataPage {
    int color;
    String title;

    public int getColor() {
        return color;
    }

    public void setColor(int color) {
        this.color = color;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public DataPage(int color, String title) {
        this.color = color;
        this.title = title;
    }
}

Datapage

package com.example.test19;

import android.graphics.Color;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class ViewHolderPage extends RecyclerView.ViewHolder {
    private TextView tv_title;
    private LinearLayout ll_layout;
    DataPage data;

    public ViewHolderPage(@NonNull View itemView) {
        super(itemView);

        tv_title = itemView.findViewById(R.id.textView);
        ll_layout = itemView.findViewById(R.id.llayout);
    }

    public void onBind(DataPage data) {
        this.data = data;

        tv_title.setText(data.getTitle());
        tv_title.setTextColor(Color.WHITE);

        ll_layout.setBackgroundResource(data.getColor());
    }
}

ViewHolder

package com.example.test19;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class ViewPagerAdapter extends RecyclerView.Adapter<ViewHolderPage> {
    private ArrayList<DataPage> listData;

    ViewPagerAdapter(ArrayList<DataPage> data) {
        this.listData = data;
    }

    @NonNull
    @Override
    public ViewHolderPage onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        View view = LayoutInflater.from(context).inflate(R.layout.item_viewpager, parent, false);
        return new ViewHolderPage(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolderPage holder, int position) {
        if (holder instanceof ViewHolderPage) {
            ViewHolderPage viewHolder = (ViewHolderPage) holder;
            viewHolder.onBind(listData.get(position));
   Log.d("jaeho",listData.get(position).getTitle());

        }
    }

    @Override
    public int getItemCount() {
        return listData.size();
    }
}

ViewPagerAdapter

package com.example.test19;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Bundle;
import android.widget.Button;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ViewPager2 viewPager2;
    Button btnToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager2 = findViewById(R.id.viewPager2);
        btnToggle = findViewById(R.id.btToggle);

        ArrayList<DataPage> list = new ArrayList<>();
        list.add(new DataPage(android.R.color.black,"1 Page"));
        list.add(new DataPage(android.R.color.holo_red_light, "2 Page"));
        list.add(new DataPage(android.R.color.holo_green_dark, "3 Page"));
        list.add(new DataPage(android.R.color.holo_orange_dark, "4 Page"));
        list.add(new DataPage(android.R.color.holo_blue_light, "5 Page"));
        list.add(new DataPage(android.R.color.holo_blue_bright, "6 Page"));

        viewPager2.setAdapter(new ViewPagerAdapter(list));

        btnToggle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (viewPager2.getOrientation() == ViewPager2.ORIENTATION_VERTICAL) {
                    btnToggle.setText("가로로 슬라이드");
                    viewPager2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
                }else {
                    btnToggle.setText("세로로 슬라이드");
                    viewPager2.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
                }
            }
        });
    }
}

MainActivity

 


탭 레이아웃

더보기

 

탭 레이아웃 이용해서 배경화면 바꾸기

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:ignore="SpeakableTextPresentCheck" />

    <FrameLayout
        android:id="@+id/fr"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
package com.example.test20;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.google.android.material.tabs.TabLayout;

public class MainActivity extends AppCompatActivity
        implements TabLayout.OnTabSelectedListener {
    // 메인액티비티 자체에 OnTabSelectedListener 이벤트 추가.
    // 즉 메인액티비티가 탭 선택 이벤트에 반응.
    MyTabFragment myFrags[] = new MyTabFragment[3];

    // 객체 배열. 빈 공간.
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actionBar = getSupportActionBar();
        actionBar.hide();
        TabLayout tabs = findViewById(R.id.tabs);
        tabs.addTab(tabs.newTab().setText("음악별"));
        // 탭을 생성하면서 이름을 주고 그 탭을 탭 레이아웃에 추가.
        tabs.addTab(tabs.newTab().setText("가수별"));
        tabs.addTab(tabs.newTab().setText("앨범별"));
        //tabs.setOnTabSelectedListener(this); // deprecated
        tabs.addOnTabSelectedListener(this);
        // 아래 코드를 명시하지 않으면, 탭과 동떨어진 레이아웃이 표시됨.
        TabLayout.Tab tab = tabs.getTabAt(0);
        onTabSelected(tab);
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        MyTabFragment myTabFrag = null;
        if (myFrags[tab.getPosition()] == null) {
            myTabFrag = new MyTabFragment();
            Bundle data = new Bundle();
            data.putString("tabName", tab.getText().toString());
            // 번들에 탭이름 추가하기.
            myTabFrag.setArguments(data);
            myFrags[tab.getPosition()] = myTabFrag;
        } else
            myTabFrag = myFrags[tab.getPosition()];
        getSupportFragmentManager().beginTransaction().replace(R.id.fr,
                myTabFrag).commit();
        // 프레그먼트 관리자에 새로운 작업 시작. 기존 프레임 레이아웃을 생성된 프레그먼트로 대체.
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {
    }

    // 내부 클래스
    public static class MyTabFragment extends Fragment {
        String tabName;

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Bundle data = getArguments();
            // 앱 구동에 추가로 필요한 정보 (추가나 읽기가 쉬움), 키와 값의 쌍.
            tabName = data.getString("tabName");// value return
        }

        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater
                , @Nullable ViewGroup container, @Nullable Bundle
                                         savedInstanceState) {
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT);
            LinearLayout baseLayout = new LinearLayout(getActivity());
            baseLayout.setOrientation(LinearLayout.VERTICAL);
            baseLayout.setLayoutParams(params);
            if (tabName == "음악별")
                baseLayout.setBackgroundColor(Color.RED);
            if (tabName == "가수별")
                baseLayout.setBackgroundColor(Color.GREEN);
            if (tabName == "앨범별")
                baseLayout.setBackgroundColor(Color.BLUE);
            return baseLayout;
            // 프래그먼트를 호출하면, 탭 이름에 따라서 지정된 레이아웃을 반환.
        }
    }
}

viewfliper 이용해서 색 바꾸기

더보기

 

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context=".MainActivity">
 <LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:orientation="horizontal">
 <Button
 android:id="@+id/btPrev"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_weight="1"
 android:text="이전 화면" />
 <Button
 android:id="@+id/btNext"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_weight="1"
 android:text="다음 화면" />
 </LinearLayout>
 <ViewFlipper
 android:id="@+id/viewFlipper1"
 android:layout_width="match_parent"
 android:layout_height="match_parent">
 <LinearLayout
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="#00ff00"
 android:orientation="vertical"></LinearLayout>
 <LinearLayout
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="#0000ff"
 android:orientation="vertical"></LinearLayout>
 <LinearLayout
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="#ff0000"
 android:orientation="vertical"></LinearLayout>
 </ViewFlipper>
</LinearLayout>
public class MainActivity extends AppCompatActivity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 Button btPrev = findViewById(R.id.btPrev);
 Button btNext = findViewById(R.id.btNext);
 ViewFlipper vFlipper=findViewById(R.id.viewFlipper1);
 btPrev.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 vFlipper.showPrevious();
 }
 });
 btNext.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 vFlipper.showNext();
 }
 });
 }
}

 

간단 이미지뷰어 만들기

더보기
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

public class MyPictureView extends View {
    // 뷰는 화면에 보여지는 부분.
    String imagePath = null;

    public MyPictureView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // 보여지는 부분 그리기
        super.onDraw(canvas);
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            int centerX = (canvas.getWidth() - bitmap.getWidth()) / 2;
            int centerY = (canvas.getHeight() - bitmap.getHeight()) / 2;
            canvas.drawBitmap(bitmap, centerX, centerY, null);
            // 이미지 객체, 왼쪽 좌표, 위쪽에서 간격, 붓 모양.
            bitmap.recycle();
        }
    }
}

MyPictureView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context=".MainActivity" >
 <LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:orientation="horizontal">
 <Button
 android:id="@+id/button2"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_weight="1"
 android:text="Button" />
 <Button
 android:id="@+id/button"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_weight="1"
 android:text="Button" />
 </LinearLayout>
 <view
 android:id="@+id/view2"
 class="com.example.test16.MyPictureView"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_weight="1" />
</LinearLayout>

activity_main

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;

public class MainActivity extends AppCompatActivity {
    int curNum = 0;// index 는 0 부터 시작.
    String imageFname;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("간단 이미지 뷰어");
        // 휴대폰 소유자에게 권한 사용 확인.
        ActivityCompat.requestPermissions(this
                , new
                        String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}
                , MODE_PRIVATE);
        Button btNext = findViewById(R.id.btNext);
        Button btPrev = findViewById(R.id.btPrev);
        MyPictureView myPicture = findViewById(R.id.view2);
        File[] imageFiles = new
                File(Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/Pictures").listFiles();
        // 파일과 폴더 정보가 배열 형태로 리턴.
// for (File f1 : imageFiles) {
// Log.d("imageFiles", "f:" + f1.toString());
// }
        for (int i = 0; i < imageFiles.length; i++) {
            Log.d("imageFiles", "f[" + i + "] :" + imageFiles[i].toString());
        }
        imageFname = imageFiles[0].toString();
        // 왜 1 일까?
        myPicture.imagePath = imageFname;
// int curNum=1;
        btPrev.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (curNum <= 0) {// 1 이 아니라 0 으로 변경.
                    Toast.makeText(getApplicationContext(), "첫번째 그림입니다"
                            , Toast.LENGTH_SHORT)
                            .show();
                } else {
                    curNum--;
                    imageFname = imageFiles[curNum].toString();
                    myPicture.imagePath = imageFname;
                    myPicture.invalidate();
                    // 추출한 이미지 정보를 다 전달하고 메모리 비우기.
                    // 해당 뷰의 onDraw 호출.
                }
            }
        });
        btNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (curNum >= imageFiles.length - 1) {
                    Toast.makeText(getApplicationContext(), "마지막 그림입니다"
                            , Toast.LENGTH_SHORT)
                            .show();
                } else {
                    curNum++;
                    imageFname = imageFiles[curNum].toString();
                    myPicture.imagePath = imageFname;
                    myPicture.invalidate();
                }
            }
        });
    }
}

mainActivity


간단 그림판 만들기

더보기

 

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
        setContentView(new MyGraphicView(this));
    }

    private static class MyGraphicView extends View {
        public MyGraphicView(Context context) {
            super(context);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            Paint paint = new Paint();
            paint.setAntiAlias(true);// 계단 현상 제거
            paint.setColor(Color.GREEN);
            paint.setStrokeWidth(10);// 선 굵기
            canvas.drawLine(10, 10, 300, 10, paint);
            // 선 그리기
            paint.setColor(Color.BLUE);
            paint.setStrokeWidth(5);// 선 굵기
            canvas.drawLine(10, 30, 300, 30, paint);
            paint.setColor(Color.RED);
            paint.setStrokeWidth(0);
            // 도형은 테두리 선과 면색으로 구성
            paint.setStyle(Paint.Style.FILL);// 면색 채우기
            Rect rect1 = new Rect(10, 50, 10 + 100, 50 + 100);
            canvas.drawRect(rect1, paint);
            paint.setStyle(Paint.Style.STROKE);// 도형에서 테두리만 표시
            Rect rect2 = new Rect(130, 50, 130 + 100, 50 + 100);
            canvas.drawRect(rect2, paint);
            RectF rect3 = new RectF(250, 50, 250 + 100, 50 + 100);
            canvas.drawRoundRect(rect3, 10, 10, paint);
            // 타원형 사각형의 모서리 곡면 크기 지정.
            paint.setColor(Color.YELLOW);
            paint.setStrokeWidth(10);
            canvas.drawCircle(0, 0, 100, paint);
            // 원의 중심점위치 좌표와 원의 반지름
            paint.setStrokeWidth(5);
            paint.setColor(Color.BLUE);
            Path path1 = new Path();
            //import android.graphics.Path;
            path1.moveTo(10, 290);
            path1.lineTo(10 + 50, 290 + 50);
            path1.lineTo(10 + 100, 290);
            path1.lineTo(10 + 150, 290 + 50);
            path1.lineTo(10 + 200, 290);
            canvas.drawPath(path1, paint);
            paint.setStrokeWidth(0);
            paint.setTextSize(30);
            canvas.drawText("안드로이드", 10, 390, paint);
        }
    }
}

간단 그림판 2

더보기
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    final static int LINE = 1, CIRCLE = 2;
    // 상수
    static int curShape = LINE;// 현재 도형

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
        setContentView(new MyGraphicView(this));
        setTitle("간단 그림판");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, 1, 0, "선 그리기");
        menu.add(0, 2, 0, "원 그리기");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case 1:
                curShape = LINE; // 선
                return true;
            case 2:
                curShape = CIRCLE; // 원
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private static class MyGraphicView extends View {
        int startX = -1, startY = -1, stopX = -1, stopY = -1;

        // 좌표상 없는 값을 주고, 드래그시 실제 값으로 대체
        public MyGraphicView(Context context) {
            super(context);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    startX = (int) event.getX();
                    startY = (int) event.getY();
                    // 터치 다운시 시작 좌표 초기화
                    break;
                case MotionEvent.ACTION_MOVE:
                    // break none
                case MotionEvent.ACTION_UP:
                    stopX = (int) event.getX();
                    stopY = (int) event.getY();
                    this.invalidate();
                    break;
            }
            return true;
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            Paint paint = new Paint();
            paint.setAntiAlias(true);
            paint.setStrokeWidth(5);
            paint.setStyle(Paint.Style.STROKE);
            paint.setColor(Color.RED);
            switch (curShape) {
                case LINE:
                    canvas.drawLine(startX, startY, stopX, stopY, paint);
                    break;
                case CIRCLE:
                    // Constant expression required
                    int radius = (int) Math.sqrt(Math.pow(stopX - startX, 2)
                            + Math.pow(stopY - startY, 2));
                    canvas.drawCircle(startX, startY, radius, paint);
                    break;
            }
        }
    }
}



'Android Development' 카테고리의 다른 글

Android Studio 11일차  (0) 2021.11.15
Android Studio 10일차  (0) 2021.11.12
Android Studio 7일차  (0) 2021.11.09
Android Studio 6일차  (0) 2021.11.08
Android Studio 5일차  (0) 2021.11.05