adb shell 을 통한 명령어 실행하기

프로그래밍/ANDROID|2020. 11. 27. 09:41
반응형

public class MainActivity extends Activity {


    TextView tv;


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        tv=(TextView)findViewById(R.id.cmdOp);

        tv.setText("Output :"+"\n"+runAsRoot());

    }


    public String runAsRoot() {


        try {

            // Executes the command.

            Process process = Runtime.getRuntime().exec("ls -l");


            // Reads stdout.

            // NOTE: You can write to stdin of the command using

            //       process.getOutputStream().

            BufferedReader reader = new BufferedReader(

                    new InputStreamReader(process.getInputStream()));


            int read;

            char[] buffer = new char[4096];

            StringBuffer output = new StringBuffer();

            while ((read = reader.read(buffer)) > 0) {

                output.append(buffer, 0, read);

            }

            reader.close();


            // Waits for the command to finish.

            process.waitFor();


            return output.toString();

        } catch (IOException e) {

            throw new RuntimeException(e);

        } catch (InterruptedException e) {

            throw new RuntimeException(e);

        }

    }

}



[출처] https://stackoverflow.com/questions/23608005/execute-shell-commands-and-get-output-in-a-textview


하지만 위와 같은 경우 ping 명령을 실행하면 (예 : -c 3 옵션으로 3번만 시도) 진행 과정이 실시간으로 출력되지 않고 시간이 걸려 모든 결과가 출력되면 화면에 보이게 됩니다.





반응형

댓글()

안드로이드 맥어드레스 (MAC Address) 정보 가져오기

프로그래밍/ANDROID|2020. 11. 26. 15:42
반응형

아래 코드는 onCreateView 와 동일 레벨에 작성합니다.

그리고 onCreateView 내에서 String str = getMacAddr(); 과 같이 불러오면 끝.



public static String getMacAddr() {

    try {

        List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());

        for (NetworkInterface nif : all) {

            if (!nif.getName().equalsIgnoreCase("wlan0")) continue;


            byte[] macBytes = nif.getHardwareAddress();

            if (macBytes == null) {

                return "";

            }


            StringBuilder res1 = new StringBuilder();

            for (byte b : macBytes) {

                res1.append(String.format("%02X:",b));

            }


            if (res1.length() > 0) {

                res1.deleteCharAt(res1.length() - 1);

            }

            return res1.toString();

        }

    } catch (Exception ex) {

    }

    return "02:00:00:00:00:00";

}



[출처] https://stackoverflow.com/questions/11705906/programmatically-getting-the-mac-of-an-android-device

반응형

댓글()

ViewPager2 와 Fragments 를 이용한 탭메뉴 (AndroidX)

프로그래밍/ANDROID|2020. 11. 26. 12:45
반응형

[출처]  http://www.tutorialsface.com/2020/07/android-tablayout-example-using-viewpager2-and-fragments-with-latest-android-api-androidx/


In this tutorial we are going to create 3 Tabs .Every tab have its own Fragment to control over screen. Also user can swipe between 3 tabs.

we are using AndroidX support Library , ViewPager2 and 3 different fragment & 3 different xml for layouts. And TabLayout for Tabs.

Layout Demonstration :

  • Checkout the following pic which explains the complete overview of layout architecture. Basically we are using ViewPager as main layout and for individual pager views we use Fragments. The tabs are part of Action Bar.

STEP 1: CREATING PROJECT

  • Let’s start with creating new project in android studio with package name com.example.manualSliding and class name MainActivity.java and its layout name is activity_main.xml.

STEP 2: ADDING DEPENDENCIES

  • open file Gradle Scripts/build.gradle(Module: app)
  • under dependencies{ } add this:
dependencies {
   
    //this is for ViewPager
    implementation "androidx.viewpager2:viewpager2:1.0.0"
    
    //this is for TabLayout
    implementation 'com.google.android.material:material:1.2.0-alpha01'

}
  • under compileOptions{} add this:
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}

