Android 는 Flexbox Layout 를 이용 하여 유동 레이아웃 을 쉽게 구현 합 니 다.

머리말
예전 에 우 리 는 유동성 구 조 를 실현 해 야 했 고 번 거 로 웠 습 니 다.구 글 은 Flexbox Layout 라 는 프로젝트 를 개 원 했 습 니 다.모두 가 낯 설 지 않 을 것 이 라 고 믿 습 니 다.다음은 Flexbox Layout 기초 지식 을 배우 고 하나의 사례 를 통 해 이 해 를 깊이 있 게 하 겠 습 니 다.Flexbox Layout 에 대해 잘 알 고 있다 면 본문 을 무시 하 십시오.
플 렉 스 박스
쉽게 말 하면 Flexbox 는 웹 전단 분야 의 CSS 에 속 하 는 레이아웃 방안 으로 2009 년 W3C 에서 새로운 레이아웃 방안 을 제 시 했 고 각종 페이지 레이아웃 을 응답 식 으로 실현 할 수 있 으 며 React Native 도 Flex 레이아웃 을 사용 했다.
Flexbox 는 CSS 분야 에서 Linearlayout 과 유사 한 레이아웃 이지 만 Linearlayout 보다 훨씬 강하 다 는 것 을 간단하게 이해 할 수 있다.
둘째, Flexbox Layout 가 뭐 예요?
우 리 는 안 드 로 이 드 개발 에서 Linearlayout+RelativeLayout 를 사용 하면 기본적으로 대부분의 복잡 한 레이아웃 을 실현 할 수 있 지만 구 글 은 Flexbox 와 같은 레이아웃 이 있 을 까?라 고 생각 했다.이것 은 하나의 구 조 를 사용 하면 각종 복잡 한 상황 을 해결 할 수 있 기 때문에 Flexbox Layout 는 이에 따라 생 겨 났 다.
그래서 Flexbox Layout 는 안 드 로 이 드 플랫폼 을 대상 으로 Flexbox 레이아웃 방안 과 유사 한 오픈 소스 프로젝트 입 니 다.
일단 공식 데모 의 효과 도 를 살 펴 보도 록 하 겠 습 니 다.

오픈 소스 주소:https://github.com/google/flexbox-layout
로 컬 다운로드:여 기 를 클릭 하 세 요.
3.사용 방식
사용 방식 은 간단 합 니 다.다음 의존 도 를 추가 하기 만 하면 됩 니 다.

compile 'com.google.android:flexbox:0.2.2'
xml 레이아웃 에서 이렇게 사용 할 수 있 습 니 다.

 <com.google.android.flexbox.FlexboxLayout
  android:id="@+id/flexbox_layout"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  app:flexWrap="wrap">
  <TextView
  android:id="@+id/tv1"
  android:layout_width="120dp"
  android:layout_height="80dp"
  app:layout_flexBasisPercent="50%" />
  <TextView
  android:id="@+id/tv2"
  android:layout_width="80dp"
  android:layout_height="80dp"
  app:layout_alignSelf="center"/>
  <TextView
  android:id="@+id/tv3"
  android:layout_width="160dp"
  android:layout_height="80dp"
  app:layout_alignSelf="flex_end"/>
 </com.google.android.flexbox.FlexboxLayout>
코드 에 서 는 이렇게 사용 할 수 있 습 니 다.

FlexboxLayout flexboxLayout = (FlexboxLayout) findViewById(R.id.flexbox_layout);
flexboxLayout.setFlexDirection(FlexboxLayout.FLEX_DIRECTION_COLUMN);
View view = flexboxLayout.getChildAt(0);
FlexboxLayout.LayoutParams lp = (FlexboxLayout.LayoutParams) view.getLayoutParams();
lp.order = -1;
lp.flexGrow = 2;
view.setLayoutParams(lp);
따라 할 포석 을 한번 볼 게 요.

다음은 우리 가 그것 을 실현 하고 최종 실현 의 효 과 를 살 펴 보 자.

