MainActivity

public class MainActivity extends AppCompatActivity {


    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;
    private Button AButton;
    private Button BButton;
    ArrayList<Element> itemList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        addItem();
        switchFragment(Global.FRAGMENT_INDEX_A);
    }

    private void addItem() {
        itemList = new ArrayList<>();

        itemList.add(new Element("바나나", "500", "1", "바나나바나나바나나바나나"));
        itemList.add(new Element("사과", "400", "2", "사과사과사과사과사과사과"));
        itemList.add(new Element("배", "300", "3", "배배배배배배배"));
        itemList.add(new Element("키위", "200", "4", "키위키위키위키위키위"));
        itemList.add(new Element("아보카도", "100", "5", "아보카도아보카도아보카도아보카도아보카도"));
    }

    private void init() {
        AButton = findViewById(R.id.btn_fragmentA);
        BButton = findViewById(R.id.btn_fragmentB);
        //첫화면 프래그먼트A0
        AButton.setOnClickListener(onClick);
        BButton.setOnClickListener(onClick);
    }

    private View.OnClickListener onClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.equals(AButton)) {
                switchFragment(Global.FRAGMENT_INDEX_A);
            } else if (v.equals(BButton)) {
                switchFragment(Global.FRAGMENT_INDEX_B);
            }
        }
    };

    public void switchFragment(int index) {

        Fragment fragment = null;
        Bundle data = new Bundle();
        switch (index) {
            case Global.FRAGMENT_INDEX_A:
                fragment = new AFragment();
                data.putParcelableArrayList(Global.FRAGMENT_KEY_DATA_LIST, itemList);
                fragment.setArguments(data);

                break;
            case Global.FRAGMENT_INDEX_B:
                fragment = new BFragment();
                fragment.setArguments(data);
                break;
            default:
                break;
        }

        fragmentManager = getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.frameLayout, fragment).commitAllowingStateLoss();
    }


}

 FragmentManager와 FragmentTransaction을 사용합니다.

데이터 이동은 Bundle 을 통하시면 됩니다.

 

ListAdapter

public class ListAdapter extends BaseAdapter {
    // Adapter에 추가된 데이터를 저장하기 위한 ArrayList
    private ArrayList<Element> itemList = new ArrayList<Element>();
    private Context context;
    private View.OnClickListener onClickItem;

    // ListViewAdapter의 생성자
    public ListAdapter(Context context, ArrayList<Element> itemList, View.OnClickListener onClickItemName) {
        this.context = context;
        this.itemList = itemList;
        this.onClickItem = onClickItemName;
    }

    // Adapter에 사용되는 데이터의 개수를 리턴.
    @Override
    public int getCount() {
        return itemList.size();
    }

    // position에 위치한 데이터를 화면에 출력하는데 사용될 View를 리턴.
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View cView = convertView;
        ViewHolder holder;
        if (cView == null) {
            cView = LayoutInflater.from(context).inflate(R.layout.listview_custom, parent, false);
            holder = new ViewHolder();
            holder.nameText = cView.findViewById(R.id.nameText);
            holder.priceText = cView.findViewById(R.id.priceText);
            holder.sizeText = cView.findViewById(R.id.sizeText);
            cView.setTag(holder);

        } else {
            holder = (ViewHolder) cView.getTag();
        }

        Element item = itemList.get(position);
        holder.nameText.setText(item.getName());
        holder.sizeText.setText(item.getSize());
        holder.priceText.setText(item.getPrice());
        holder.nameText.setTag(item);
        holder.nameText.setOnClickListener(onClickItem);


        return cView;
    }

    // 지정한 위치(position)에 있는 데이터와 관계된 아이템(row)의 ID를 리턴
    @Override
    public long getItemId(int position) {
        return position;
    }

    // 지정한 위치(position)에 있는 데이터 리턴
    @Override
    public Object getItem(int position) {
        return itemList.get(position);
    }

    // 아이템 데이터 추가를 위한 함수.
 /*   public void addItem(String name, String size, String price, String info) {
        Element item = new Element(name, size, price, info);
        itemList.add(item);

        notifyDataSetChanged();
    }*/

    class ViewHolder {
        TextView nameText;
        TextView priceText;
        TextView sizeText;

    }
}

 

AFragment

public class AFragment extends Fragment {
    private ArrayList<Element> itemList = null;
    private ListView listView;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_a, container, false);

        itemList = getArguments().getParcelableArrayList(Global.FRAGMENT_KEY_DATA_LIST);

        init(view);

        return view;
    }

    private void init(View view) {
        listView = view.findViewById(R.id.listView);
        final ListAdapter adapter = new ListAdapter(getActivity(), itemList, onClickItemName);
        listView.setAdapter(adapter);


    }

    private View.OnClickListener onClickItemName = new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Element item = (Element) view.getTag();
            switchB(item);
        }
    };

    private void switchB(Element item){

        BFragment fragment = new BFragment();
        Bundle bundle = new Bundle();

        bundle.putParcelable(Global.FRAGMENT_KEY_DATA,item);
        fragment.setArguments(bundle);
        FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.frameLayout, fragment).commitAllowingStateLoss();
    }


}

 

BFragment

public class BFragment extends Fragment {

    private TextView nameText, priceText, sizeText, infoText;
    private Element item;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment_b, container, false);
        item = getArguments().getParcelable(Global.FRAGMENT_KEY_DATA);
        if (item != null) {
            String isName = item.getName();
            String isPrice =item.getPrice();
            String isSize = item.getSize();
            String isInfo = item.getInfo();

            Log.d("gg", "받은데이터 : 이름 : " + isName + " || 사이즈 : " + isSize + " || 가격 : " + isPrice + " || 정보 : " + isInfo);

            nameText = v.findViewById(R.id.name);
            sizeText = v.findViewById(R.id.size);
            priceText = v.findViewById(R.id.price);
            infoText = v.findViewById(R.id.info);

            nameText.setText(isName);
            sizeText.setText(isSize);
            priceText.setText(isPrice);
            infoText.setText(isInfo);

        }
        return v;
    }


}

 

Global -keyData,index

public class Global {
    public static final String FRAGMENT_KEY_DATA_LIST = "keyDataList";
    public static final String FRAGMENT_KEY_DATA = "keyData";
    public static final int FRAGMENT_INDEX_A = 0;
    public static final int FRAGMENT_INDEX_B = 1;
}

 

Element -객체,parcelable

public class Element implements Parcelable {
    private String name;
    private String price;
    private String size;
    private String info;

    public Element(String name, String price, String size, String info) {
        this.name = name;
        this.price = price;
        this.size = size;
        this.info = info;
    }

    protected Element(Parcel in) {
        name = in.readString();
        price = in.readString();
        size = in.readString();
        info = in.readString();
    }

    public static final Creator<Element> CREATOR = new Creator<Element>() {
        @Override
        public Element createFromParcel(Parcel in) {
            return new Element(in);
        }

        @Override
        public Element[] newArray(int size) {
            return new Element[size];
        }
    };

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getSize() {
        return size;
    }

    public void setSize(String size) {
        this.size = size;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(name);
        parcel.writeString(price);
        parcel.writeString(size);
        parcel.writeString(info);
    }
}

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@id/LinerLayout"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </FrameLayout>

    <LinearLayout
        android:id="@+id/LinerLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/frameLayout">

        <Button
            android:id="@+id/btn_fragmentA"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="A" />

        <Button
            android:id="@+id/btn_fragmentB"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="B" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

 

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

    <LinearLayout
        android:id="@+id/linearLayout3"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:orientation="horizontal">


        <TextView
            android:id="@+id/nameText"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:gravity="center"
            android:text="TextView" />

        <TextView
            android:id="@+id/sizeText"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginRight="10dp"
            android:gravity="center"
            android:text="TextView" />

        <TextView
            android:id="@+id/priceText"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginRight="10dp"
            android:gravity="center"
            android:text="TextView" />


    </LinearLayout>
</LinearLayout>

 

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

        <ListView
            android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

</LinearLayout>

 

fragment_b.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="150dp"
        android:text="과일"
        android:textColor="#2196F3"
        android:textSize="50sp"
        app:layout_constraintBottom_toTopOf="@id/frameLayout"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <LinearLayout
        android:id="@+id/frameLayout"
        android:layout_width="wrap_content"
        android:layout_height="600dp"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="50dp"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@id/name">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="크기 : "
                android:textSize="30sp" />

            <TextView
                android:id="@+id/size"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="리스트에서"
                android:textSize="30sp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="가격 : "
                android:textSize="30sp" />

            <TextView
                android:id="@+id/price"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="과일 클릭시"
                android:textSize="30sp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="정보 : "
                android:textSize="30sp" />

            <TextView
                android:id="@+id/info"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="정보가 표출"
                android:textSize="30sp" />
        </LinearLayout>

    </LinearLayout>


</androidx.constraintlayout.widget.ConstraintLayout>

 

결과 순서 ( MainActivity , 데이터 전달전 BFragment , 데이터 전달후 BFragment  -- 과일이름클릭시 이동)

 

AndroidManifest 

<uses-permission android:name="android.permission.INTERNET" /> -- 인터넷사용



<application

android:usesCleartextTraffic="true" -- 중요 안드로이드 http 프로토콜 접속 시 예외발생 조치

/>

 

build.gradle 

implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.google.code.gson:gson:2.8.5'

 

MainActivity .

public class MainActivity extends AppCompatActivity {

    private EditText id_EditText;
    private EditText password_EditText;
    private Button LoginBtn;

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

        LoginBtn.setOnClickListener(onClickListener);
    }


    private void init(){

        id_EditText = findViewById(R.id.id_EditText);
        password_EditText = findViewById(R.id.password_EditText);
        LoginBtn = findViewById(R.id.LoginBtn);
    }

    private View.OnClickListener onClickListener = new View.OnClickListener(){

        @Override
        public void onClick(View view) {
            //데이터 ->
            if(view.equals(LoginBtn)){
                Intent intent = new Intent(getApplicationContext(),ResultActivity.class);
                intent.putExtra("id",id_EditText.getText().toString());
                intent.putExtra("pw",password_EditText.getText().toString());
                startActivity(intent);
            }
        }
    };
}

 

 

ResultActivity

public class ResultActivity extends AppCompatActivity {

    private TextView Result_TextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        Intent intent = getIntent();
        String id = intent.getExtras().getString("id");
        String pw = intent.getExtras().getString("pw");
        init();

        RetrofitConnection connection = new RetrofitConnection();
        RetrofitInterFace retrofit = connection.getRetrofitConnection();
        retrofit.groupList(id, pw).enqueue(new Callback<Element>() {
            @Override
            public void onResponse(Call<Element> call, Response<Element> response) {

                if (response.isSuccessful()) {
                    setTextView(response.body());
                }

            }

            @Override
            public void onFailure(Call<Element> call, Throwable t) {
                Log.e("fail", t.toString());
            }
        });


    }

    private void setTextView(Element body) {
        Result_TextView.setText(body.getInfo().toString());
    }

    public void init() {
        Result_TextView = findViewById(R.id.Result_TextView);
    }


}

 

RetrofitConnection

public class RetrofitConnection {

    private static final String URL = "서버주소"; // 서버 API
    private static Retrofit retrofit = null;
    private static RetrofitInterFace retrofitInterFace = null;

    public RetrofitInterFace getRetrofitConnection() {
        if (retrofitInterFace == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(URL)
                    .addConverterFactory(GsonConverterFactory.create()) //json ->gson 
                    .build();
            retrofitInterFace = retrofit.create(RetrofitInterFace.class);
        }
        return retrofitInterFace;
    }
}

 

RetrofitInterFace

public interface RetrofitInterFace {


    @GET("/app/login")
    Call<Element> groupList(@Query("id") String id, @Query("pw") String pw);


}

 

-결과-

                                            정상적으로 데이터를 가져오는 모습입니다.

<?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:background="#101527"
    >

<RelativeLayout
    android:layout_width="600px"
    android:layout_height="300px">

    <SeekBar
        android:layout_centerInParent="true"
        android:id="@+id/seekbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="4"
        android:maxHeight="3.0dp"
        android:progress="1"
        android:background="@null"
        android:shape="oval"
        android:splitTrack="false"
        android:secondaryProgress="0"
        android:progressDrawable="@drawable/seeker_bar"
        android:thumb="@drawable/handler" />
    <RelativeLayout
        android:layout_width="400dp"
        android:layout_height="wrap_content"
        android:layout_below="@id/seekbar"
        android:layout_marginLeft="30px"
        android:layout_marginTop="-10px">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="0"
            android:textColor="#77838f"
            android:textSize="11sp"
            android:layout_marginTop="-6px" />
        <TextView
            android:layout_marginTop="-6px"
            android:layout_marginRight="30px"
            android:layout_alignParentRight="true"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="5"
            android:textColor="#77838f"
            android:textSize="11sp" />
    </RelativeLayout>
    <View
        android:id="@+id/Torque_map_DIV"
        style="@style/Divider3"
        android:layout_width="2dp"
        android:layout_height="5dp"
        android:layout_centerVertical="true"
        android:layout_marginLeft="174px"
        android:layout_marginTop="28px"
        android:layout_marginBottom="30px"
        android:background="@drawable/selector" />
    <View
        android:id="@+id/Torque_map_DIV2"
        style="@style/Divider3"
        android:layout_width="2dp"
        android:layout_height="5dp"
        android:layout_centerVertical="true"
        android:layout_marginLeft="296px"
        android:layout_marginTop="28px"
        android:layout_marginBottom="30px"
        android:background="@drawable/selector" />
    <View
        android:id="@+id/Torque_map_DIV3"
        style="@style/Divider3"
        android:layout_width="2dp"
        android:layout_height="5dp"
        android:layout_centerVertical="true"

        android:layout_marginLeft="418px"
        android:layout_marginTop="28px"
        android:layout_marginBottom="30px"
        android:background="@drawable/selector" />
</RelativeLayout>
</LinearLayout>

간단한 xml입니다. 

 

다음과같이 view가 seekbar 위에 걸쳐서 표시가 됩니다.

간단한 방법으로 위치를 조절할 수 있습니다.

 

public class Seekbar_view_progress extends Activity {
    public int number1;
    View view1,view2,view3;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.seekbar_view_progress);

       final SeekBar seekbar = (SeekBar) findViewById(R.id.seekbar);
        view1 = (View)findViewById(R.id.Torque_map_DIV);
        view2 = (View)findViewById(R.id.Torque_map_DIV2);
        view3 = (View)findViewById(R.id.Torque_map_DIV3);
        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //Seekbar의 상태(정도)가 변경되었을 때 실행될 사항
                progressNumber1();
                update();

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //Seekbar의 움직임이 시작될 때 실행될 사항

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //Seekbar의 움직임이 멈춘다면 실행될 사항

            }

            public void update() {
                if (seekbar.getProgress() == 1) {
                    seekbar.bringToFront();
                    view2.bringToFront();
                    view3.bringToFront();
                } else if (seekbar.getProgress() == 2) {
                    seekbar.bringToFront();
                    view1.bringToFront();
                    view3.bringToFront();
                } else if (seekbar.getProgress() == 3) {
                    seekbar.bringToFront();
                    view2.bringToFront();
                    view1.bringToFront();
                } else {
                    view1.bringToFront();
                    view2.bringToFront();
                    view3.bringToFront();
                }
                //  Log.d("updatenumber1",String.valueOf(seekbar_Torque_map.getProgress()==1));
            }

            public void progressNumber1() {
                number1 = seekbar.getProgress();
                //  Log.d("number1",String.valueOf(number1));
            }
        });
    }
}

시크바의 getProgress()를 이용해서 시크바 위치를 먼저 최상위로 지정해주고 다음 양쪽의 view들의 위치를 최상위로 바꿔줍니다 [ .bringToFront() ] 

 

view 위에 있어도 seekbar의 thumb가 젤 최상위로 위치했네요.

seekbar 다음 view를 최상위로 위치해준 이유는 프로그래스바와 시크바thumb가 동시에 움직이기 때문입니다.
다른 좋은 방법이 있는지 모르겠지만 간단한 방법으로 해결해봤습니다.

하지만 이것만으로 완벽히 시크바를 사용하기는 어렵습니다. 
객체를 통해 데이터를 담아오고 불러오는 과정에서 progress의 위치로 시작될 경우 초기 저장 값은 view가 보이더군요.

그 과정은 Handler().postDelayed() 를 통하여 view를 클리어한 후 다시 set 해주는 방법으로 해결했습니다.

 

public void viewclear(){
        //데이터 뷰에 적용하기
        seekbar.setProgress(0);
        
    }

다음과 같이 progress를 초기위치로 바꾸고 

 

   final ProgressDialog pd = ProgressDialog.show(MainScreen.this, "", "잠시 기다려주세요...");


        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                viewset();
                pd.dismiss();
            }
        },1000);

핸들러를 통하여 1초의 딜레이후 뷰를 셋 해주었습니다.

    public void viewset(){
        //데이터 뷰에 적용하기
        seekbar.setProgress(mMain_data.getAcceleration());
        }

저는 객체를 통하여 데이터를 sqlite와 의 데이터 전송을 위해 만들었기 때문에 해당 과정은 간단한 방법들만 적었습니다.

더 좋은 방법과 view를 seekbar와 통일할 수 있는 방법을 알려주실 분 환영합니다.

댓글이나 이메일로 부탁드려요~ 

안녕하세요 누누입니다.

안드로이드 xml 뷰를 만들다 보면 여러 가지 레이아웃을 사용하게 됩니다.

 

RelativeLayout은 (0,0)좌표에 중첩되어 쌓이는 뷰입니다.

최상위 부모나 id를 참조해서 특정 뷰의 상대적인 위치를 지정 가능합니다. 

 

layout_above    ~의 위에 배치하라

layout_below    ~의 밑에 배치하라

layout_toLeftOf  ~의 왼쪽에 배치하라

layout_toRightOf ~의 오른쪽에 배치하라 

layout_alignTop     ~와 위쪽 변을 맞춰라
layout_alignBottom ~와 밑쪽 변을 맞춰라
layout_alignLeft     ~와 왼쪽 변을 맞춰라
layout_alignRight    ~와 오른쪽 변을 맞춰라

layout_alignParentTop     true이면 부모와 위쪽 변을 맞춰라
layout_alignParentBottom true이면 부모와 밑쪽 변을 맞춰라
layout_alignParentLeft     true이면 부모와 왼쪽 변을 맞춰라
layout_alignParentRight    true이면 부모와 오른쪽 변을 맞춰라

layout_centerHorizontal true이면 부모의 수평 중앙에 배치하라
layout_centerVertical    true이면 부모의 수직 중앙에 배치하라
layout_centerInParent   true이면 부모의 수평, 수직 중앙에 배치하라

layout_alignParentLeft   true이면 부모의 왼쪽으로 붙여라

layout_alignParentRight    true 이면 부모의 오른쪽으로 붙여라 

 

등 자주 사용하는 속성입니다.

 

LinearLayout은 가로 또는 세로로 순차적으로 나열되는 레이아웃입니다.

android:orientation=""으로 가로 또는 세로로 설정이 가능합니다. 

LinearLayout은 레이아웃안의 뷰들의 면적이 조절 가능합니다.

 

<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:layout_marginTop="6.5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:textColor="#929292"
android:lineSpacingExtra="5sp"
android:text="사고차량"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:textColor="#333333"
android:lineSpacingExtra="2sp"
android:text="12가 1234"
/>
</LinearLayout>

<LinearLayout
android:orientation="vertical"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TextView
android:layout_marginTop="6.5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:textColor="#929292"
android:lineSpacingExtra="5sp"
android:text=android:text="사고차종종"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:textColor="#333333"
android:lineSpacingExtra="2sp"
android:text="제네시스 G90"
/>
</LinearLayout>

<LinearLayout
android:orientation="vertical"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TextView
android:layout_marginTop="6.5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:textColor="#929292"
android:lineSpacingExtra="5sp"
android:text="사고유형"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:textColor="#333333"
android:lineSpacingExtra="2sp"
android:text=android:text="잠금장치해제"
/>
</LinearLayout>

 

다음과 같이 3개의 레이아웃을 삼분할하여 분배가 가능합니다.

 

 

자주 사용하는 두 가지의 레이아웃을 소개해드렸습니다. 짧은 소개였지만 레이아웃 안에서의 화면 분할을 원하시면 LinearLayout을 상대적인 위치 값을 이용하고 싶으시면 RelativeLayout을 사용하시면 되겠습니다.

 

다들 즐 코딩하세요 ^^!

MainActivity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
public class MainActivity extends AppCompatActivity {
 
 
    Context mContext = null;
    ArrayList spinnerArray = new ArrayList<>();
    ArrayList listArray = new ArrayList<>();
    ArrayList<Element> element = new ArrayList<Element>();
    Spinner spinner;
    EditText name,age;
    TextView result;
    Handler mHandler;
    SpinKitView spin_kit;
    int count = 0;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final DBHelper dbHelper = new DBHelper(getApplicationContext(),"Board.db",null,1);
        final ArrayAdapter listAdapter = new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_list_item_1,listArray);
        final ListView listview = (ListView)findViewById(R.id.listview);
        final ToggleButton toggleButton = (ToggleButton)findViewById(R.id.toggleButton);
        mContext = this;
        spinner = (Spinner)findViewById(R.id.gender);
        name = (EditText) findViewById(R.id.name) ;
        age = (EditText) findViewById(R.id.age) ;
        result=(TextView)findViewById(R.id.result);
        spin_kit = (SpinKitView)findViewById(R.id.spin_kit);
        spin_kit.setVisibility(View.INVISIBLE);
        //스피너 리스트 목록
        spinnerArray.add("남자");
        spinnerArray.add("여자");
 
        //초기 EditText 데이터 넣기
        show(listAdapter,dbHelper,listview);
        name.setText(element.get(0).getName());
        age.setText(String.valueOf(element.get(0).getAge()));
        if(element.get(0).getGender().equals("남자") ){
            spinner.setSelection(0);
        }else{
            spinner.setSelection(1);
        }
 
        //토글버튼 리스너
        toggleButton.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View v) {
                if(toggleButton.isChecked()){
                    mHandler = new Handler(){
                        public void handleMessage(Message msg){
                            spin_kit.setVisibility(View.VISIBLE);
                            if(count<element.size()){
                                name.setText(element.get(count).getName());
                                age.setText(String.valueOf(element.get(count).getAge()));
                                if(element.get(count).getGender().equals("남자") ){
                                    spinner.setSelection(0);
                                }else{
                                    spinner.setSelection(1);
                                }
                                count++;
                                mHandler.sendEmptyMessageDelayed(0,5000);
                                Log.d("count : "String.valueOf(count) + "|" + element.size());
                            }
                            else{
                                count=0;
                                handleMessage(msg);
                            }
                        }
                    };
                    mHandler.sendEmptyMessage(0);
                }else{
                    spin_kit.setVisibility(View.INVISIBLE);
                    mHandler.removeMessages(0);
                    name.setText(element.get(0).getName());
                    age.setText(String.valueOf(element.get(0).getAge()));
                    if(element.get(0).getGender().equals("남자") ){
                        spinner.setSelection(0);
                    }else{
                        spinner.setSelection(1);
                    }
                }
            }
        });
 
 
        ArrayAdapter arrayAdapter = new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,spinnerArray);
        spinner.setAdapter(arrayAdapter);
 
        //전송버튼 클릭 리스너
        findViewById(R.id.submit).setOnClickListener(new Button.OnClickListener(){
            public void onClick(View view){
                String names = name.getText().toString();
                int ages = Integer.parseInt(age.getText().toString());
                String  genders = spinner.getSelectedItem().toString();
                dbHelper.insert(names,ages,genders);
                show(listAdapter,dbHelper,listview);
 
            }
     });
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
 
                @Override
                public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
                    dialogBuilder.setTitle(element.get(position).getName() + " | "+element.get(position).getAge() + " | "+element.get(position).getGender() + "\n");
                    dialogBuilder.setPositiveButton("지우기"new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dbHelper.delete(element.get(position).getNum());
                            show(listAdapter,dbHelper,listview);
                        }
                    });
                    dialogBuilder.setNegativeButton("선택하기"new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            name.setText(element.get(position).getName());
                            age.setText(String.valueOf(element.get(position).getAge()));
                            if(element.get(position).getGender().equals("남자") ){
                                spinner.setSelection(0);
                            }else{
                                spinner.setSelection(1);
                            }
                        }
                    });
                    dialogBuilder.show();
                }
            });
    }
 
 
    //셀렉트 보드 함수
    //뷰 변경사항 확인
    private void show(ArrayAdapter listAdapter,DBHelper dbHelper,ListView listview){
        listAdapter.clear();
        element.clear();
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM Board ORDER BY num DESC",null);
        if(cursor !=null){
            cursor.move(0);
            while(cursor.moveToNext()){
                int num = Integer.parseInt(cursor.getString(cursor.getColumnIndex("num")));
                String name = cursor.getString(cursor.getColumnIndex("name"));
                int age = Integer.parseInt(cursor.getString(cursor.getColumnIndex("age")));
                String gender = cursor.getString(cursor.getColumnIndex("gender"));
                //객체에 DB내용 담기
                element.add(new Element(num,name,age,gender));
            }
            listview.setAdapter(listAdapter);
            for(Element element : element){
                listAdapter.add(element.getNum() +" | " +element.getName()+ " | " +element.getAge()+ " | " +element.getGender()+"\n");
            }
            listAdapter.notifyDataSetChanged();
        }
    }
}
 
 