STEP 3: EDIT app/res/values/colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#0698bc</color>
<color name="colorPrimaryDark">#067d9b</color>
<color name="colorAccent">#FF4081</color>
<color name="frg1Color">#FEBE29</color>
<color name="frg2Color">#3395FF</color>
<color name="frg3Color">#F6437B</color>
<color name="txtBGColor">#9FA8DA</color>
<color name="white">#FFFFFF</color>
</resources>

STEP 4: EDIT app/res/values/styles.xml : we using this theme because TabLayout component works in this theme.

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

</resources>

STEP 6: CREATING LAYOUT FOR EACH FRAGMENT :

  • create new xml layout file under app/res/layout/first_frag.xml and add the below code:
<?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:id="@+id/cLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/frg1Color">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="356dp"
android:text="sample text 1"
android:textSize="25dp"
android:textStyle="bold"
android:textColor="@color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
  • create new xml layout file under app/res/layout/second_frag.xml and add the below code:
<?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:id="@+id/cLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/frg2Color">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="356dp"
android:text="sample text 2"
android:textSize="25dp"
android:textStyle="bold"
android:textColor="@color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
  • create new xml layout file under app/res/layout/third_frag.xml and add the below code:
<?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:id="@+id/cLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/frg3Color">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="356dp"
android:textSize="25dp"
android:textStyle="bold"
android:text="sample text 3"
android:textColor="@color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

STEP 7: Create FRAGMENT CLASS for each view layout:

  • create new java class under app/java/com.example.manualSliding/FirstFragment.java
package com.example.manualsliding;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

public class FirstFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag, container, false);

TextView tv = (TextView) v.findViewById(R.id.textView1);
tv.setText(getArguments().getString("msg"));
return v;
}

public static FirstFragment newInstance(String text) {

FirstFragment f = new FirstFragment();
Bundle b = new Bundle();
b.putString("msg", text);

f.setArguments(b);

return f;
}
}
  • create new java class under app/java/com.example.manualSliding/SecondFragment.java
package com.example.manualsliding;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

public class SecondFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.second_frag, container, false);

TextView tv = (TextView) v.findViewById(R.id.textView1);
tv.setText(getArguments().getString("msg"));

return v;
}

public static SecondFragment newInstance(String text) {

SecondFragment f = new SecondFragment();
Bundle b = new Bundle();
b.putString("msg", text);

f.setArguments(b);

return f;
}
}
  • create new java class under app/java/com.example.manualSliding/ThirdFragment.java
package com.example.manualsliding;


import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

public class ThirdFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.third_frag, container, false);

        TextView tv = (TextView) v.findViewById(R.id.textView1);
        tv.setText(getArguments().getString("msg"));

        return v;
    }

    public static ThirdFragment newInstance(String text) {

        ThirdFragment  f = new ThirdFragment();
        Bundle b = new Bundle();
        b.putString("msg", text);

        f.setArguments(b);

        return f;
    }
}

STEP 8: app/res/layout/activity_main.xml : here we are creating TabLayout and ViewPager2.

<?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">

<com.google.android.material.tabs.TabLayout
android:id="@+id/tab_layout"
style="@style/Widget.MaterialComponents.TabLayout.Colored"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<androidx.viewpager2.widget.ViewPager2
android:id="@+id/mypager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />

</LinearLayout>

STEP 8: app/java/com.example.manualSliding/MainActivity.java

  • Here we use FragmentStateAdapter class for creating fragment and then we will assign it into Viewpager2.
  • create Strings array of tabs titles.
    • private String[] titles = new String[]{“Tab1”, “Tab2”, “Tab3”};
  • Inflating tab layout
    • TabLayout tabLayout =( TabLayout) findViewById(R.id.tab_layout);
  • Displaying tabs
    • new TabLayoutMediator(tabLayout, viewPager,(tab, position) -> tab.setText(titles[position])).attach();
  • complete code of MainActivity.java