실현 방법 은 다음 과 같다.
1.새 activityflow.xml 레이아웃

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
 <com.google.android.flexbox.FlexboxLayout
  android:id="@+id/flexbox_layout"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  app:flexWrap="wrap" />
</RelativeLayout>
레이아웃 이 간단 합 니 다.Flexbox Layout 만 있 습 니 다.동적 으로 아 이 템 을 만들어 야 하기 때문에 TextView 를 고정 적 으로 씁 니 다.
2.새 ActivityFlow Activity,데이터 원본 채 우기

String[] tags = {"    ", "  ", "  ", "      ", "    ", "    ", "   ", "     ", "   ", "   ", "   ", "  ", "    ", "  ", "  ", "  ", "    ", "  ", "  "};
  flexboxLayout = (FlexboxLayout) findViewById(R.id.flexbox_layout);
  for (int i = 0; i < tags.length; i++) {
   Book model = new Book();
   model.setId(i);
   model.setName(tags[i]);
   flexboxLayout.addView(createNewFlexItemTextView(model));
  }
그 중에서 Book 은 하나의 실체 입 니 다.이것 은 관건 이 아니 라 createNewFlexItemTextView 방법 입 니 다.
플 렉 스 박스 레이아웃 의 플 렉 스 아 이 템 을 동적 으로 불 러 오고 플 렉 스 박스 레이아웃 의 아 이 템 이 클릭 이 벤트 를 지원 하도록 해 야 합 니 다.사용자 가 어떤 주 제 를 클릭 했 는 지 알 아야 하기 때 문 입 니 다.
createNewFlexItemTextView 방법 을 살 펴 보 겠 습 니 다.

/**
  *     TextView
  * @param book
  * @return
  */
 private TextView createNewFlexItemTextView(final Book book) {
  TextView textView = new TextView(this);
  textView.setGravity(Gravity.CENTER);
  textView.setText(book.getName());
  textView.setTextSize(12);
  textView.setTextColor(getResources().getColor(R.color.colorAccent));
  textView.setBackgroundResource(R.drawable.tag_states);
  textView.setTag(book.getId());
  textView.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    Log.e(TAG, book.getName());
   }
  });
  int padding = Util.dpToPixel(this, 4);
  int paddingLeftAndRight = Util.dpToPixel(this, 8);
  ViewCompat.setPaddingRelative(textView, paddingLeftAndRight, padding, paddingLeftAndRight, padding);
  FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(
    ViewGroup.LayoutParams.WRAP_CONTENT,
    ViewGroup.LayoutParams.WRAP_CONTENT);
  int margin = Util.dpToPixel(this, 6);
  int marginTop = Util.dpToPixel(this, 16);
  layoutParams.setMargins(margin, marginTop, margin, 0);
  textView.setLayoutParams(layoutParams);
  return textView;
 }
기타 도서 실체 와 Util 류 에 관 한 것 도 붙 여 주세요.
책 실체

public class Book {
 private int id;
 private String name;
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public Book() {
 }
}
Util 도구 클래스

public class Util {
 public static int pixelToDp(Context context, int pixel) {
  DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
  return pixel < 0 ? pixel : Math.round(pixel / displayMetrics.density);
 }
 public static int dpToPixel(Context context, int dp) {
  DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
  return dp < 0 ? dp : Math.round(dp * displayMetrics.density);
 }
}
이렇게 하면 유동 구조[Flexbox Layout]에 대해 우 리 는 완성 을 실현 할 수 있 습 니 다.매우 간단 하지 않 습 니까?
총결산
이상 은 안 드 로 이 드 가 유동 레이아웃(Flexbox Layout)을 쉽게 해결 하 는 데 관 한 모든 내용 입 니 다.본 논문 의 내용 이 안 드 로 이 드 개발 자 여러분 에 게 어느 정도 도움 이 되 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 댓 글 을 남 겨 주 셔 서 저희 에 대한 지원 에 감 사 드 립 니 다.

좋은 웹페이지 즐겨찾기