LinearLayout을 버튼처럼 작동하게 만들기 보이도록 스타일을 지정 button했으며 몇 가지

나는. LinearLayout처럼 보이도록 스타일을 지정 button했으며 몇 가지 text / ImageView 요소가 포함되어 있습니다. 나는 전체를 만들고 싶다LinearLayout 행위를 button, 특히 눌렀을 때 다른 배경을 가지도록 정의 된 상태를 부여하기 위해.

ImageButton전체 레이아웃의 크기를 만들고 절대적으로 배치 하는 것보다 더 좋은 방법이 있습니까?



답변

방금이 문제가 발생했습니다. LinearLayout을 클릭 가능으로 설정해야합니다. XML에서 다음과 같이 할 수 있습니다.

android:clickable="true"

또는 코드에서

yourLinearLayout.setClickable(true);

건배!


답변

Android 기본 백그라운드 비헤이비어를 추가하여 Layout“clikable”처럼 작동하도록 View하려면 타겟팅 된Layout .

API 11+ (Pure Android) :

android:background="?android:attr/selectableItemBackground"

API 7+ (Android + AppCompat 지원 라이브러리) :

android:background="?attr/selectableItemBackground"

모든 API :

android:background="@android:drawable/list_selector_background"

위의 답변은 여전히 ​​사실이지만 기본 눌림 및 해제 UI 상태를 추가하는 데 도움이되지 않았습니다 (예 🙂 ListView.


답변

나는 첫 번째와 두 번째 대답을 사용했습니다. 하지만 내 선형 레이아웃에는 배경색이있는 이미지와 텍스트가 있으므로 “배경”을 “전경”으로 변경해야했습니다.

선형 레이아웃

android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"

답변

먼저 선택기를 사용하여 다른 상태를 정의해야합니다. 예를 들어, XML 파일에서 :

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_pressed"
          android:state_pressed="true" />
    <item android:drawable="@drawable/button_focused"
          android:state_focused="true" />
    <item android:drawable="@drawable/button_normal" />
</selector>

시도하지 않았지만 LinearLayout의 android : background를이 선택기로 설정하고 android : clickable을 true로 설정하면 작동합니다.

그렇지 않은 경우 RelativeLayout 사용으로 전환하고이 선택기를 배경으로 사용하여 첫 번째 요소를 버튼으로 만들고 레이아웃 너비 및 높이에 대해 fill_parent를 만들 수 있습니다. 이 경우 일반 버튼을 사용하고 선택기에 android : background를 설정하면됩니다. 버튼에 텍스트를 넣을 필요가 없습니다.


답변

작업중인 응용 프로그램에서 LinearLayout을 동적으로 만들어야합니다. 이 경우 명령

ll.setClickable(true);

예상대로 작동하지 않습니다. 내가 뭔가를 놓칠 수는 있지만 setOnTouchListener를 이용하여 동일한 결과를 얻었으며 누구나 동일한 요구 사항이있을 경우 코드를 제출합니다.

다음 코드는 두 개의 텍스트 뷰와 둥근 모서리가있는 LinearLayout을 만들고 누르면 색상이 변경됩니다.

먼저 드로어 블 폴더에 두 개의 xml 파일을 만듭니다. 하나는 일반용이고 다른 하나는 눌려진 선형 레이아웃 상태 용입니다.

일반 상태 xml (drawable / rounded_edges_normal.xml)

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />
            <corners android:radius="7dp" />
            <padding android:left="5dip" android:top="5dip" android:right="5dip" android:bottom="5dip" />
        </shape>
    </item>
    <item android:bottom="3px">
        <shape android:shape="rectangle">
            <solid android:color="#F1F1F1" />
            <corners android:radius="7dp" />
        </shape>
    </item>
</layer-list>

눌러 진 상태 xml (drawable / rounded_edges_pressed.xml). 유일한 차이점은 색상입니다 …

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />
            <corners android:radius="7dp" />
            <padding android:left="5dip" android:top="5dip" android:right="5dip" android:bottom="5dip" />
        </shape>
    </item>
    <item android:bottom="3px">
        <shape android:shape="rectangle">
            <solid android:color="#add8e6" />
            <corners android:radius="7dp" />
        </shape>
    </item>
</layer-list>

그런 다음 다음 코드가 작업을 수행합니다.

전역 변수 :

public int layoutpressed = -1;

에서 onCreate():

// Create some textviews to put into the linear layout...
TextView tv1 = new TextView(this);
TextView tv2 = new TextView(this);
tv1.setText("First Line");
tv2.setText("Second Line");

// LinearLayout definition and some layout properties...
final LinearLayout ll = new LinearLayout(context);
ll.setOrientation(LinearLayout.VERTICAL);

// it is supposed that the linear layout will be in a table.
// if this is not the case for you change next line appropriately...
ll.setLayoutParams(new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

ll.setBackgroundResource(R.drawable.rounded_edges_normal);
ll.addView(tv1);
ll.addView(tv2);
ll.setPadding(10, 10, 10, 10);
// Now define the three button cases
ll.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View arg0, MotionEvent arg1) {
                if (arg1.getAction()==MotionEvent.ACTION_DOWN){
                        ll.setBackgroundResource(R.drawable.rounded_edges_pressed);
                        ll.setPadding(10, 10, 10, 10);
                        layoutpressed = arg0.getId();
                }
                else if (arg1.getAction()== MotionEvent.ACTION_UP){
                        ll.setBackgroundResource(R.drawable.rounded_edges_normal);
                        ll.setPadding(10, 10, 10, 10);
                        if(layoutpressed == arg0.getId()){
                            //  ...........................................................................
                            // Code to execute when LinearLayout is pressed...
                            //  ........................................................................... 
                     }
          }
          else{
                ll.setBackgroundResource(R.drawable.rounded_edges_showtmimata);
                ll.setPadding(10, 10, 10, 10);
                layoutpressed = -1;
          }
          return true;
                }
  });           

답변

이 속성을 설정하십시오.

<LinearLayout
    ...
    android:background="@android:drawable/btn_default"
    android:clickable="true"
    android:focusable="true"
    android:onClick="onClick"
    >
...
</LinearLayout>

답변

배경 속성 / selectableItemBackground를 선형 레이아웃에 추가하고 해당 선형 레이아웃을 클릭 가능하게 만드십시오.

예 :

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/linear1"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true">

그것은 그것이 눌 렸을 때 linearlayout이 버튼처럼 작동하게 만듭니다. 🙂