想了解java.beans.beancontext.BeanContextSupport的实例源码的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于java.beans.introspecti
想了解java.beans.beancontext.BeanContextSupport的实例源码的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于java.beans.introspection的相关问题,此外,我们还将为您介绍关于android.support.v4.content.ContextCompat的实例源码、ApplicationContext注入Bean(多线程中注入Bean)、bean实例化的三种方式 bean标签常用属性 单例模式和多例模式的对象 BeanFactory和ApplicationContext:、java – Spring 3 applicationContext-security-JDBC.xml有bean:bean不是bean?的新知识。
本文目录一览:- java.beans.beancontext.BeanContextSupport的实例源码(java.beans.introspection)
- android.support.v4.content.ContextCompat的实例源码
- ApplicationContext注入Bean(多线程中注入Bean)
- bean实例化的三种方式 bean标签常用属性 单例模式和多例模式的对象 BeanFactory和ApplicationContext:
- java – Spring 3 applicationContext-security-JDBC.xml有bean:bean不是bean?
java.beans.beancontext.BeanContextSupport的实例源码(java.beans.introspection)
/** Create nodes for a given key. * @param key the key * @return child nodes for this key or null if there should be no * nodes for this key */ protected Node[] createNodes(Object key) { Object ctx = bean; if (bean == null) return new Node[0]; try { if (key instanceof BeanContextSupport) { BeanContextSupport bcs = (BeanContextSupport)key; if (((BeanContext) ctx).contains (bcs.getBeanContextPeer())) { // sometimes a BeanContextSupport occures in the list of // beans children even there is its peer. we think that // it is desirable to hide the context if the peer is // also present return new Node[0]; } } return new Node[] { new BeanContextNode (key,task) }; } catch (IntrospectionException ex) { // ignore the exception return new Node[0]; } }
/** * @throws a MultipleSoloMapComponentException if a duplicate * instance of SoloMapComponent exists. * @return true if the object can be added to the MapHandler. */ public boolean canAdd(BeanContextSupport bc,Object obj) throws MultipleSoloMapComponentException { if (obj instanceof SoloMapComponent) { Class firstClass = obj.getClass(); for (Iterator it = bc.iterator(); it.hasNext();) { Object someObj = it.next(); if (someObj instanceof SoloMapComponent) { Class secondClass = someObj.getClass(); if (firstClass == secondClass || firstClass.isAssignableFrom(secondClass) || secondClass.isAssignableFrom(firstClass)) { throw new MultipleSoloMapComponentException(firstClass,secondClass); } } } } return true; }
public void testSerialization_nopeer() throws IOException,ClassNotFoundException { BeanContextSupport support = new BeanContextSupport(null,Locale.ITALY,true,true); support .addBeanContextMembershipListener(new MockBeanContextMembershipListener()); support .addBeanContextMembershipListener(new MockBeanContextMembershipListenerS( "l2")); support .addBeanContextMembershipListener(new MockBeanContextMembershipListenerS( "l3")); support .addBeanContextMembershipListener(new MockBeanContextMembershipListener()); support.add("abcd"); support.add(new MockBeanContextChild()); support.add(new MockBeanContextChildS("a child")); support.add(new MockBeanContextChild()); support.add("1234"); support.add(new MockBeanContextProxyS("proxy",new MockBeanContextChildS("b child"))); assertEqualsSerially(support,(BeanContextSupport) SerializationTester .getDeserilizedobject(support)); }
public void testSerialization_nopeer() throws IOException,(BeanContextSupport) SerializationTester .getDeserilizedobject(support)); }
public void testSerialization_Compatibility() throws Exception { MockBeanContextDelegateS mock = new MockBeanContextDelegateS("main id"); BeanContextSupport support = mock.support; support.addBeanContextMembershipListener(new MockBeanContextMembershipListener()); support.addBeanContextMembershipListener(new MockBeanContextMembershipListenerS("l2")); support.addBeanContextMembershipListener(new MockBeanContextMembershipListenerS("l3")); support.addBeanContextMembershipListener(new MockBeanContextMembershipListener()); support.add("abcd"); support.add(new MockBeanContextChild()); support.add(new MockBeanContextChildS("a child")); support.add(new MockBeanContextChild()); support.add("1234"); MockBeanContextDelegateS serMock = (MockBeanContextDelegateS) SerializationTester .readobject(mock,"serialization/java/beans/beancontext/BeanContextSupport.ser"); assertEquals(mock.id,serMock.id); assertSame(mock,mock.support.beanContextChildPeer); assertSame(serMock,serMock.support.beanContextChildPeer); assertEqualsSerially(mock.support,serMock.support); }
/** * @see java.beans.beancontext.BeanContextSupport#retainAll(Collection) * @see java.beans.beancontext.BeanContextSupport#iterator() */ public Result testContainsAllBeanContext()throws Exception { bean = new BeanContextChildSupport(); beanWithContext = new BeanWithBeanContext(); subContext = new BeanContextSupport(); vector = new Vector(); // Adding the components context.add(bean); context.add(beanWithContext); context.add(subContext); // Adding the components from bean context to Vector for (int i = 0; i < context.size(); i++) { vector.add(context.iterator().next()); } // It's verified that objects in the specified Vector are children of this bean context if (context.containsAll(vector)) { return passed(); } else { return Failed("testCollectionContainsAll() - Failed "); } }
/** * @see java.beans.beancontext.BeanContextSupport#size() */ public Result testSize() throws Exception { // The BeanContext object to be checked by the test BeanContextSupport contextForSize = new BeanContextSupport(); // Components that should be added to context BeanContextSupport subContext = new BeanContextSupport(); BeanWithBeanContext beanWithContext = new BeanWithBeanContext(); BeanContextChildSupport bean = new BeanContextChildSupport(); // Adding the components contextForSize.add(subContext); contextForSize.add(beanWithContext); contextForSize.add(bean); // It's verified that the BeanContext contains 4 components if (contextForSize.size() == 4) { return passed(); } else { return Failed("testSize() - Failed "); } }
/** * @see java.beans.beancontext.BeanContextSupport#isEmpty() */ public Result testIsContextEmpty() throws Exception { // The BeanContext object to be checked by the test BeanContextSupport context = new BeanContextSupport(); // Components that should be added to context BeanContextSupport subContext = new BeanContextSupport(); BeanWithBeanContext beanWithContext = new BeanWithBeanContext(); BeanContextChildSupport bean = new BeanContextChildSupport(); // Adding the components context.add(subContext); context.add(beanWithContext); context.add(bean); // It's verified that the BeanContext isn't empty if (!context.isEmpty()) { return passed(); } else { return Failed("testIsContextEmpty() - Failed "); } }
/** * @see java.beans.beancontext.BeanContextMembershipEvent */ public Result testNullPointerException1() throws Exception { context = new BeanContextSupport(); bean = new BeanContextChildSupport(); // Adding the component context.add(bean); Object[] array = null; try { event = new BeanContextMembershipEvent(bean.getBeanContext(),array); } catch (java.lang.NullPointerException e) { return passed(); } return Failed("testNullPointerException1"); }
/** * @see java.beans.beancontext.BeanContextMembershipEvent */ public Result testNullPointerException2() throws Exception { context = new BeanContextSupport(); bean = new BeanContextChildSupport(); // Adding the component context.add(bean); Collection[] array = null; try { event = new BeanContextMembershipEvent(bean.getBeanContext(),array); } catch (java.lang.NullPointerException e) { return passed(); } return Failed("testNullPointerException2"); }
/** * @see java.beans.beancontext.BeanContextMembershipEvent#contains() */ public Result testContainsBeanContextMembershipEvent() throws Exception { context = new BeanContextSupport(); bean = new BeanContextChildSupport(); sBean = new ServiceBean(); // Adding the component context.add(bean); context.add(sBean); event = new BeanContextMembershipEvent(bean.getBeanContext(),context .toArray()); if ((event.contains(sBean)) || !(event.contains(context))) return passed(); else return Failed("testContainsBeanContextMembershipEvent"); }
/** * @see java.beans.beancontext.BeanContextSupport#iterator() */ public Result testIteratorBeanContextMembershipEvent() throws Exception { context = new BeanContextSupport(); bean = new BeanContextChildSupport(); sBean = new ServiceBean(); // Adding the component context.add(bean); context.add(sBean); event = new BeanContextMembershipEvent(bean.getBeanContext(),context .toArray()); if ((event.iterator() instanceof java.util.Iterator)) return passed(); else return Failed("testIteratorBeanContextMembershipEvent"); }
/** * @see java.beans.beancontext.BeanContextSupport#size() */ public Result testSizeBeanContextMembershipEvent() throws Exception { context = new BeanContextSupport(); bean = new BeanContextChildSupport(); sBean = new ServiceBean(); // Adding the component context.add(bean); context.add(sBean); event = new BeanContextMembershipEvent(bean.getBeanContext(),context .toArray()); // System.out.println(event.size()); if (event.size() == 2) return passed(); else return Failed("testSizeBeanContextMembershipEvent"); }
public static void main(String[] args) { BeanContextSupport context = new BeanContextSupport(); // The BeanContext BeanContextChildSupport bean = new BeanContextChildSupport(); // The JavaBean // add the bean to the context context.add(bean); try { context.getResourceAsstream("Readme.txt",bean); } catch (Exception exception) { throw new Error("unexpected exception",exception); } }
public static void main(String[] args) { BeanContextSupport context = new BeanContextSupport(); // The BeanContext BeanContextChildSupport bean = new BeanContextChildSupport(); // The JavaBean // add the bean to the context context.add(bean); try { context.getResourceAsstream("Readme.txt",exception); } }
public static void main(String[] args) { BeanContextSupport context = new BeanContextSupport(); // The BeanContext BeanContextChildSupport bean = new BeanContextChildSupport(); // The JavaBean // add the bean to the context context.add(bean); try { context.getResourceAsstream("Readme.txt",exception); } }
public static void main(String[] args) { BeanContextSupport context = new BeanContextSupport(); // The BeanContext BeanContextChildSupport bean = new BeanContextChildSupport(); // The JavaBean // add the bean to the context context.add(bean); try { context.getResourceAsstream("Readme.txt",exception); } }
public static void main(String[] args) { BeanContextSupport context = new BeanContextSupport(); // The BeanContext BeanContextChildSupport bean = new BeanContextChildSupport(); // The JavaBean // add the bean to the context context.add(bean); try { context.getResourceAsstream("Readme.txt",exception); } }
/** * initializes the serialization for different types of data * * @param layout the component that manages the layout * @param context the bean context support to use * @param datatype the type of data to read/write * @throws Exception if initialization fails */ public XMLBeans(JComponent layout,BeanContextSupport context,int datatype,int tab) throws Exception { super(); m_vectorIndex = tab; m_BeanLayout = layout; m_BeanContextSupport = context; setDataType(datatype); }
/** * initializes the serialization for different types of data * * @param layout the component that manages the layout * @param context the bean context support to use * @param datatype the type of data to read/write * @throws Exception if initialization fails */ public XMLBeans(JComponent layout,int tab) throws Exception { super(); m_vectorIndex = tab; m_BeanLayout = layout; m_BeanContextSupport = context; setDataType(datatype); }
/** * initializes the serialization for different types of data * * @param layout the component that manages the layout * @param context the bean context support to use * @param datatype the type of data to read/write * @throws Exception if initialization fails */ public XMLBeans(JComponent layout,int tab) throws Exception { super(); m_vectorIndex = tab; m_BeanLayout = layout; m_BeanContextSupport = context; setDataType(datatype); }
public static void main(String[] args) { BeanContextSupport context = new BeanContextSupport(); // The BeanContext BeanContextChildSupport bean = new BeanContextChildSupport(); // The JavaBean // add the bean to the context context.add(bean); try { context.getResourceAsstream("Readme.txt",exception); } }
public static void main(String[] args) { BeanContextSupport context = new BeanContextSupport(); // The BeanContext BeanContextChildSupport bean = new BeanContextChildSupport(); // The JavaBean // add the bean to the context context.add(bean); try { context.getResourceAsstream("Readme.txt",exception); } }
public static void main(String[] args) { BeanContextSupport context = new BeanContextSupport(); // The BeanContext BeanContextChildSupport bean = new BeanContextChildSupport(); // The JavaBean // add the bean to the context context.add(bean); try { context.getResourceAsstream("Readme.txt",exception); } }
public static void main(String[] args) { BeanContextSupport context = new BeanContextSupport(); // The BeanContext BeanContextChildSupport bean = new BeanContextChildSupport(); // The JavaBean // add the bean to the context context.add(bean); try { context.getResourceAsstream("Readme.txt",exception); } }
/** * @return true if the object can be added to the MapHandler,and * will have removed the prevIoUs duplicate from the * MapHandler. */ public boolean canAdd(BeanContextSupport bc,Object obj) throws MultipleSoloMapComponentException { if (obj == null) { return false; } // At first we just added the new item,but we should remove // the prevIoUs one,too. if (obj instanceof SoloMapComponent) { Class firstClass = obj.getClass(); for (Iterator it = bc.iterator(); it.hasNext();) { Object someObj = it.next(); if (someObj instanceof SoloMapComponent) { Class secondClass = someObj.getClass(); if (firstClass == secondClass || firstClass.isAssignableFrom(secondClass) || secondClass.isAssignableFrom(firstClass)) { bc.remove(someObj); break; } } } } return true; }
public static void main(String[] args) { BeanContextSupport context = new BeanContextSupport(); // The BeanContext BeanContextChildSupport bean = new BeanContextChildSupport(); // The JavaBean // add the bean to the context context.add(bean); try { context.getResourceAsstream("Readme.txt",exception); } }
public void testInstantiateClassLoaderStringBeanContext_Class() throws Exception { ClassLoader loader = new BinClassLoader(); BeanContext context = new BeanContextSupport(); Object bean = Beans.instantiate(loader,MOCK_JAVA_BEAN2,context); assertEquals("as_class",(String) bean.getClass().getmethod( "getPropertyOne",(Class[]) null).invoke(bean,(Object[]) null)); assertSame(loader,bean.getClass().getClassLoader()); assertTrue(context.contains(bean)); }
public void testInstantiateClassLoaderStringBeanContext_Ser() throws Exception { ClassLoader loader = new SerClassLoader(); BeanContext context = new BeanContextSupport(); Object bean = Beans.instantiate(loader,context); assertEquals("as_object",bean.getClass().getClassLoader()); assertTrue(context.contains(bean)); }
public void testInstantiateClassLoaderStringBeanContext_ClassLoaderNull() throws Exception { BeanContext context = new BeanContextSupport(); Object bean = Beans.instantiate(null,MockJavaBean.class.getName(),context); assertEquals(bean.getClass(),MockJavaBean.class); assertSame(ClassLoader.getSystemClassLoader(),bean.getClass() .getClassLoader()); assertTrue(context.contains(bean)); }
public void testInstantiateClassLoaderStringBeanContext_BeanNameNull() throws Exception { BeanContext context = new BeanContextSupport(); ClassLoader loader = createSpecificclassLoader(); try { Beans.instantiate(loader,null,context); fail("Should throw NullPointerException."); } catch (NullPointerException e) { } }
public void testInstantiateClassLoaderStringBeanContextAppletinitializer_Class() throws Exception { ClassLoader loader = new BinClassLoader(); BeanContext context = new BeanContextSupport(); Appletinitializer appInit = new MockAppletinitializer(); Object bean = Beans.instantiate(loader,context,appInit); assertEquals("as_class",bean.getClass().getClassLoader()); assertTrue(context.contains(bean)); }
public void testInstantiateClassLoaderStringBeanContextAppletinitializer_Ser() throws Exception { ClassLoader loader = new SerClassLoader(); BeanContext context = new BeanContextSupport(); Appletinitializer appInit = new MockAppletinitializer(); Object bean = Beans.instantiate(loader,appInit); assertEquals("as_object",bean.getClass().getClassLoader()); assertTrue(context.contains(bean)); }
public void testInstantiateClassLoaderStringBeanContextAppletinitializer_LoaderNull() throws Exception { String beanName = "org.apache.harmony.beans.tests.support.mock.MockJavaBean"; BeanContext context = new BeanContextSupport(); Appletinitializer appInit = new MockAppletinitializer(); Object bean = Beans.instantiate(null,beanName,appInit); assertSame(ClassLoader.getSystemClassLoader(),bean.getClass() .getClassLoader()); assertEquals(beanName,bean.getClass().getName()); assertTrue(context.contains(bean)); }
public void testInstantiateClassLoaderStringBeanContextAppletinitializer_BeanNull() throws Exception { ClassLoader loader = createSpecificclassLoader(); BeanContext context = new BeanContextSupport(); Appletinitializer appInit = new MockAppletinitializer(); try { Beans.instantiate(loader,appInit); fail("Should throw NullPointerException."); } catch (NullPointerException e) { } }
public void testInstantiateClassLoaderStringBeanContextAppletinitializer_InitializerNull() throws Exception { ClassLoader loader = createSpecificclassLoader(); String beanName = "org.apache.harmony.beans.tests.support.mock.MockJavaBean"; BeanContext context = new BeanContextSupport(); Object bean = Beans.instantiate(loader,null); assertSame(ClassLoader.getSystemClassLoader(),bean.getClass().getName()); }
public void test_writeObject_java_beans_beancontext_BeanContextSupport() throws PropertyVetoException{ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); XMLEncoder encoder = new XMLEncoder(new bufferedoutputstream( byteArrayOutputStream)); BeanContextSupport support = new BeanContextSupport(); encoder.writeObject(support); encoder.close(); DataInputStream stream = new DataInputStream(new ByteArrayInputStream( byteArrayOutputStream.toByteArray())); XMLDecoder decoder = new XMLDecoder(stream); BeanContextSupport aSupport = (BeanContextSupport) decoder.readobject(); assertEquals(Locale.getDefault(),aSupport.getLocale()); }
public void test_setLocale_null() throws Exception { Locale locale = Locale.FRANCE; BeanContextSupport beanContextSupport = new BeanContextSupport(null,locale); assertEquals(Locale.FRANCE,beanContextSupport.getLocale()); MyPropertychangelistener myPropertychangelistener = new MyPropertychangelistener(); beanContextSupport.addPropertychangelistener("locale",myPropertychangelistener); beanContextSupport.setLocale(null); assertEquals(Locale.FRANCE,beanContextSupport.getLocale()); assertFalse(myPropertychangelistener.changed); }
/** * Test method setBeanContext() with BeanContext parameter. * <p> */ public void testSetBeanContextBeanContext() throws Exception { BeanContextChildSupport sup = new BeanContextChildSupport(); sup.setBeanContext(new BeanContextSupport()); assertNotNull("BeanContext should not be null",sup.getBeanContext()); }
android.support.v4.content.ContextCompat的实例源码
private void initExpandIcon(RelativeLayout headerLayout) { expandIcon = new ImageView(getContext()); int margin = (int) getContext().getResources().getDimension(R.dimen.icon_margin); RelativeLayout.LayoutParams expandIconParams = new RelativeLayout.LayoutParams((int) getResources().getDimension(R.dimen.expand_drawable_size),(int) getResources().getDimension(R.dimen.expand_drawable_size)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { expandIconParams.addRule(RelativeLayout.ALIGN_PARENT_END); } else { expandIconParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); } expandIconParams.addRule(RelativeLayout.CENTER_VERTICAL); expandIconParams.setMargins(margin,margin,margin); expandIcon.setId(Expandableutils.ID_EXPAND_ICON); expandIcon.setLayoutParams(expandIconParams); expandIcon.setimageDrawable(expandindicator == null ? ContextCompat.getDrawable(getContext(),R.drawable.ic_down) : expandindicator); headerLayout.addView(expandIcon); }
private void activateMainIcons(boolean enabled) { Integer color = R.color.colorPrimary; if (!enabled) { color = R.color.colorSilver; } ImageView imageViewShowList = (ImageView) findViewById(R.id.imageViewShowList); ImageView imageViewShowMap = (ImageView) findViewById(R.id.imageViewShowMap); ImageView imageViewCategory = (ImageView) findViewById(R.id.imageViewShowCategories); ImageView imageViewAchievements = (ImageView) findViewById(R.id.imageViewAchievements); TextView textViewShowList = (TextView) findViewById(R.id.textViewShowList); TextView textViewShowMap = (TextView) findViewById(R.id.textViewShowMap); TextView textViewCategory = (TextView) findViewById(R.id.textViewShowCategories); TextView textViewShowAchievements = (TextView) findViewById(R.id.textViewShowAchievements); DrawableCompat.setTint(imageViewShowList.getDrawable(),ContextCompat.getColor(this,color)); DrawableCompat.setTint(imageViewShowMap.getDrawable(),color)); DrawableCompat.setTint(imageViewCategory.getDrawable(),color)); DrawableCompat.setTint(imageViewAchievements.getDrawable(),color)); textViewShowList.setTextColor(ContextCompat.getColor(this,color)); textViewShowMap.setTextColor(ContextCompat.getColor(this,color)); textViewCategory.setTextColor(ContextCompat.getColor(this,color)); textViewShowAchievements.setTextColor(ContextCompat.getColor(this,color)); }
@Override protected void onPostExecute(Boolean b) { if (b) { dismiss(); Toast.makeText(Utils.getContext(),"Umfrage erfolgreich erstellt",Toast.LENGTH_LONG).show(); } else { final Snackbar snackbar = Snackbar.make(findViewById(R.id.wrapper),"Es ist etwas schiefgelaufen,versuche es später erneut",Snackbar.LENGTH_SHORT); snackbar.setActionTextColor(ContextCompat.getColor(getContext(),R.color.colorPrimary)); snackbar.setAction(getContext().getString(R.string.dismiss),new View.OnClickListener() { @Override public void onClick(View v) { snackbar.dismiss(); } }); snackbar.show(); } }
public TextView showProgressDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(false); View view = View.inflate(this,R.layout.dialog_loading,null); builder.setView(view); ProgressBar pb_loading = (ProgressBar) view.findViewById(R.id.pb_loading); TextView tv_hint = (TextView) view.findViewById(R.id.tv_hint); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { pb_loading.setIndeterminateTintList(ContextCompat.getColorStateList(this,R.color.dialog_pro_color)); } tv_hint.setText("视频编译中"); progressDialog = builder.create(); progressDialog.show(); return tv_hint; }
/** * 拍照 */ private void takePhoto() { //在每次拍照做权限的判断,防止出现权限不全而获取不到图像 if (ContextCompat.checkSelfPermission(mActivity,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(mActivity,Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { return; } Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){ mPhotoUri = get24MediaFileUri(TYPE_TAKE_PHOTO); takeIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); }else { mPhotoUri = getMediaFileUri(TYPE_TAKE_PHOTO); } takeIntent.putExtra(MediaStore.EXTRA_OUTPUT,mPhotoUri); mActivity.startActivityForResult(takeIntent,COOD_TAKE_PHOTO); }
public BubblePageIndicator(Context context,AttributeSet attrs,int defStyle) { super(context,attrs,defStyle); if (isInEditMode()) return; //Load defaults from resources final Resources res = getResources(); final int defaultPageColor = ContextCompat.getColor(context,R.color.default_bubble_indicator_page_color); final int defaultFillColor = ContextCompat.getColor(context,R.color.default_bubble_indicator_fill_color); final float defaulTradius = res.getDimension(R.dimen.default_bubble_indicator_radius); //Retrieve styles attributes TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.BubblePageIndicator,defStyle,0); paintPageFill.setStyle(Style.FILL); paintPageFill.setColor(a.getColor(R.styleable.BubblePageIndicator_pageColor,defaultPageColor)); paintFill.setStyle(Style.FILL); paintFill.setColor(a.getColor(R.styleable.BubblePageIndicator_fillColor,defaultFillColor)); radius = a.getDimension(R.styleable.BubblePageIndicator_radius,defaulTradius); marginBetweenCircles = a.getDimension(R.styleable.BubblePageIndicator_marginBetweenCircles,radius); a.recycle(); }
@Override public void onBindViewHolder(MyViewHolder holder,int position) { try { Pessoa.Contato contato = contatoList.get(position); switch (contato.getTipo().toLowerCase()) { case "facebook": holder.tipo_contato_image.setimageDrawable(ContextCompat.getDrawable(context,R.drawable.ic_facebook)); break; case "twitter": holder.tipo_contato_image.setimageDrawable(ContextCompat.getDrawable(context,R.drawable.ic_twitter)); break; case "linkedin": holder.tipo_contato_image.setimageDrawable(ContextCompat.getDrawable(context,R.drawable.ic_linkedin)); break; case "github": holder.tipo_contato_image.setimageDrawable(ContextCompat.getDrawable(context,R.drawable.ic_github)); break; default: holder.tipo_contato_image.setimageDrawable(ContextCompat.getDrawable(context,R.drawable.ic_outro)); } } catch (Exception e) { e.printstacktrace(); } }
public View getView(final int position,View convertView,ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.media_item,parent,false); viewHolder = new ViewHolder(convertView); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.tvText.setCompoundDrawablesWithIntrinsicBounds(null,ContextCompat.getDrawable(mContext,getItem(position).getDrawableId()),null,null); viewHolder.tvText.setText(getItem(position).getText()); convertView.setonClickListener(new OnClickListener() { @Override public void onClick(View v) { getItem(position).getMediaListener().onMediaClick(getItem(position).getId()); } }); return convertView; }
private void initTabs() { int normalColor = QMUIResHelper.getAttrColor(getActivity(),R.attr.qmui_config_color_gray_6); int selectColor = QMUIResHelper.getAttrColor(getActivity(),R.attr.qmui_config_color_blue); mTabSegment.setDefaultnormalColor(normalColor); mTabSegment.setDefaultSelectedColor(selectColor); QMUITabSegment.Tab component = new QMUITabSegment.Tab( ContextCompat.getDrawable(getContext(),R.mipmap.icon_tabbar_component),ContextCompat.getDrawable(getContext(),R.mipmap.icon_tabbar_component_selected),"Components",false ); QMUITabSegment.Tab util = new QMUITabSegment.Tab( ContextCompat.getDrawable(getContext(),R.mipmap.icon_tabbar_util),R.mipmap.icon_tabbar_util_selected),"Helper",false ); QMUITabSegment.Tab lab = new QMUITabSegment.Tab( ContextCompat.getDrawable(getContext(),R.mipmap.icon_tabbar_lab),R.mipmap.icon_tabbar_lab_selected),"Lab",false ); mTabSegment.addTab(component) .addTab(util) .addTab(lab); }
private void initToolbar() { Toolbar toolbar = findViewById(R.id.actionBarChat); toolbar.setTitleTextColor(ContextCompat.getColor(getApplicationContext(),android.R.color.white)); toolbar.setTitle(cname); setSupportActionBar(toolbar); getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_arrow_left); getSupportActionBar().setdisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); if (ctype != Chat.ChatType.PRIVATE && Utils.getController().getMessengerDatabase().userInChat(Utils.getUserID(),cid)) { toolbar.setonClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivityForResult(new Intent(getApplicationContext(),ChatEditactivity.class) .putExtra("cid",cid) .putExtra("cname",cname),1); } }); } }
private void shiftSharedElements(float pageOffsetX,boolean forward){ final Context context=pager.getContext(); //since we're clipping the page,we have to adjust the shared elements AnimatorSet shiftAnimator=new AnimatorSet(); for(View view:sharedElements){ float translationX=forward?pageOffsetX:-pageOffsetX; float temp=view.getWidth()/3f; translationX-=forward?temp:-temp; ObjectAnimator shift=ObjectAnimator.ofFloat(view,View.TRANSLATION_X,translationX); shiftAnimator.playTogether(shift); } int color=ContextCompat.getColor(context,forward?R.color.color_logo_sign_up:R.color.color_logo_log_in); DrawableCompat.setTint(sharedElements.get(0).getDrawable(),color); //scroll the background by x int offset=authBackground.getWidth()/2; ObjectAnimator scrollAnimator=ObjectAnimator.ofInt(authBackground,"scrollX",forward?offset:-offset); shiftAnimator.playTogether(scrollAnimator); shiftAnimator.setInterpolator(new AccelerateDecelerateInterpolator()); shiftAnimator.setDuration(pager.getResources().getInteger(R.integer.duration)/2); shiftAnimator.start(); }
public void requestAppPermissions(final String[]requestedPermissions,final int stringId,final int requestCode) { mErrorString.put(requestCode,stringId); int permissionCheck = PackageManager.PERMISSION_GRANTED; boolean showRequestPermissions = false; for(String permission: requestedPermissions) { permissionCheck = permissionCheck + ContextCompat.checkSelfPermission(this,permission); showRequestPermissions = showRequestPermissions || ActivityCompat.shouldShowRequestPermissionRationale(this,permission); } if (permissionCheck!=PackageManager.PERMISSION_GRANTED) { if(showRequestPermissions) { Snackbar.make(findViewById(android.R.id.content),stringId,Snackbar.LENGTH_INDEFINITE).setAction("GRANT",new View.OnClickListener() { @Override public void onClick(View v) { ActivityCompat.requestPermissions(AbsRuntimePermission.this,requestedPermissions,requestCode); } }).show(); } else { ActivityCompat.requestPermissions(this,requestCode); } } else { onPermissionsGranted(requestCode); } }
private void fillViews(Optional<Concert> optional) { if (!optional.isPresent()) { return; } Concert concert = optional.getValue(); String artistName = concert.getArtist().getName(); collapsingToolbar.setTitle(artistName); collapsingToolbar.setExpandedTitleColor( ContextCompat.getColor(this,android.R.color.transparent)); artistTextView.setText(artistName); String placeText = String.format("%s,%s",concert.getLocation().getName(),concert.getPlace()); placeTextView.setText(placeText); dateTextView.setText(makeDateString(concert)); imageLoader.loadConcertBackdrop(this,concert,backdropImageView); }
/** * Check if the calling context has a set of permissions. * * @param context * the calling context. * @param perms * one ore more permissions,such as {@code android.Manifest.permission.CAMERA}. * @return true if all permissions are already granted,false if at least one permission is not yet granted. */ public static boolean hasPermissions(@NonNull Context context,@NonNull String... perms) { // Always return true for SDK < M,let the system deal with the permissions if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { Log.w(TAG,"hasPermissions: API version < M,returning true by default"); return true; } for (String perm : perms) { boolean hasPerm = (ContextCompat.checkSelfPermission(context,perm) == PackageManager.PERMISSION_GRANTED); if (!hasPerm) { return false; } } return true; }
public void onAttachClick() { final int permissionStatus = ContextCompat.checkSelfPermission( getContext(),Manifest.permission.READ_EXTERNAL_STORAGE ); if (permissionStatus != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( getActivity(),new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},REQUEST_ATTACH_PERMISSION ); return; } final Intent attach = new Intent(Intent.ACTION_GET_CONTENT) .addCategory(Intent.CATEGORY_OPENABLE) .setType("*/*"); startActivityForResult(attach,REQUEST_ATTACH_FILE); }
public static int[] getBaseColors(Context context) { return new int[] { ContextCompat.getColor(context,R.color.md_red_500),ContextCompat.getColor(context,R.color.md_pink_500),R.color.md_purple_500),R.color.md_deep_purple_500),R.color.md_indigo_500),R.color.md_blue_500),R.color.md_light_blue_500),R.color.md_cyan_500),R.color.md_teal_500),R.color.md_green_500),R.color.md_light_green_500),R.color.md_lime_500),R.color.md_yellow_500),R.color.md_Amber_500),R.color.md_orange_500),R.color.md_deep_orange_500),R.color.md_brown_500),R.color.md_blue_grey_500),R.color.md_grey_500),R.color.av_color5) }; }
public ShadowDrawableWrapper(Context context,Drawable content,float radius,float shadowSize,float maxShadowSize) { super(content); mShadowStartColor = ContextCompat.getColor(context,R.color.design_fab_shadow_start_color); mShadowMiddleColor = ContextCompat.getColor(context,R.color.design_fab_shadow_mid_color); mShadowEndColor = ContextCompat.getColor(context,R.color.design_fab_shadow_end_color); mCornerShadowPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG); mCornerShadowPaint.setStyle(Paint.Style.FILL); mCornerRadius = Math.round(radius); mContentBounds = new RectF(); mEdgeShadowPaint = new Paint(mCornerShadowPaint); mEdgeShadowPaint.setAntiAlias(false); setShadowSize(shadowSize,maxShadowSize); }
@Override public void onBindViewHolder(final VersionSelectionViewHolder holder,int position) { TextView contentView = holder.getContentView(); if (contentView == null) { return; } holder.setItem(mValues.get(position)); contentView.setText(mValues.get(position).getdisplayText()); boolean currentIsSelected = CurrentSelected.getVersion() != null && CurrentSelected.getVersion().getId().equals(mValues.get(position).getId()); contentView.setTextColor(ContextCompat.getColor(contentView.getContext(),currentIsSelected ? R.color.primary : R.color.primary_text)); contentView.setTypeface(null,currentIsSelected ? Typeface.BOLD : Typeface.norMAL); holder.itemView.setonClickListener(v -> { if (mListener != null) { // Notify the active callbacks interface (the activity,if the // fragment is attached to one) that an item has been selected. mListener.onVersionSelected(holder.getItem()); } }); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSwipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer); mSwipeContainer.setEnabled(false); mSwipeContainer.setColorSchemeColors(ContextCompat.getColor(this,R.color.colorAccent)); // exit if the device doesn't have BLE if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUetoOTH_LE)) { Toast.makeText(this,R.string.no_ble,Toast.LENGTH_SHORT).show(); finish(); } // load ScanFragment mFragmentManager = getSupportFragmentManager(); mCurrentFragment = ScanFragment.newInstance(); mFragmentManager.beginTransaction().replace(R.id.container,mCurrentFragment).commit(); }
private void makeShape() { loadShapeAttributes(); GradientDrawable gradientDrawable = (GradientDrawable) rootLayout.getBackground(); gradientDrawable.setCornerRadius(cornerRadius != -1 ? cornerRadius : R.dimen.default_corner_radius); gradientDrawable.setstroke(strokeWidth,strokeColor); if (backgroundColor == 0) { gradientDrawable.setColor(ContextCompat.getColor(context,R.color.defaultBackgroundColor)); } else { gradientDrawable.setColor(backgroundColor); } if (solidBackground) { gradientDrawable.setAlpha(getResources().getInteger(R.integer.fullBackgroundAlpha)); } else { gradientDrawable.setAlpha(getResources().getInteger(R.integer.defaultBackgroundAlpha)); } rootLayout.setBackground(gradientDrawable); }
private void checkPermissions() { int permissionCheck = ContextCompat.checkSelfPermission(this,Manifest.permission.READ_PHONE_STATE); if (permissionCheck != PackageManager.PERMISSION_GRANTED) { // permission not granted if (ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.READ_PHONE_STATE)) { // show message if u want.. // Todo: show message why we want READ_PHONE_STATE permission // for Now,just toast why we need permissions showToast("We need some permissions for this app to function properly."); } else { // request the permission here ActivityCompat.requestPermissions( this,new String[]{Manifest.permission.READ_PHONE_STATE},PERMISSION_REQUEST_CODE ); } } }
/** * Build a connection to the database. This progress will analysis the * litepal.xml file,and will check if the fields in LitePalAttr are valid,* and it will open a sqliteOpenHelper to decide to create tables or update * tables or doing nothing depends on the version attributes. * * After all the stuffs above are finished. This method will return a * LitePalHelper object.Notes this method Could throw a lot of exceptions. * * @return LitePalHelper object. * * @throws org.litepal.exceptions.InvalidAttributesException */ private static LitePalOpenHelper buildConnection() { LitePalAttr litePalAttr = LitePalAttr.getInstance(); litePalAttr.checkSelfValid(); if (mLitePalHelper == null) { String dbname = litePalAttr.getdbname(); if ("external".equalsIgnoreCase(litePalAttr.getStorage())) { dbname = LitePalApplication.getContext().getExternalFilesDir("") + "/databases/" + dbname; } else if (!"internal".equalsIgnoreCase(litePalAttr.getStorage()) && !TextUtils.isEmpty(litePalAttr.getStorage())) { // internal or empty means internal storage,neither or them means sdcard storage String dbPath = Environment.getExternalStorageDirectory().getPath() + "/" + litePalAttr.getStorage(); dbPath = dbPath.replace("//","/"); if (BaseUtility.isClassAndMethodExist("android.support.v4.content.ContextCompat","checkSelfPermission") && ContextCompat.checkSelfPermission(LitePalApplication.getContext(),Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { throw new DatabaseGenerateException(String.format(DatabaseGenerateException.EXTERNAL_STORAGE_PERMISSION_DENIED,dbPath)); } File path = new File(dbPath); if (!path.exists()) { path.mkdirs(); } dbname = dbPath + "/" + dbname; } mLitePalHelper = new LitePalOpenHelper(dbname,litePalAttr.getVersion()); } return mLitePalHelper; }
@Override protected void onCreate(Bundle savedInstanceState) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); boolean isDark = preferences.getBoolean("DARK_THEME_KEY",false); if (isDark) setTheme(R.style.AppThemeDark_NoActionBar); else setTheme(R.style.AppTheme_NoActionBar); super.onCreate(savedInstanceState); setContentView(R.layout.aboutme_layout); if (isDark) findViewById(R.id.relativeLayoutAbout).setBackgroundColor(ContextCompat.getColor(this,R.color.DarkcolorPrimaryDark)); else { findViewById(R.id.relativeLayoutAbout).setBackgroundColor(ContextCompat.getColor(this,R.color.colorPrimaryDark)); } TextView textView = (TextView) findViewById(R.id.textView3); String s = "Version " + BuildConfig.VERSION_NAME; textView.setText(s); }
private void checkPermission() { //6.0申请读写sd卡权限 if (Build.VERSION.SDK_INT >= 23) { //检测是否有读写权限 if (ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { Log.e("没有权限","走了"); //没有权限,检查用户是否已经设置不再提醒申请该权限 if (!ActivityCompat.shouldShowRequestPermissionRationale (this,Manifest.permission.WRITE_EXTERNAL_STORAGE)) { Toast.makeText(this,"您已禁止该权限,请到设置中打开",Toast.LENGTH_SHORT).show(); }else { //申请该权限 ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_CODE); } }else downloadApk(); }else { downloadApk(); } }
private void setUpRecyclerView() { List<ListItemAttachment> items = mCurrent.getItems(); if(items.size() == 0 || items.get(items.size()-1).getText() != null) //If no items or last item of list isn't blank,add a blank item items.add(new ListItemAttachment()); mLayoutManager = new linearlayoutmanager(mActivity,linearlayoutmanager.VERTICAL,false); mListItemAdapter = new ListItemAttachmentAdapter(mActivity,items,mRealTimeDataPersistence); mListItemAdapter.setAttachmentDataUpdatedListener(new ListItemAttachmentAdapter.AttachmentDataUpdatedListener() { @Override public void onAttachmentDataUpdated() { mAttachmentAdapter.triggerAttachmentDataUpdatedListener(); } }); DividerItemdecoration itemdecoration = new DividerItemdecoration(mActivity,mLayoutManager.getorientation()); itemdecoration.setDrawable(ContextCompat.getDrawable(mActivity,R.drawable.item_decoration_complete_line)); mRecyclerView.setnestedScrollingEnabled(false); mRecyclerView.addItemdecoration(itemdecoration); mRecyclerView.setLayoutManager(mLayoutManager); mRecyclerView.setAdapter(mListItemAdapter); }
@Override protected void onResume() { super.onResume(); //进入到这个页面,如果账号输入框为空,则账号输入框自动获得焦点,并弹出键盘 //如果两个输入框都不为空,则登录按钮可点击 if (!user.getText().toString().equals("") && !pass.getText().toString().equals("")) { user_size = true; pass_size = true; login.setEnabled(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { login.setBackground(ContextCompat.getDrawable(LoginActivity.this,R.drawable.style_btn_login)); } } else if (user.getText().toString().equals("")) { EditTextListener.showSoftInputFromWindow(LoginActivity.this,user); } }
public boolean checkSelfPermission(String permission,int requestCode) { log.debug("checkSelfPermission " + permission + " " + requestCode); if (ContextCompat.checkSelfPermission(this,permission) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this,new String[]{permission},requestCode); return false; } if (Manifest.permission.CAMERA.equals(permission)) { ((AGApplication) getApplication()).initWorkerThread(); } return true; }
private void setThemeColor(int colorPrimary,int colorPrimaryDark) { mToolbar.setBackgroundResource(colorPrimary); mRefreshLayout.setPrimaryColorsId(colorPrimary,android.R.color.white); if (Build.VERSION.SDK_INT >= 21) { getwindow().setStatusBarColor(ContextCompat.getColor(this,colorPrimaryDark)); } }
/** * 判断有没有保存权限,有则保存,没有则申请权限 */ private void saveCurrentimage() { // 判断是否有写入SD权限 if (ContextCompat.checkSelfPermission(mContext,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { // 申请权限 ActivityCompat.requestPermissions(mContext,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE); } else { // 保存图片到相册中 StreamUtils.saveImagetoAlbum(mContext,insetPhotoBeanList.get(mIndex).getUrl()); } }
@Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_right_sample); sv = (StretchView) findViewById(R.id.sv); sv.setDrawHelper(new ArcDrawHelper(sv,ContextCompat.getColor(RightSampleActivity.this,R.color.colorPrimary),40)); rcv = (RecyclerView) findViewById(R.id.rcv); rcv.setLayoutManager(new linearlayoutmanager(RightSampleActivity.this,linearlayoutmanager.HORIZONTAL,false)); rcv.addItemdecoration(new Rcvdecoration(0,(int) getResources().getDimension(R.dimen.divider_horzontal),LinearLayoutCompat.HORIZONTAL)); rcv.setAdapter(new RecyclerView.Adapter() { @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) { return new VH(LayoutInflater.from(RightSampleActivity.this).inflate(R.layout.item_horizontal,false)); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder,int position) { } @Override public int getItemCount() { return 10; } }); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_friends_search); toolbar = (Toolbar) findViewById(R.id.toolbar1); setSupportActionBar(toolbar); getSupportActionBar().setdisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle("Find friends on Facebook"); toolbar.setTitleTextColor(ContextCompat.getColor(context,R.color.white)); recyclerView = (RecyclerView) findViewById(R.id.recyclerView); allList = new ArrayList<>(); allAdapter = new FriendAdapter(context,allList); /* allAdapter.setClickListener(new FriendAdapter.ClickListener() { @Override public void onItemClickListener(View v,int pos) { } @Override public void onFriendListener(int pos,boolean isFollowing) { } });*/ recyclerView.setLayoutManager(new linearlayoutmanager(context)); recyclerView.setnestedScrollingEnabled(false); recyclerView.setAdapter(allAdapter); setList(); }
@OnClick(R.id.root) public void unfold(){ if(!lock) { caption.setVerticalText(false); caption.requestLayout(); Rotate transition = new Rotate(); transition.setStartAngle(-90f); transition.setEndAngle(0f); transition.addTarget(caption); TransitionSet set=new TransitionSet(); set.setDuration(getResources().getInteger(R.integer.duration)); ChangeBounds changeBounds=new ChangeBounds(); set.addTransition(changeBounds); set.addTransition(transition); TextSizeTransition sizeTransition=new TextSizeTransition(); sizeTransition.addTarget(caption); set.addTransition(sizeTransition); set.setordering(TransitionSet.ORDERING_TOGETHER); caption.post(()->{ TransitionManager.beginDelayedTransition(parent,set); caption.setTextSize(TypedValue.COMPLEX_UNIT_PX,getResources().getDimension(R.dimen.unfolded_size)); caption.setTextColor(ContextCompat.getColor(getContext(),R.color.color_label)); caption.setTranslationX(0); ConstraintLayout.LayoutParams params = getParams(); params.rightToRight = ConstraintLayout.LayoutParams.PARENT_ID; params.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID; params.verticalBias = 0.78f; caption.setLayoutParams(params); }); callback.show(this); lock=true; } }
@Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_repeat); ButterKnife.bind(this); alarmClockLab = new AlarmClockBuilder().builderLab(0); tvOnce.setonClickListener(this); tvWeekDay.setonClickListener(this); tvEveryDay.setonClickListener(this); tvWeekend.setonClickListener(this); tvChoice.setonClickListener(this); String repeat = alarmClockLab.repeat; if (repeat.equals(tvOnce.getText().toString())) { tvOnce.setTextColor(ContextCompat.getColor(this,R.color.colorRed_500)); } else if (repeat.equals(tvWeekDay.getText().toString())) { tvWeekDay.setTextColor(ContextCompat.getColor(this,R.color.colorRed_500)); } else if (repeat.equals(tvEveryDay.getText().toString())) { tvEveryDay.setTextColor(ContextCompat.getColor(this,R.color.colorRed_500)); } else if (repeat.equals(tvWeekend.getText().toString())) { tvWeekend.setTextColor(ContextCompat.getColor(this,R.color.colorRed_500)); } else if (repeat.equals(tvChoice.getText().toString())) { tvChoice.setTextColor(ContextCompat.getColor(this,R.color.colorRed_500)); } }
@OnClick(R.id.customView_webView) public void showCustomWebView() { int accentColor = ThemeSingleton.get().widgetColor; if (accentColor == 0) accentColor = ContextCompat.getColor(this,R.color.accent); ChangelogDialog.create(false,accentColor) .show(getSupportFragmentManager(),"changelog"); }
private void showSnackBar(String message) { Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content),message,Snackbar.LENGTH_SHORT); View sbView = snackbar.getView(); TextView textView = (TextView) sbView .findViewById(android.support.design.R.id.snackbar_text); textView.setTextColor(ContextCompat.getColor(this,R.color.white)); snackbar.show(); }
private void init() { if (getInputType() == InputType.TYPE_CLASS_NUMBER) { // if inputType="number",it can't insert separator. setInputType(InputType.TYPE_CLASS_PHONE); } mTextWatcher = new MyTextWatcher(); this.addTextChangedListener(mTextWatcher); mRightMarkerDrawable = getCompoundDrawables()[2]; if (customizeMarkerEnable && mRightMarkerDrawable != null) { setCompoundDrawables(getCompoundDrawables()[0],getCompoundDrawables()[1],getCompoundDrawables()[3]); setHasNoSeparator(true); } if (mRightMarkerDrawable == null) { // didn't customize Marker mRightMarkerDrawable = ContextCompat.getDrawable(getContext(),R.mipmap.indicator_input_error); DrawableCompat.setTint(mRightMarkerDrawable,getCurrentHintTextColor()); if (mRightMarkerDrawable != null) { mRightMarkerDrawable.setBounds(0,mRightMarkerDrawable.getIntrinsicWidth(),mRightMarkerDrawable.getIntrinsicHeight()); } } setonFocuschangelistener(new OnFocuschangelistener() { @Override public void onFocusChange(View v,boolean hasFocus) { hasFocused = hasFocus; markerFocusChangeLogic(); iOSFocusChangeLogic(); } }); if (iOsstyleEnable) { initiOSObjects(); } if (disableEmoji) { setFilters(new InputFilter[]{new EmojiExcludeFilter()}); } }
public void setData(HomeAdapter adapter,Fragment fragment,Task current,int position,boolean isSelected,boolean nextItemIsATask) { mAdapter = adapter; mFragment = fragment; mCurrent = current; mReminderPosition = position; mCategoryIcon.setimageResource(mCurrent.getCategory().getIconRes()); mContainer.setBackgroundColor((isSelected ? ContextCompat.getColor(fragment.getActivity(),R.color.gray_300) : Color.TRANSPARENT )); mAttachmentList.setColorFilter(ContextCompat.getColor(mFragment.getActivity(),(hasAttachmentsOfType(AttachmentType.LIST) ? R.color.icons_enabled : R.color.icons_disabled))); mAttachmentLink.setColorFilter(ContextCompat.getColor(mFragment.getActivity(),(hasAttachmentsOfType(AttachmentType.LINK) ? R.color.icons_enabled : R.color.icons_disabled))); mAttachmentAudio.setColorFilter(ContextCompat.getColor(mFragment.getActivity(),(hasAttachmentsOfType(AttachmentType.AUdio) ? R.color.icons_enabled : R.color.icons_disabled))); mAttachmentimage.setColorFilter(ContextCompat.getColor(mFragment.getActivity(),(hasAttachmentsOfType(AttachmentType.IMAGE) ? R.color.icons_enabled : R.color.icons_disabled))); mAttachmentText.setColorFilter(ContextCompat.getColor(mFragment.getActivity(),(hasAttachmentsOfType(AttachmentType.TEXT) ? R.color.icons_enabled : R.color.icons_disabled))); mTitle.setText(mCurrent.getTitle()); if(!mCurrent.getDescription().isEmpty()) mDescription.setText(mCurrent.getDescription()); else mDescription.setText(""); if(current.getReminderType() == ReminderType.ONE_TIME && current.getReminder() != null) { DateFormat df = SharedPreferenceUtil.getDateFormat(mFragment.getActivity()); mDate.setText(df.formatCalendar(((OneTimeReminder)current.getReminder()).getDate())); mTime.setText(((OneTimeReminder)current.getReminder()).getTime().toString()); } else { mDate.setText("-"); mTime.setText("-"); } mItemdecoration.setVisibility(nextItemIsATask ? View.VISIBLE : View.INVISIBLE); }
private void startRecordWithPerm() { if (android.os.Build.VERSION.SDK_INT >= M) { if (ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { //进行权限请求 ActivityCompat.requestPermissions(this,EXTERNAL_STORAGE_REQ_AUdio_CODE); } else startRecord(); } else startRecord(); }
private void reveal() { appBarLayout.setBackgroundColor(ContextCompat.getColor(this,R.color.colorPrimary)); final Pair<Float,Float> center = ViewUtils.getCenter(revealImage); final Animator animator = ViewAnimationUtils.createCircularReveal(appBarLayout,center.first.intValue(),center.second.intValue(),appBarLayout.getWidth()); animator.setDuration(TRANSITION_DURATION); toolbarImageView.setVisibility(View.VISIBLE); animator.start(); }
DevicesAdapter(Context context,DeviceAdapterListener listener) { this.listener = listener; red = ContextCompat.getColor(context,R.color.mojo); green = ContextCompat.getColor(context,R.color.fern); connected = context.getString(R.string.status_connected); disconnected = context.getString(R.string.status_disconnected); }
ApplicationContext注入Bean(多线程中注入Bean)
文章目录
- 前言
- 一、线程中注入Service层或Dao层
- 总结
前言
通常我们用一下几种方式注入 :
1、
@Autowired
是通过 byType 的方式去注入的, 使用该注解,要求接口只能有一个实现类。
2、@Resource
可以通过 byName 和 byType的方式注入, 默认先按 byName的方式进行匹配,如果匹配不到,再按 byType的方式进行匹配。
3、@Qualifier
注解可以按名称注入, 但是注意是 类名。
一、线程中注入Service层或Dao层
有些情况我们需要在工具类或在new一个线程之后,线程中注入Service层或Dao层,
这时候用以上方法是注入不进去
用以下方法即可注入:
package com.java.base.config;
import java.lang.annotation.Annotation;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
/***
*
* <p>Title: MyApplicationContext</p>
* <p>Description: ApplicationContextAware 通过它spring容器会自动把上下文环境对象调用ApplicationContextAware接口中的setApplicationContext方法。
* 通过这个上下文环境对象得到spring容器中的Bean
* 在我们写的工具类获取线程中不能直接通过Spring注入,这个时候就需要通过ApplicationContext获取Bean
* </p>
* @author shy
*/
@Service
public class MyApplicationContext implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static <T> T getBean(final Class<T> requiredType) {
return context.getBean(requiredType);
}
public static <T> T getBean(final String beanName) {
@SuppressWarnings("unchecked")
final T bean = (T) context.getBean(beanName);
return bean;
}
public static <T> Map<String, T> getBeans(final Class<T> requiredType) {
return context.getBeansOfType(requiredType);
}
public static Map<String, Object> getBeansWithAnnotation(final Class<? extends Annotation> annotationType) {
return context.getBeansWithAnnotation(annotationType);
}
}
private XXXrService xxxService = MyApplicationContext.getBean(XXXService.class);
总结
如果此篇文章有帮助到您, 希望打大佬们能
关注
、点赞
、收藏
、评论
支持一波,非常感谢大家!
如果有不对的地方请指正!!!
参考1
bean实例化的三种方式 bean标签常用属性 单例模式和多例模式的对象 BeanFactory和ApplicationContext:
bean实例化的三种方式 bean标签常用属性 单例模式和多例模式的对象 beanfactory和ApplicationContext:
- 学习网站/博客:
- 1.bean实例化的三种方式:
- 页面结构整体布局:
- 运行结果如下:
- 代码如下:
- pom.xml:
- Student:
- MyStaticFactory :
- MyInstanceFactory :
- Test:
- spring-1.xml:
- 2.bean标签常用属性:
- 代码整体布局:
- 运行结果:
- 添加/修改的代码如下:
- spring-2.xml:(添加)
- Student:(修改)
- (test)Test2:
- 3.单例模式和多例模式的对象:
- 运行结果:
- God:
- Test:
- (singleton)God:(添加)
- (singleton)Test:(添加)
- 4.BeanFactory和ApplicationContext:
学习网站/博客:
spring https://spring.io/
The loC Container https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans
Spring官方文档(中文版!!!) https://blog.csdn.net/li1376417539/article/details/104951358/
1.bean实例化的三种方式:
页面结构整体布局:
运行结果如下:
代码如下:
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>lesson0820_spring</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!--引入spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.18</version>
</dependency>
</dependencies>
</project>
Student:
package com.entity;
public class Student {
public Student(){
System.out.println("这是Student的构造方法...");
}
public void introduce(){
System.out.println("我是一个学生");
}
}
MyStaticFactory :
package com.factory;
import com.entity.Student;
/**
* 静态工厂
*/
public class MyStaticFactory {
/**
* 静态返回学生实例
* @return
*/
public static Student createInstance(){
System.out.println("调用静态工厂.....MyStaticFactory...createInstance");
return new Student();
}
}
MyInstanceFactory :
package com.factory;
import com.entity.Student;
/**
* 实例工厂
*/
public class MyInstanceFactory {
/**
* 定义创建对象的实例方法
* @return
*/
public Student createInstance(){
return new Student();
}
}
Test:
package com.test;
import com.entity.Student;
import com.factory.MyInstanceFactory;
import com.factory.MyStaticFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClasspathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
//Student student = new Student();
//创建spring bean容器对象
ApplicationContext ac = new ClasspathXmlApplicationContext("spring-1.xml");
// Student student = ac.getBean(Student.class);
//静态工厂创建的对象,通过id名字,获取bean对象
// Student s = (Student) ac.getBean("stu");
// s.introduce();
//实例工厂方式创建对象
Student s2 = (Student) ac.getBean("stu2");
s2.introduce();
}
}
spring-1.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
default-lazy-init="true"
>
<!--class属性必须配置,用于指明要创建的bean对象的类型
lazy-init="true":延迟加载(懒汉模式)
1.bean的方式定义对象
-->
<!-- <beanlazy-init="true"/>-->
<!--2.静态工厂方式创建学生对象-->
<bean id="stu"factory-method="createInstance"/>
<!--3.实例工厂创建对象-->
<bean id="fac"/>
<bean id="stu2" factory-bean="fac" factory-method="createInstance"/>
</beans>
2.bean标签常用属性:
代码整体布局:
运行结果:
添加/修改的代码如下:
spring-2.xml:(添加)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
>
<!--
class属性:用于指定要创建的bean对象的类型,必须写的属性
id属性: 用于唯一标识该类型对象,不能重复,但是可以省略
name属性: 可以认为是对bean对象起的别名,可以设置多个名字,用空格或逗号分隔。
现在一般不用
lazy-init:是否是延迟加载(懒汉,饿汉)。可以在beans中配置全局的延迟加载属性default-lazy-init
scope:定义创建对象的方式和范围,singleton(单例),prototype(多例),request,session,global-session
singleton(单例):表示容器中,只有一个对象,每次获取的都是同一个对象
prototype(多例):每次都是new一个新的对象返回
init-method:定义bean生命周期的初始化函数
destroy-method:定义bean生命周期的销毁函数
-->
<bean id="stu"
name="s1 s2"lazy-init="true"
scope="prototype"
init-method="initStu"
destroy-method="destroyStu" />
</beans>
Student:(修改)
package com.entity;
import org.springframework.beans.factory.annotation.Autowired;
public class Student {
public Student(){
System.out.println("这是Student的构造方法...");
}
//自我介绍
public void introduce(){
System.out.println("我是一个学生");
}
//学生初始化
public void initStu(){
System.out.println("调用了学生的初始化方法");
}
//学生销毁
public void destroyStu(){
System.out.println("调用了学生的销毁方法");
}
}
(test)Test2:
package com.test;
import com.entity.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClasspathXmlApplicationContext;
public class Test2 {
public static void main(String[] args) {
//创建spring容器
ApplicationContext ctx = new ClasspathXmlApplicationContext("spring-2.xml");
//根据id获取学生对象
Student s1 =(Student) ctx.getBean("stu");
System.out.println("s1:"+s1);
//根据类型获取学生对象
Student s2 = (Student) ctx.getBean(Student.class);
System.out.println("s2:"+s2);
//根据id和类型获取学生对象
Student s3 = ctx.getBean("stu",Student.class);
System.out.println("s3:"+s3);
//根据name属性获取学生对象
Student s4 = (Student) ctx.getBean("s1");
Student s5 = (Student) ctx.getBean("s2");
System.out.println("s4:"+s4);
System.out.println("s5:"+s5);
}
}
3.单例模式和多例模式的对象:
运行结果:
God:
package com.singleton;
public class God {
public void createWorld(){
System.out.println("上帝创造了世界....");
}
}
Test:
package com.singleton;
public class Test {
public static void main(String[] args) {
God god = new God();
god.createWorld();
System.out.println(god);
God god2 = new God();
god2.createWorld();
System.out.println(god2);
}
}
(singleton)God:(添加)
package com.singleton;
public class God {
//3.定义静态私有对象
private static God god;
//1.构造私有化
private God(){
}
//2.定义静态工厂获取实例的方法,用于获取对象
public static God createInstance(){
if (god==null){
god = new God();
}
return god;
}
public void createWorld(){
System.out.println("上帝创造了世界....");
}
}
(singleton)Test:(添加)
package com.singleton;
public class Test {
public static void main(String[] args) {
God god = God.createInstance();
god.createWorld();
System.out.println(god);
God god2 = God.createInstance();
god2.createWorld();
System.out.println(god2);
}
}
4.beanfactory和ApplicationContext:
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
java – Spring 3 applicationContext-security-JDBC.xml有bean:bean不是bean?
有人可以告诉我在我的ApplicationContext中我必须使用bean:bean而不是bean以及如何修复它.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/friends/**" access="hasRole('ROLE_USER')" />
<form-login login-page="/login.html"
default-target-url="/index.html" always-use-default-target="true"
authentication-failure-url="/login.html?authFailed=true" />
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource" />
</authentication-provider>
</authentication-manager>
<beans:bean id="propertyConfigurer"https://www.jb51.cc/tag/fig/" target="_blank">fig.PropertyPlaceholderConfigurer">
<beans:property name="location" value="classpath:jdbc.properties" />
</beans:bean>
<beans:bean id="dataSource">
<beans:property name="driverClassName" value="${database.driver}" />
<beans:property name="url" value="${database.url}" />
<beans:property name="username" value="${database.user}" />
<beans:property name="password" value="${database.password}" />
<beans:property name="initialSize" value="5" />
<beans:property name="maxActive" value="10" />
</beans:bean>
</beans:beans>
解决方法:
说明.基本上你在这里处理XML命名空间. Spring配置允许您使用来自不同命名空间的配置元素作为扩展基本bean命名空间配置的方法,使用方便的特定于域的配置,如上面的安全配置.
如果您的配置文件集中在其中一个扩展名称空间上 – 再次,让我们使用安全性作为示例 – 如果您将默认名称空间声明为扩展名称空间而不是标准bean名称空间,它可以清理该文件.那是什么
xmlns="http://www.springframework.org/schema/security"
确实 – 它使安全性成为默认命名空间,这意味着您不必使用sec:或security:作为前缀.
但是当您将安全性设置为默认值时,则在使用beans命名空间元素时必须明确.因此bean:前缀.
解.如果您更喜欢bean作为默认值,只需将默认命名空间更改为beans:
xmlns="http://www.springframework.org/schema/beans"
替代方案.或者,如果你想输入更短的东西,你可以这样做
xmlns:b="http://www.springframework.org/schema/beans"
代替
xmlns:beans="http://www.springframework.org/schema/beans"
这将允许你做的事情
<b:bean id="beanId"/>
我们今天的关于java.beans.beancontext.BeanContextSupport的实例源码和java.beans.introspection的分享就到这里,谢谢您的阅读,如果想了解更多关于android.support.v4.content.ContextCompat的实例源码、ApplicationContext注入Bean(多线程中注入Bean)、bean实例化的三种方式 bean标签常用属性 单例模式和多例模式的对象 BeanFactory和ApplicationContext:、java – Spring 3 applicationContext-security-JDBC.xml有bean:bean不是bean?的相关信息,可以在本站进行搜索。
本文标签: