view 相关内容代码片段笔记

来源:互联网 发布:php微社区源码 编辑:程序博客网 时间:2024/06/06 06:03


在activity中获取fragment中的控件
 getFragmentManager().findFragmentById(id).getView().findViewById(id)


HolderView item view 处理

@Overridepublic View getView(int i, View convertView, ViewGroup viewGroup) {    HolderView holderView;    // Important to not just null check, but rather to a instanceof    // since we might get any subclass of view here.    if (convertView instanceof HolderView) {        holderView = (HolderView) convertView;    } else {        holderView = new HolderView(mContext);    }    holderView.bind(new Digit(i));    return holderView;}class HolderView extends FrameLayout{        //private Context ctx;        private View vroot;        public HolderView(Context context) {            super(context);            init(context);        }        public HolderView(Context context, AttributeSet attrs, View vroot) {            super(context, attrs);            init(context);        }        private void init(Context context){            vroot = LayoutInflater.from(context).inflate(R.layout.flyrecoder_item, this);            ButterKnife.bind(this, vroot);        }void bindData(FlyRecordData model){this.tv_fly_record_item_title.setText(model.itemTitle);this.tv_fly_record_title_today.setText(model.todayData);} }

在展示窗体内容时添加对view统一处理

mLayoutInflater = (LayoutInflater) activity                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);        mViewGroup = (ViewGroup) activity                .findViewById(android.R.id.content);        mToastView = mLayoutInflater.inflate(R.layout.supertoast,                mViewGroup, false);        mMessageTextView = (TextView) mToastView                .findViewById(R.id.message_textview);

指定content view中头部或底部加入其它的view

private void setPoppyViewOnView(View view) {LayoutParams lp = view.getLayoutParams();ViewParent parent = view.getParent();ViewGroup group = (ViewGroup)parent;int index = group.indexOfChild(view);final FrameLayout newContainer = new FrameLayout(mActivity);group.removeView(view);group.addView(newContainer, index, lp);newContainer.addView(view);final FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);layoutParams.gravity = mPoppyViewPosition == PoppyViewPosition.BOTTOM ? Gravity.BOTTOM : Gravity.TOP;newContainer.addView(mPoppyView, layoutParams);group.invalidate();}public enum PoppyViewPosition {TOP, BOTTOM};private View mPoppyView;

设置图片叠加层(参差不齐效果)

Drawable[] array = new Drawable[2];       
array[0] = getResources().getDrawable(R.drawable.qq_girl);       
array[1] = getResources().getDrawable(R.drawable.qq_boy);       
LayerDrawable la = new LayerDrawable(array);       
// 其中第一个参数为层的索引号,后面的四个参数分别为left、top、right和bottom       
la.setLayerInset(0, 0, 0, 0, 0);       
la.setLayerInset(1, 18, 35, 180, 76);       
image.setImageDrawable(la);  

也可在xml实现
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/compassbackground" />
    <item android:drawable="@drawable/compass_text" />
</layer-list>



扩大控件有效点击区域(以imageview为例,当图片较小时,点击会有不灵敏感觉)这里需要设置scaleType属性

改进:
<ImageView
      android:layout_width="100dp"
      android:layout_height="100dp"
       android:src="@drawable/edit"
      android:scaleType="centerInside"/>
这里设置路ImageView的大小,这个大小区域就是ImageViwe的有效的点击区域,可以根据自己的情况修改大小
需要注意的是: 要使用 src 不能使用background 否则图像会被拉伸


在touch屏幕上某点时,判断点击是否在某个widget控件内:

Rect mTouchRect = new Rect(); private boolean isTouchedView(View view, float x, float y) {        view.getHitRect(mTouchRect);        // by taping top or bottom padding, the list performs on click on a border item.        // we don't add top padding here to keep behavior consistent.      //  mTouchRect.top += mTranslateY;      //  mTouchRect.bottom += mTranslateY + getPaddingTop();      //  mTouchRect.left += getPaddingLeft();      //  mTouchRect.right -= getPaddingRight();        return mTouchRect.contains((int)x, (int)y);    }

activity设置背景透明 getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));   

view背景透明设置
android:background
以下两种方法设置背景为透明:"@android :color/transparent"和"@null"

GirdView,ListView设置divide透明    gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));


隐去标题栏,  隐去状态栏 android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
设置透明背景,修改AndroidManifest.xml文件,在对应的Activity里面加上下面的属性:
android:theme="@android:style/Theme.Translucent"
使用系统背景作为应用的背景,在onCreate的时候添加窗口标志:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);
android:theme="@android:style/Theme.Dialog"


dialog级别设置 ctx不依赖Activity
 AlertDialog mDialog=dialog.create();  
 mDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);//设定为系统级警告,关键   

<activity android:windowSoftInputMode="stateVisible|adjustResize" . . . >
 该Activity主窗口总是被调整屏幕的大小以便留出软键盘的空间

//强制为横屏   
 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);  
<activity android:name=".HandlerActivity" android:screenOrientation="landscape"/>  

//强制为竖屏   
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);  
<activity android:name=".HandlerActivity" android:screenOrientation="portrait"/>

AndroidManifest.xml 中设置属性禁止重新创建Activity,并且添加屏幕切换监听。
<activity android:name=".HandlerActivity"
sdk<3.2 android:configChanges="orientation|keyboardHidden"/>
dk>3.2 android:configChanges="orientation|screenSize"




handler清理所有消息内容   mHandler.removeCallbacksAndMessages(null); 