package com.example.manualsliding;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

public class MainActivity extends AppCompatActivity {
private static final int NUM_PAGES = 3;
//The pager widget, which handles animation and allows swiping horizontally to access previous and next wizard steps.
 public static ViewPager2 viewPager;
// The pager adapter, which provides the pages to the view pager widget.
 private FragmentStateAdapter pagerAdapter;
// Arrey of strings FOR TABS TITLES
 private String[] titles = new String[]{"Tab1", "Tab2", "Tab3"};
// tab titles
 @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = findViewById(R.id.mypager);
pagerAdapter = new MyPagerAdapter(this);
viewPager.setAdapter(pagerAdapter);
//inflating tab layout
 TabLayout tabLayout =( TabLayout) findViewById(R.id.tab_layout);
//displaying tabs
 new TabLayoutMediator(tabLayout, viewPager,(tab, position) -> tab.setText(titles[position])).attach();
}

private class MyPagerAdapter extends FragmentStateAdapter {

public MyPagerAdapter(FragmentActivity fa) {
super(fa);
}


@Override
public Fragment createFragment(int pos) {
switch (pos) {
case 0: {
return FirstFragment.newInstance("fragment 1");
}
case 1: {

return SecondFragment.newInstance("fragment 2");
}
case 2: {
return ThirdFragment.newInstance("fragment 3");
}
default:
return FirstFragment.newInstance("fragment 1, Default");
}
}

@Override
public int getItemCount() {
return NUM_PAGES;
}
}


@Override
public void onBackPressed() {
if (viewPager.getCurrentItem() == 0) {
// If the user is currently looking at the first step, allow the system to handle the
 // Back button. This calls finish() on this activity and pops the back stack.d
 super.onBackPressed();
} else {
// Otherwise, select the previous step.
 viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
}
}

}


[출처]  http://www.tutorialsface.com/2020/07/android-tablayout-example-using-viewpager2-and-fragments-with-latest-android-api-androidx/


반응형

댓글()

리스트뷰 (listview) 구분선 제거

프로그래밍/ANDROID|2020. 7. 31. 16:57
반응형

자동으로 구분선이 생기므로 아래 옵션을 이용해 없애줍니다.


<ListView

    android:id="@+id/lv"

    android:dividerHeight="0px"

    android:divider="#FFFFFF" />



반응형

댓글()

안드로이드 상태바 없애기 (시계, 알림 아이콘 부분)

프로그래밍/ANDROID|2020. 7. 24. 09:42
반응형
안드로이드 상태바를 없애 화면을 좀 더 넓어 보이게 할 수 있습니다.

// 상태바 없애기 (안드로이드 상단 시간, 알림 아이콘 부분)
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
WindowManager.LayoutParams.FLAG_FULLSCREEN);

setContentView(R.layout.activity_main); // 이것 전에 사용해야 함




반응형

댓글()

구글맵 마커 사이즈 조절하기

프로그래밍/ANDROID|2020. 5. 4. 14:19
반응형

int height = 200;

int width = 200;

BitmapDrawable bitmapdraw=(BitmapDrawable)getResources().getDrawable(R.mipmap.marker);

Bitmap b=bitmapdraw.getBitmap();

Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);


map.addMarker(new MarkerOptions()

                .position(POSITION)

                .title("Your title")

                .icon(BitmapDescriptorFactory.fromBitmap(smallMarker))

                );



[출처] https://stackoverflow.com/questions/14851641/change-marker-size-in-google-maps-api-v2 



반응형

댓글()

google map 에서 움직이는 마커 사용하기

프로그래밍/ANDROID|2020. 5. 4. 14:15
반응형

[출처] https://exceptionshub.com/rotate-marker-and-move-animation-on-map-like-uber-android-2.html


아래 소스는 출력된 마커를 터치하면 목적지까지 부드럽게 마커가 이동하는 소스입니다.