객체 Element 객체를 활용하여 getset

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public class Element implements Serializable {
 
    private int num;
    private String name;
    private int age;
    private String gender;
 
    public Element(int num,String name,int age,String gender){
        super();
        this.num =num;
        this.name = name;
        this.age = age;
        this. gender = gender;
    }
    public int getNum() {
        return num;
    }
 
    public void setNum(int num) {
        this.num = num;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public String getGender() {
        return gender;
    }
 
    public void setGender(String gender) {
        this.gender = gender;
    }
 
    @Override
    public String toString() {
        return "Element{" +
                "num=" + num +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                '}';
    }
}
 
 

DB HELPER 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
 
public class DBHelper extends SQLiteOpenHelper {
 
    // DBHelper 생성자로 관리할 DB 이름과 버전 정보를 받음
    public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }
 
    // DB를 새로 생성할 때 호출되는 함수
    @Override
    public void onCreate(SQLiteDatabase db) {
        // 새로운 테이블 생성
        /* 이름은 BOARD이고, 자동으로 값이 증가하는 num 정수형 기본키 컬럼과
        name 문자열 컬럼, age 정수형 컬럼, gender 문자열 컬럼으로 구성된 테이블을 생성. */
        db.execSQL("CREATE TABLE BOARD (num INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, gender TEXT);");
    }
 
    // DB 업그레이드를 위해 버전이 변경될 때 호출되는 함수
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 
    }
 
    public void insert(String name ,int age, String gender) {
        // 읽고 쓰기가 가능하게 DB 열기
        SQLiteDatabase db = getWritableDatabase();
        // DB에 입력한 값으로 행 추가
        db.execSQL("INSERT INTO BOARD VALUES(null, '" + name + "', " + age + ", '" + gender + "');");
        db.close();
    }
 
    public void update(String name, int age) {
        SQLiteDatabase db = getWritableDatabase();
        // 입력한 항목과 일치하는 행의 가격 정보 수정
        db.execSQL("UPDATE BOARD SET age=" + age + " WHERE name='" + name + "';");
        db.close();
    }
 
    public void delete(int num){
        SQLiteDatabase db = getWritableDatabase();
        // 입력한 항목과 일치하는 행의 가격 정보 수정
        db.execSQL("DELETE FROM BOARD WHERE num=" + num );
        db.close();
    }
 
 
 
    public String getResult() {
 
        // 읽기가 가능하게 DB 열기
        SQLiteDatabase db = getReadableDatabase();
        String result = "";
 
        // DB에 있는 데이터를 쉽게 처리하기 위해 Cursor를 사용하여 테이블에 있는 모든 데이터 출력
        Cursor cursor = db.rawQuery("SELECT * FROM BOARD"null);
        while (cursor.moveToNext()) {
 
 
            result += cursor.getString(cursor.getColumnIndex("num"))
                    + " | "
                    + cursor.getString(cursor.getColumnIndex("name"))
                    + " | "
                    + cursor.getString(cursor.getColumnIndex("age"))
                    + " | "
                    + cursor.getString(cursor.getColumnIndex("gender"))
                    + "\n";
 
           /* result += cursor.getString(0)
                    + " | "
                    + cursor.getString(1)
                    + " | "
                    + cursor.getInt(2)
                    + " | "
                    + cursor.getString(3)
                    + "\n";*/
        }
        cursor.close();
        return result;
    }
 
 
 

build.gradle github입니다.

아래의 추가해주세요.

1
2
3
4
5
6
7
8
9
10
11
12
13
repositories {
    maven {
        url  "http://dl.bintray.com/dodola/maven"
    }
}
 
dependencies {
    /*리스트뷰를 아래나 위로 당겼을때 발생하는 애니메이션입니다. (출렁거림)*/
    implementation 'com.dodola:listviewext:1.0'
    
    /*5초마다 발생하는 이벤트에 들어갈 spinkit입니다.*/
    implementation 'com.github.ybq:Android-SpinKit:1.2.0'
}
 
 

activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
<?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_gravity="right"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
 
    <ToggleButton
        android:id="@+id/toggleButton"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textOn="5초마다 바뀜"
        android:textOff="맨위에것만 바뀜"
       />
</LinearLayout>
    <!--Spin Kit-->
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/spin_kit"
        style="@style/SpinKitView.Large.Circle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        app:SpinKit_Color="@color/colorAccent" />
    <LinearLayout
        android:orientation="vertical"
        android:layout_marginTop="30dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
 
        <LinearLayout
            android:layout_gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
 
            <TextView
                android:textSize="20dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="이름 : "
                />
 
            <EditText
                android:id="@+id/name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="이름"
                />
        </LinearLayout>
        <LinearLayout
            android:layout_gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
 
            <TextView
                android:textSize="20dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="나이 : "
                />
 
            <EditText
                android:id="@+id/age"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="나이"
                />
        </LinearLayout>
        <LinearLayout
            android:layout_gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
 
            <TextView
                android:textSize="20dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="성별 : "
                />
 
            <Spinner
                android:id="@+id/gender"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
 
            </Spinner>
        </LinearLayout>
        <LinearLayout
            android:gravity="center"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
 
            <Button
                android:id="@+id/submit"
                android:text="전송하기"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
 
 
        </LinearLayout>
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
 
            <TextView
                android:id="@+id/result"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
 
                android:id="@+id/listview"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
 
            </com.dodola.listview.extlib.ListViewExt>
 
        </LinearLayout>
    </LinearLayout>
 
 
 
 
    </LinearLayout>
 
 
 

아직 정확한 사용법을 자세히 알지는 못하지만 연습하는 과정을 공유합니다. 
수정 부분이나 좀 더 효율적으로 사용하는 방법이 있으면 댓글 달아주세요.


안드로이드 기본인 로그인과 회원가입 페이지를 제작해 보겠습니다.

우선 기초적인 디자인과 인텐트 부분만 다뤄봤습니다.



준비물입니다.


2개의 클래스를 추가해주세요.



2개의 백그라운드 사진이 필요합니다.



2개의 xml이 필요합니다 각각 클래스에 연결됩니다.




먼저 xml 부분을 살펴보겠습니다.


android:background="@drawable/back3" 해당레이아웃에 background를 줍니다.

  <EditText 아이디 비밀번호는 EditText로 하였습니다.

android:inputType="textPassword"비밀번호는 type을 주어 비밀번호가 별모양으로 표시됩니다.

<android.support.v7.widget.AppCompatCheckBox 또한 유저의 편의성을 위해 자동로그인 버튼을 만들 예정입니다.

    <TextView 그리고 회원가입페이지로 이동할 텍스트뷰를 하나 만들어 줍니다.



디자인 이미지입니다.




회원가입 xml입니다.


<?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"
android:background="@drawable/back1">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="40dp"
android:text="다람월드 회원가입"
android:textColor="#000000"
android:textSize="30dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30dp"
android:layout_marginTop="30dp"
android:layout_marginBottom="30dp"
android:text="회원가입 페이지입니다."
android:layout_gravity="center"
android:textStyle="bold"
android:textColor="#000000"/>
<EditText
android:id="@+id/idText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:ems="10"
android:hint="아이디"
android:textColorHint="#000000"
android:textColor="#000000"
android:inputType="textPersonName" />

<EditText
android:id="@+id/passwordText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:ems="10"
android:hint="비밀번호"
android:textColorHint="#000000"
android:textColor="#000000"
android:inputType="textPassword" />



<Button
android:id="@+id/registerButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="회원가입" />
</LinearLayout>

  <EditText>저희가 필요한건 아이디와 패스워드이니 두가지의 EditText를 받아옵니다.



디자인 이미지입니다.


사진은 drawable파일에 사진을 복사해서 붙여넣기 해주시면 됩니다.


이제 class 파일을 살펴 보겠습니다.



로그인 메인입니다.