//获取View在窗口/屏幕中的位置
TextView tv= (TextView) findViewById(R.id.tv);
int loc[]=new int[2];
tv.getLocationInWindow(loc);
Log.e("TAG",loc[0]+" "+loc[1]);


根据widget资源名称获取对应ID:   
int resID = getResources().getIdentifier("widget_id", "id",  getPackageName());
View addButton = findViewById(resID);

View中的isShown()方法,以前都是用view.getVisibility() == View.VISIBLE来判断的,但是与这个函数还是有区别的。
 也就是只有当view本身和它的所有父容器都是visible时,isShown()才返回TRUE。
 而平常我们调用if(view.getVisibility() == View.VISIBLE)只是对view本身而不对父容器的可见性进行判断。


直接获取view,不需要强制转型

public static <T> T $(View vroot,int viewID) {
        return (T) vroot.findViewById(viewID);
    }

使用:
Button takePicture = Utils.$(v, R.id.start_camera);


通过拨号键盘打开测试程序:

注册对应Receiver
<receiver android:name=".receiver.DiagnoserReceiver">
    <intent-filter>
        <action android:name="android.provider.Telephony.SECRET_CODE"/>
        <data android:scheme="android_secret_code" android:host="111222"/>
    </intent-filter>
</receiver>

接收处理:
public class DiagnoserReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        if ("android.provider.Telephony.SECRET_CODE".equals(intent.getAction())) {
            Intent i = new Intent(Intent.ACTION_MAIN);
            i.setClass(context, Diagnoser.class);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);
        }
     }
}

dial拨号输入  *#*#111222#*#*即可开启


绘制扇形进度加载

public void draw(Canvas canvas) {        if (getHideWhenZero() && mLevel == 0) {            return;        }        drawBar(canvas, maxLevel, getBackgroundColor());        drawBar(canvas, mLevel, getColor());    }        private void drawBar(Canvas canvas, int level, int color) {        Rect bounds = getBounds();        RectF rectF = new RectF((float) (bounds.right * .4), (float) (bounds.bottom * .4),                (float) (bounds.right * .6), (float) (bounds.bottom * .6));        mPaint.setColor(color);        mPaint.setStyle(Paint.Style.STROKE);        mPaint.setStrokeWidth(6);        if (level != 0)            canvas.drawArc(rectF, 0, (float) (level * 360 / maxLevel), false, mPaint);    }

屏幕截取

/**     * 获取当前屏幕截图,包含状态栏     */    public static Bitmap snapShotWithStatusBar(Activity activity){        View view = activity.getWindow().getDecorView();        view.setDrawingCacheEnabled(true);        view.buildDrawingCache();        Bitmap bmp = view.getDrawingCache();        int width = getScreenWidth(activity);        int height = getScreenHeight(activity);        Bitmap bp = null;        bp = Bitmap.createBitmap(bmp, 0, 0, width, height);        view.destroyDrawingCache();        return bp;    }     /**     * 获取当前屏幕截图,不包含状态栏     *     */    public static Bitmap snapShotWithoutStatusBar(Activity activity){        View view = activity.getWindow().getDecorView();        view.setDrawingCacheEnabled(true);        view.buildDrawingCache();        Bitmap bmp = view.getDrawingCache();        Rect frame = new Rect();        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);        int statusBarHeight = frame.top;        int width = getScreenWidth(activity);        int height = getScreenHeight(activity);        Bitmap bp = null;        bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height                - statusBarHeight);        view.destroyDrawingCache();        return bp;    }

Bitmap大小计算

static int getBitmapBytes(Bitmap bitmap) {    int result;    if (SDK_INT >= HONEYCOMB_MR1) {      result = BitmapHoneycombMR1.getByteCount(bitmap);    } else {      result = bitmap.getRowBytes() * bitmap.getHeight();    }    if (result < 0) {      throw new IllegalStateException("Negative size: " + bitmap);    }    return result;  }

保存恢复ListView当前位置

private void saveCurrentPosition() {        if (mListView != null) {            int position = mListView.getFirstVisiblePosition();            View v = mListView.getChildAt(0);            int top = (v == null) ? 0 : v.getTop();            //保存position和top        }    }        private void restorePosition() {        if (mFolder != null && mListView != null) {            int position = 0;//取出保存的数据            int top = 0;//取出保存的数据            mListView.setSelectionFromTop(position, top);        }    }

帮助、about、关于作者、HELP等的提示dialog页面

//方法一: AlertDialog ad = new AlertDialog.Builder(SettingPreference.this)                        .setTitle(R.string.about_dlg_title)                        .setMessage(R.string.about_dlg_message)                        .setPositiveButton(getText(R.string.ok), null).create();                ad.show();//加入链接功能                Linkify.addLinks((TextView) ad.findViewById(android.R.id.message),                        Linkify.ALL);//方法二://设计一个AboutDialog类继承于AlertDialogpublic class AboutDialog extends AlertDialog {       public AboutDialog(Context context) {           super(context);           final View view = getLayoutInflater().inflate(R.layout.about,                   null);           setButton(context.getText(R.string.close), (OnClickListener) null);           setIcon(R.drawable.icon_about);           setTitle("程序版本   v1.0.0" );           setView(view);       }   

布局文件about.xml

<?xml version="1.0" encoding="utf-8"?>  <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="fill_parent" android:layout_height="wrap_content">      <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"         android:layout_width="fill_parent" android:layout_height="fill_parent">             <TextView android:layout_height="fill_parent"             android:layout_width="fill_parent" android:text="@string/help_dialog_text"             android:padding="6dip" android:textColor="#FFFFFF" />      </ScrollView>  </FrameLayout>  




0 0
原创粉丝点击