(녹색 부분 제외하면 터치 없이 실행 됩니다)

어렵게 구했습니다.. ㅜ.ㅜ

목적에 맞게 수정해서 사용하면 됩니다.



1. onCreate 에서


SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

mapFragment.getMapAsync(this);



2. onMapReady 에서


@Override

    public void onMapReady(final GoogleMap googleMap) {


        mMap = googleMap;


        final LatLng SomePos = new LatLng(37.52487, 126.92723); // 시작 지점


        try {

            googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); // 지도 타입

            googleMap.setMyLocationEnabled(true); // 내 위치 표시

            googleMap.setTrafficEnabled(false); // 교통정보 레이어

            googleMap.setIndoorEnabled(false); // 실내 지도 여부. 향후 normal 지도 유형에서만 지원 예정

            googleMap.setBuildingsEnabled(true); // 건물 표시

            googleMap.getUiSettings().setZoomControlsEnabled(true); // 줌 컨트롤러 표시 (확대, 축소)

            googleMap.moveCamera(CameraUpdateFactory.newLatLng(SomePos));

            googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder()

                    .target(googleMap.getCameraPosition().target)

                    .zoom(17)

                    .bearing(30) // 지도를 돌려서 보기 (각도)

                    .tilt(45) // 지도를 눞여서 보기 (각도)

                    .build()));


            // 마커 이미지 및 사이즈 변경

            int height = 200;

            int width = 200;

            BitmapDrawable bitmapdraw = (BitmapDrawable)getResources().getDrawable(R.drawable.img_marker);

            Bitmap b = bitmapdraw.getBitmap();

            Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);


            final Marker myMarker = googleMap.addMarker(new MarkerOptions()

                    .position(SomePos)

                    .icon(BitmapDescriptorFactory.fromBitmap(smallMarker))

                    .title("Hello world"));


            googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {

                @Override

                public boolean onMarkerClick(Marker arg0) {


                    final LatLng startPosition = myMarker.getPosition();

                    final LatLng finalPosition = new LatLng(37.62487, 127.02723); // 끝 지점

                    final Handler handler = new Handler();

                    final long start = SystemClock.uptimeMillis();

                    // AccelerateDecelerateInterpolator 는 마커 이동 유형 (움직이는 스타일)

                    //final Interpolator interpolator = new AccelerateDecelerateInterpolator();

                    final float durationInMs = 4000; // 이동 시간 (ms)


                    handler.post(new Runnable() {

                        long elapsed;

                        float t;


                        @Override

                        public void run() {

                            // Calculate progress using interpolator

                            elapsed = SystemClock.uptimeMillis() - start;

                            t = elapsed / durationInMs;


                            LatLng currentPosition = new LatLng(

                                    startPosition.latitude * (1 - t) + finalPosition.latitude * t,

                                    startPosition.longitude * (1 - t) + finalPosition.longitude * t);


                            myMarker.setPosition(currentPosition);


                            // Repeat till progress is complete.

                            if (t < 1) {

                                // Post again 16ms later.

                                handler.postDelayed(this, 16);

                            }

                        }

                    });

                    return true;

                }

            });


        } catch (Exception e) {

            e.printStackTrace();

        }


    } 



반응형

댓글()

슬라이드 레이어 만들기 (AndroidSlidingUpPanel 라이브러리)

프로그래밍/ANDROID|2020. 4. 28. 07:36
반응형

소스 출처 및 라이브러리 배포

https://github.com/umano/AndroidSlidingUpPanel



activity_main.xml


