Android Checkable LinearLayout状态 [英] Android Checkable LinearLayout states

查看:60
本文介绍了Android Checkable LinearLayout状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现可检查的线性布局,我已经完成了选中的项目,但是现在onclick和onLongClick不能正常工作了,它应该知道如何实现此行为.

I'am trying to implement a checkable Linear Layout, i already accomplish the checked item, but now the onclick and the onLongClick its not working has it should any ideas how can i implement this behavior.

  • 如果未选中&& OnLongClick =检查
  • 如果已选中&& onClick =取消选中
  • 如果已选中&& onLongClick =取消选中
  • 如果未选中&& onClick = super.performClick()

我可检查的LinearLayout

My checkable LinearLayout

public class CheckableLinearLayout extends LinearLayout implements Checkable {

/**
 * Interface definition for a callback to be invoked when the checked state
 * of this View is changed.
 */
public static interface OnCheckedChangeListener {

    /**
     * Called when the checked state of a compound button has changed.
     * 
     * @param checkableView
     *            The view whose state has changed.
     * @param isChecked
     *            The new checked state of checkableView.
     */
    void onCheckedChanged(View checkableView, boolean isChecked);
}

private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked };

private boolean mChecked = false;

private OnCheckedChangeListener mOnCheckedChangeListener;

public CheckableLinearLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public boolean isChecked() {
    return mChecked;
}

public void setChecked(boolean b) {
    if (b != mChecked) {
        mChecked = b;
        refreshDrawableState();

        if (mOnCheckedChangeListener != null) {
            mOnCheckedChangeListener.onCheckedChanged(this, mChecked);
        }
    }
}

public void toggle() {
    setChecked(!mChecked);
}

@Override
public int[] onCreateDrawableState(int extraSpace) {
    final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
    if (isChecked()) {
        mergeDrawableStates(drawableState, CHECKED_STATE_SET);
    }
    return drawableState;
}

/**
 * Register a callback to be invoked when the checked state of this view
 * changes.
 * 
 * @param listener
 *            the callback to call on checked state change
 */
public void setOnCheckedChangeListener(OnCheckedChangeListener listener) {
    mOnCheckedChangeListener = listener;
}

@Override
public boolean performLongClick() {
    toggle();
    return super.performLongClick();
}

@Override
public boolean performClick() {

    if (isChecked()) {
        toggle();
        return false;
    } else
        return super.performClick();
}

我的状态可绘制xml

my state drawable xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/add_schedule_button_checked_pressed" android:state_checked="true" android:state_pressed="true"/>

<!-- <item android:drawable="@drawable/add_schedule_button_checked_focused" -->
<!-- android:state_checked="true" -->
<!-- android:state_focused="true" /> -->

<item android:drawable="@drawable/selected_card_shape_w_shadow_white" android:state_checked="true"/>

<!-- <item android:drawable="@drawable/add_schedule_button_unchecked_pressed" -->
<!-- android:state_pressed="true" /> -->


<!-- <item android:drawable="@drawable/add_schedule_button_unchecked_focused" -->
<!-- android:state_focused="true" /> -->

我的布局

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/topics_preview_main_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<LinearLayout
    android:id="@+id/favorites_header_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="6dp"
    android:layout_marginRight="6dp"
    android:layout_marginTop="2dp"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/favorites_header_title"
        style="@style/CardText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="4dp"
        android:layout_marginLeft="6dp"
        android:layout_marginRight="6dp"
        android:layout_marginTop="4dp"
        android:background="@drawable/card"
        android:gravity="left"
        android:paddingBottom="10dp"
        android:paddingLeft="5dp"
        android:paddingTop="10dp"
        android:text="@string/favorites_header" />

    <ui.CheckableLinearLayout
        android:id="@+id/favorites_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="4dp"
        android:layout_marginLeft="6dp"
        android:layout_marginRight="6dp"
        android:layout_marginTop="4dp"
        android:background="@drawable/selector_card_shape_w_shadow_white"
        android:clickable="true"
        android:longClickable="true"
        android:orientation="vertical"
        android:paddingBottom="16dp" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:paddingLeft="8dp"
            android:paddingRight="8dp" >

            <TextView
                android:id="@+id/favorites_title"
                style="@style/CardTitle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="title" />
        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="4dp"
            android:background="@color/C_Favorites_Pink" />

        <LinearLayout
            android:id="@+id/favorites_description_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="vertical"
            android:padding="4dp" >

            <TextView
                android:id="@+id/favorites_description"
                style="@style/CardText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="8dp"
                android:ellipsize="end"
                android:maxLines="4"
                android:text="Lorem ipsum dolor sit amet" />
        </LinearLayout>
    </ui.CheckableLinearLayout>
</LinearLayout>

我的片段

private void onFavoriteClick(final MCourse courseInfo,
        LinearLayout favoritesLayout) {
    favoritesLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String courseId = Integer.toString(v.getId());
            String courseName = courseInfo.getFullname();

            Bundle bundle = new Bundle();
            bundle.putString("courseId", courseId);
            bundle.putString("courseName", courseName);

            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager
                    .beginTransaction();

            TopicsPreview insideTopicsFrag = new TopicsPreview();
            insideTopicsFrag.setArguments(bundle);
            fragmentTransaction
                    .replace(R.id.mainFragment, insideTopicsFrag);
            fragmentTransaction.commit();

        }
    });
}