public class LoginMain extends Activity {

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


TextView id = (TextView)findViewById(R.id.Login_id);
TextView ps = (TextView)findViewById(R.id.Login_password);
Button button = (Button)findViewById(R.id.Login_Button);
CheckBox box = (CheckBox)findViewById(R.id.Auto_Login);
TextView register = (TextView)findViewById(R.id.Go_registerActivity);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(LoginMain.this,MainActivity.class);
startActivity(intent);
}
});

register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(LoginMain.this,LoginRegister.class);
startActivity(intent);
}
});
}
}


메인에 보면 버튼과 텍스트뷰에 하나씩 클릭 리스너를 넣어주었습니다.


버튼쪽은 로그인후 메인뷰로 이동하고 레지스터텍스는 회원가입 페이지로 이동합니다.



회원가입 레지스터입니다.


public class LoginRegister extends Activity {
SharedPreferences shard;
String LoginID = "LoginID";
String LoginPassword = "LoginPassword";

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

final TextView id = (TextView)findViewById(R.id.idText);
final TextView ps = (TextView)findViewById(R.id.passwordText);
Button button = (Button)findViewById(R.id.registerButton);



button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

Intent intent =new Intent(LoginRegister.this,LoginMain.class);

startActivity(intent);
}
});
}
}

간단합니다. 

회원가입후 로그인메인으로 다시 돌아갑니다.


이후에 데이터를 저장하고 조건을 체크하는 부분을 포스팅하겠습니다.


안녕하세요 이번에는 액션바 이미지 설정에 대해 글을 올립니다.

방법은 간단합니다.



values의 styles에 들어가줍니다.



style 의 액션바설정을 할 수있습니다. 





짜잔 ~ 파란색에서 고급스런 푸른빛으로 변경했습니다.







안녕하세요. 이번 포스팅은 오토스크롤 뷰페이저 입니다.

주로 광고사진을 넣거나 사진을 효율적으로 올리기 위해 사용합니다.




우선 결과물입니다. 한번 만들어 두면 여러곳에서 잘 사용할 수 있을거 같죠 ?


제가 사용한 뷰는 엑티비티 아래에 있는 프래그먼트입니다.


보여질 클래스에 연결된 xml부분 입니다.

<cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager
android:id="@+id/autoViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp">

</cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager>
manifest에 추가할 퍼미션입니다.

<uses-permission android:name="android.permission.INTERNET"/>





AutoScrollViewpager 를 사용하기 위해서 gradle에 추가해 줍시다.
 api ('cn.trinea.android.view.autoscrollviewpager:android-auto-scroll-view-pager:1.1.2') {
exclude module: 'support-v4'
}}
repositories {
mavenCentral()
google()}
annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'




AutoScrollAdapter 입니다.

public class AutoScrollAdapter extends PagerAdapter {

Context context;
ArrayList<String> data;

public AutoScrollAdapter(Context context, ArrayList<String> data) {
this.context = context;
this.data = data;
}

@Override
public Object instantiateItem(ViewGroup container, int position) {

//뷰페이지 슬라이딩 할 레이아웃 인플레이션
LayoutInflater inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.auto_viewpager,null);
ImageView image_container = (ImageView) v.findViewById(R.id.image_container);
Glide.with(context).load(data.get(position)).into(image_container);
container.addView(v);
return v;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {

container.removeView((View)object);

}

@Override
public int getCount() {
return data.size();
}

@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}















적용할 프래그먼트입니다.

다음과 같이 import 해주시고 

레이아웃을 연결해준뒤 ArrayList에 사용할 이미지를 연결해줍니다. 

해당레이아웃의 오토스크롤 뷰페이저를 연결해준후 어뎁터와 연결하여줍니다.

import cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager;

public class TabFragment3 extends Fragment {
AutoScrollViewPager autoScrollViewPager;
ArrayList<String>data =new ArrayList<>();

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.tab_fragment_3, container, false);
LinearLayout layout = (LinearLayout) v.findViewById(R.id.fragment_uri);

ArrayList<String> data = new ArrayList<>(); //이미지 url를 저장하는 arraylist
data.add("http://www.lotteria.com/Images/main/visual/page2/img_lpoint_event_181026.jpg");
data.add("http://www.burgerking.co.kr/Content/menu/image/main/181018_Product_PC_detail_5.png");
data.add("https://www.baskinrobbins.co.kr/upload/EditUpload/1541032533-99.png");
data.add("http://www.popeyes.co.kr/images/banner/burger_main_180607.png");


autoScrollViewPager = (AutoScrollViewPager)v.findViewById(R.id.autoViewPager);
AutoScrollAdapter scrollAdapter = new AutoScrollAdapter(getActivity(), data);
autoScrollViewPager.setAdapter(scrollAdapter); //Auto Viewpager에 Adapter 장착
autoScrollViewPager.setInterval(3000); // 페이지 넘어갈 시간 간격 설정
autoScrollViewPager.startAutoScroll(); //Auto Scroll 시작

return v;

}





}



+ Recent posts