<com.sothree.slidinguppanel.SlidingUpPanelLayout

        xmlns:sothree="http://schemas.android.com/apk/res-auto"

        android:id="@+id/sliding_layout"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:gravity="bottom"

        sothree:umanoPanelHeight="68dp"

        sothree:umanoShadowHeight="4dp">


       <!-- 메인 화면 -->

        <TextView

            android:layout_width="match_parent"

            android:layout_height="match_parent"

            android:gravity="center"

            android:text="Main Content"

            android:textSize="16sp" />


       <!-- 슬라이드 레이어 부분 -->

        <TextView

            android:layout_width="match_parent"

            android:layout_height="match_parent"

            android:gravity="center|top"

            android:text="The Awesome Sliding Up Panel"

            android:textSize="16sp" />


    </com.sothree.slidinguppanel.SlidingUpPanelLayout> 



MainActivity.java


        // 슬라이드 레이어

        SlidingUpPanelLayout slidingUpPanelLayout = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout);

        slidingUpPanelLayout.addPanelSlideListener(new SlidingUpPanelLayout.PanelSlideListener() {

            @Override

            public void onPanelSlide(View panel, float slideOffset) {


            }


            @Override

            public void onPanelStateChanged(View panel, SlidingUpPanelLayout.PanelState previousState, SlidingUpPanelLayout.PanelState newState) {

            //Toast.makeText(getApplicationContext(),newState.name().toString(),Toast.LENGTH_SHORT).show();


                if(newState.name().toString().equalsIgnoreCase("Collapsed")){


                    // 닫혔을때 처리하는 부분


                }else if(newState.name().equalsIgnoreCase("Expanded")){


                    // 열렸을때 처리하는 부분


                }


            }

        }); 



반응형

댓글()

SQLite 에서 중복값 있으면 insert 건너뛰기

프로그래밍/ANDROID|2020. 1. 31. 16:25
반응형

방법1

INSERT OR IGNORE INTO favorite (no) VALUES 'str';



방법2

INSERT INTO favorite (no) SELECT 'str' WHERE NOT EXISTS (SELECT 1 FROM favorite WHERE no='str');



* str 은 데이터 입니다.




반응형

댓글()

그라데이션 테두리 있는 버튼 만들기

프로그래밍/ANDROID|2020. 1. 28. 12:14
반응형

drawable/bg.xml


<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >


    <item>

        <shape android:shape="rectangle" >

            <gradient

                android:angle="45"

                android:centerColor="@android:color/holo_blue_bright"

                android:endColor="@android:color/holo_red_light"

                android:startColor="@android:color/holo_green_light" />

            <corners android:radius="7dp" />

        </shape>

    </item>


    <item

        android:bottom="5dp"

        android:left="5dp"

        android:right="5dp"

        android:top="5dp">

        <shape android:shape="rectangle" >

            <solid android:color="#ffffff" />

            <corners android:radius="7dp" />

        </shape>

    </item>


</layer-list> 



[출처] https://stackoverflow.com/questions/20870853/android-shape-border-with-gradient

반응형

댓글()

플로팅 액션 버튼 (Floating Action Button)

프로그래밍/ANDROID|2020. 1. 22. 11:33
반응형

In previous post, I had talked about some popular designs of Floating Action Button (FAB) - a component of Design Support Library. Beside that, there is a design from Inbox application (developed by Google) which containing some FABs are combined into a group and they will be shown after the "representative button" clicked. This design called Floating Action Menu:

    Up to now, there is no official component from Google which allows us making this design so we must use third-party library to building a Floating Action Menu (FAM). Fortunately, libraries to resolve this problem is not unpopular!
    In this post, I will use a third-party developed by Dmytro Tarianyk Clans. It's very simple to implement and solving this problem quickly!
    DEMO VIDEO:

 

 

Import the library

    Adding this dependency to your application level build.gradle:
dependencies { compile 'com.github.clans:fab:1.6.4' }     Now, we have two objects called FloatingActionMenu and FloatingActionButton to build this layout.

Some important features

   FloatingActionMenu has some attributes in xml that we have to pay attention:

  • fab:menu_fab_label: Label for Menu button
  • fab_colorNormal, fab_colorPressed, fab_colorRipple: Change button color based on it's status.
  • fab_showAnimation, fab_hideAnimation: Animation when menu expand/collapse.
  • menu_labels_position: Position of buttons label (left/right).
  • menu_openDirection: Open menu up or down.