推荐答案

为了修复您当前的代码,我在这里发布了一个完整的代码解决方案(因为我不明白您的问题是什么).它非常相似,只是没有所需的额外逻辑.

in order to fix your current code, i've published here a whole code solution (since i didn't understand what's wrong with yours). it's quite similar, only it doesn't have the extra logic that you wanted.

或者,您可以改用下一个解决方案:

alternatively, you can use the next solution instead:

您可以在CTOR上调用setOnClickListener和setOnLongClickListener,并根据当前状态将逻辑包含在新函数中,例如:

you can call setOnClickListener and setOnLongClickListener on the CTOR , and have the logic in the new functions according to the current state, as such:

public CheckableLinearLayout(Context context, AttributeSet attrs) 
  {
  super(context, attrs);
  setOnClickListener(null);
  }

为了使外部世界"使用这些新方法,您需要将它们作为包装器,例如:

in order to make the "outside world" work with these new methods, you need to make them as wrappers, for example:

public void setOnClickListener(... listener)
  {
  super.setOnClickListener(new ...
    {
    @Override
    public void onClick(...)
      {
      // TODO add add logic that you wanted according to the state of the view
      if(listener!=null) 
        listener.onClick(...);
      }
    });
  }

应该为长按实现类似的东西.

similar thing should be implemented for the long-clicking.

顺便说一句,您忘了添加对savedState捆绑包的处理.在 此处 中查找缺少的内容.

btw, you've forgot to add handling of the savedState bundle. read here for the missing things .

这是我经过测试可与布局的可检查性"一起使用的代码:

here's my code that i've tested to work with the "checkability" of the layout:

public class CheckableLinearLayout extends LinearLayout implements Checkable
  {
  private boolean             mChecked;
  private static final String TAG               =CheckableLinearLayout.class.getCanonicalName();
  private static final int[]  CHECKED_STATE_SET = {android.R.attr.state_checked};

  public CheckableLinearLayout(final Context context)
    {
    super(context);
    setClickable(true);
    setLongClickable(true);
    }

  public CheckableLinearLayout(final Context context,final AttributeSet attrs)
    {
    super(context,attrs);
    setClickable(true);
    setLongClickable(true);
    }

  @TargetApi(Build.VERSION_CODES.HONEYCOMB)
  public CheckableLinearLayout(final Context context,final AttributeSet attrs,final int defStyle)
    {
    super(context,attrs,defStyle);
    setClickable(true);
    setLongClickable(true);
    }

  @Override
  public void setChecked(final boolean checked)
    {
    mChecked=checked;
    refreshDrawableState();
    }

  @Override
  protected int[] onCreateDrawableState(final int extraSpace)
    {
    final int[] drawableState=super.onCreateDrawableState(extraSpace+1);
    if(isChecked())
      mergeDrawableStates(drawableState,CHECKED_STATE_SET);
    return drawableState;
    }

  @Override
  protected void drawableStateChanged()
    {
    super.drawableStateChanged();
    final Drawable drawable=getBackground();
    if(drawable!=null)
      {
      final int[] myDrawableState=getDrawableState();
      drawable.setState(myDrawableState);
      invalidate();
      }
    }

  @Override
  public boolean performClick()
    {
    Toast.makeText(getContext(),"click",Toast.LENGTH_SHORT).show();
    return super.performClick();
    }

  @Override
  public boolean performLongClick()
    {
    Toast.makeText(getContext(),"long click",Toast.LENGTH_SHORT).show();
    return super.performLongClick();
    }

  @Override
  public boolean isChecked()
    {
    return mChecked;
    }

  @Override
  public void toggle()
    {
    setChecked(!mChecked);
    }

  @Override
  public Parcelable onSaveInstanceState()
    {
    // Force our ancestor class to save its state
    final Parcelable superState=super.onSaveInstanceState();
    final SavedState savedState=new SavedState(superState);
    savedState.checked=isChecked();
    return savedState;
    }

  @Override
  public void onRestoreInstanceState(final Parcelable state)
    {
    final SavedState savedState=(SavedState)state;
    super.onRestoreInstanceState(savedState.getSuperState());
    setChecked(savedState.checked);
    requestLayout();
    }

  // /////////////
  // SavedState //
  // /////////////
  private static class SavedState extends BaseSavedState
    {
    boolean                                            checked;
    @SuppressWarnings("unused")
    public static final Parcelable.Creator<SavedState> CREATOR;
    static
      {
      CREATOR=new Parcelable.Creator<SavedState>()
        {
          @Override
          public SavedState createFromParcel(final Parcel in)
            {
            return new SavedState(in);
            }

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

    SavedState(final Parcelable superState)
      {
      super(superState);
      }

    private SavedState(final Parcel in)
      {
      super(in);
      checked=(Boolean)in.readValue(null);
      }

    @Override
    public void writeToParcel(final Parcel out,final int flags)
      {
      super.writeToParcel(out,flags);
      out.writeValue(checked);
      }

    @Override
    public String toString()
      {
      return TAG+".SavedState{"+Integer.toHexString(System.identityHashCode(this))+" checked="+checked+"}";
      }
    }
  }

这篇关于Android Checkable LinearLayout状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