Usages in activity

Declaring a layout for our activity like this:

activity_main.xml

 

    <com.github.clans.fab.FloatingActionMenu
        android:id="@+id/fab_menu"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:paddingBottom="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        fab:menu_backgroundColor="#ccffffff"
        fab:menu_fab_label="Choose an action"
        fab:fab_colorNormal="#DA4336"
        fab:fab_colorPressed="#E75043"
        fab:fab_colorRipple="#99FFFFFF"
        fab:fab_showShadow="true"
        fab:menu_labels_colorNormal="#333333"
        fab:menu_labels_colorPressed="#444444"
        fab:menu_labels_colorRipple="#66FFFFFF"
        fab:menu_labels_showShadow="true"
        fab:menu_labels_maxLines="-1"
        fab:menu_labels_position="left"
        fab:menu_openDirection="up"
        fab:fab_shadowColor="#66000000"
        fab:menu_labels_ellipsize="end"
        fab:menu_labels_singleLine="true">

        <com.github.clans.fab.FloatingActionButton
            android:id="@+id/fab1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@android:drawable/ic_menu_edit"
            fab:fab_label="Edit an item"
            fab:fab_size="mini" />

        <com.github.clans.fab.FloatingActionButton
            android:id="@+id/fab2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@android:drawable/ic_menu_add"
            fab:fab_label="Menu item 2"
            fab:fab_size="mini" />

        <com.github.clans.fab.FloatingActionButton
            android:id="@+id/fab3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@android:drawable/ic_menu_delete"
            fab:fab_label="@string/lorem_ipsum"
            fab:fab_size="mini" />

    </com.github.clans.fab.FloatingActionMenu>

 


MainActivity.java

 

package info.devexchanges.floatingactionmenu;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;

public class MainActivity extends AppCompatActivity {

    private FloatingActionMenu fam;
    private FloatingActionButton fabEdit, fabDelete, fabAdd;

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

        fabAdd = (FloatingActionButton) findViewById(R.id.fab2);
        fabDelete = (FloatingActionButton) findViewById(R.id.fab3);
        fabEdit = (FloatingActionButton) findViewById(R.id.fab1);
        fam = (FloatingActionMenu) findViewById(R.id.fab_menu);

        //handling menu status (open or close)
        fam.setOnMenuToggleListener(new FloatingActionMenu.OnMenuToggleListener() {
            @Override
            public void onMenuToggle(boolean opened) {
                if (opened) {
                    showToast("Menu is opened");
                } else {
                    showToast("Menu is closed");
                }
            }
        });

        //handling each floating action button clicked
        fabDelete.setOnClickListener(onButtonClick());
        fabEdit.setOnClickListener(onButtonClick());
        fabAdd.setOnClickListener(onButtonClick());

        fam.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (fam.isOpened()) {
                    fam.close(true);
                }
            }
        });
    }

    private View.OnClickListener onButtonClick() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view == fabAdd) {
                    showToast("Button Add clicked");
                } else if (view == fabDelete) {
                    showToast("Button Delete clicked");
                } else {
                    showToast("Button Edit clicked");
                }
                fam.close(true);
            }
        };
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}

 

 

    Running application, we'll have this output:

    Click the "representative button" to open Menu:

    After click the "delete button" in Menu:

    Animation for expanding/collapsing process:

 

Conclusions

    As you can see, with a small third-party library, we can build a FAM easily. By searching on Internet, you can find out another similar libraries:

    You should try to use them and choose the best one!
    Reference to the libary Github page: https://github.com/Clans/FloatingActionButton

 View project on Github

 

 

[출처] http://www.devexchanges.info/2016/07/floating-action-menu-in-android.html

반응형

댓글()