草庐IT

android - 如何在 XML 中扩展自定义 View ?

coder 2023-12-15 原文

这是我第一次尝试在 XML 中使用自定义 View ,我不确定该怎么做。任何帮助将不胜感激。

我正在使用 Interfuser's coverflow并且需要在我可以以 XML 格式使用它的地方扩展它,以便我可以在 View 中添加其他组件。

希望下面的代码将显示我需要的(尝试做的)。我相信这比我想象的要容易。

感谢

布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >

<com.myapp.home.CoverFlow
    android:id="@+id/coverFlow1"
    android:layout_width="wrap_content"
    android:layout_height="10dip" />

</LinearLayout>

CoverFlow.java:

package com.myapp.home;

public class CoverFlow extends Gallery {

/**
 * Graphics Camera used for transforming the matrix of ImageViews
 */
private Camera mCamera = new Camera();

/**
 * The maximum angle the Child ImageView will be rotated by
 */    
private int mMaxRotationAngle = 60;

/**
 * The maximum zoom on the centre Child
 */
private int mMaxZoom = -120;

/**
 * The Centre of the Coverflow 
 */   
private int mCoveflowCenter;

public CoverFlow(Context context) {
super(context);
this.setStaticTransformationsEnabled(true);
}

public CoverFlow(Context context, AttributeSet attrs) {
super(context, attrs);
    this.setStaticTransformationsEnabled(true);
}

public CoverFlow(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setStaticTransformationsEnabled(true);   
}

/**
 * Get the max rotational angle of the image
* @return the mMaxRotationAngle
*/
public int getMaxRotationAngle() {
return mMaxRotationAngle;
}

/**
* Set the max rotational angle of each image
* @param maxRotationAngle the mMaxRotationAngle to set
*/
public void setMaxRotationAngle(int maxRotationAngle) {
mMaxRotationAngle = maxRotationAngle;
}

/**
* Get the Max zoom of the centre image
* @return the mMaxZoom
*/
public int getMaxZoom() {
return mMaxZoom;
}

/**
* Set the max zoom of the centre image
* @param maxZoom the mMaxZoom to set
*/
public void setMaxZoom(int maxZoom) {
mMaxZoom = maxZoom;
}

/**
 * Get the Centre of the Coverflow
 * @return The centre of this Coverflow.
 */
private int getCenterOfCoverflow() {
    return (getWidth() - getPaddingLeft() - getPaddingRight()) / 2 + getPaddingLeft();
}

/**
 * Get the Centre of the View
 * @return The centre of the given view.
 */
private static int getCenterOfView(View view) {
    return view.getLeft() + view.getWidth() / 2;
}  
/**
* {@inheritDoc}
*
* @see #setStaticTransformationsEnabled(boolean) 
*/ 
protected boolean getChildStaticTransformation(View child, Transformation t) {

final int childCenter = getCenterOfView(child);
final int childWidth = child.getWidth() ;
int rotationAngle = 0;

t.clear();
t.setTransformationType(Transformation.TYPE_MATRIX);

    if (childCenter == mCoveflowCenter) {
        transformImageBitmap((ImageView) child, t, 0);
    } else {      
        rotationAngle = (int) (((float) (mCoveflowCenter - childCenter)/ childWidth) *      mMaxRotationAngle);
        if (Math.abs(rotationAngle) > mMaxRotationAngle) {
         rotationAngle = (rotationAngle < 0) ? -mMaxRotationAngle : mMaxRotationAngle;   
        }
        transformImageBitmap((ImageView) child, t, rotationAngle);         
    }    

return true;
}

/**
* This is called during layout when the size of this view has changed. If
* you were just added to the view hierarchy, you're called with the old
* values of 0.
*
* @param w Current width of this view.
* @param h Current height of this view.
* @param oldw Old width of this view.
* @param oldh Old height of this view.
 */
 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
  mCoveflowCenter = getCenterOfCoverflow();
  super.onSizeChanged(w, h, oldw, oldh);
 }

 /**
  * Transform the Image Bitmap by the Angle passed 
  * 
  * @param imageView ImageView the ImageView whose bitmap we want to rotate
  * @param t transformation 
  * @param rotationAngle the Angle by which to rotate the Bitmap
  */
 private void transformImageBitmap(ImageView child, Transformation t, int rotationAngle) {            
  mCamera.save();
  final Matrix imageMatrix = t.getMatrix();;
  final int imageHeight = child.getLayoutParams().height;;
  final int imageWidth = child.getLayoutParams().width;
  final int rotation = Math.abs(rotationAngle);

  mCamera.translate(0.0f, 0.0f, 100.0f);

  //As the angle of the view gets less, zoom in     
  if ( rotation < mMaxRotationAngle ) {
   float zoomAmount = (float) (mMaxZoom +  (rotation * 1.5));
   mCamera.translate(0.0f, 0.0f, zoomAmount);          
  } 

  mCamera.rotateY(rotationAngle);
  mCamera.getMatrix(imageMatrix);               
  imageMatrix.preTranslate(-(imageWidth/2), -(imageHeight/2)); 
  imageMatrix.postTranslate((imageWidth/2), (imageHeight/2));
  mCamera.restore();
}
}

主.java

public class Main extends Activity {

@Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);

 requestWindowFeature(Window.FEATURE_NO_TITLE);

 CoverFlow coverFlow;
 coverFlow = new CoverFlow(this);

 coverFlow.setAdapter(new ImageAdapter(this));

 ImageAdapter coverImageAdapter =  new ImageAdapter(this);

 coverImageAdapter.createReflectedImages();

 coverFlow.setAdapter(coverImageAdapter);

 coverFlow.setSpacing(-25);
 coverFlow.setSelection(4, true);
 coverFlow.setAnimationDuration(1000);


 setContentView(R.layout.main);
 }

public class ImageAdapter extends BaseAdapter {
 int mGalleryItemBackground;
 private Context mContext;

 private FileInputStream fis;

 private Integer[] mImageIds = {
   R.drawable.a,
         R.drawable.b,
         R.drawable.c,
         R.drawable.d,
         R.drawable.e,
         R.drawable.f,
         R.drawable.g,
         R.drawable.h,
         R.drawable.i
 };

 private ImageView[] mImages;

 public ImageAdapter(Context c) {
  mContext = c;
  mImages = new ImageView[mImageIds.length];
 }
public boolean createReflectedImages() {
      //The gap we want between the reflection and the original image
      final int reflectionGap = 4;


      int index = 0;
      for (int imageId : mImageIds) {
    Bitmap originalImage = BitmapFactory.decodeResource(getResources(), 
      imageId);
       int width = originalImage.getWidth();
       int height = originalImage.getHeight();


       //This will not scale but will flip on the Y axis
       Matrix matrix = new Matrix();
       matrix.preScale(1, -1);

       //Create a Bitmap with the flip matrix applied to it.
       //We only want the bottom half of the image
       Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, height/2, width, height/2, matrix, false);


       //Create a new bitmap with same width but taller to fit reflection
       Bitmap bitmapWithReflection = Bitmap.createBitmap(width 
         , (height + height/2), Config.ARGB_8888);

      //Create a new Canvas with the bitmap that's big enough for
      //the image plus gap plus reflection
      Canvas canvas = new Canvas(bitmapWithReflection);
      //Draw in the original image
      canvas.drawBitmap(originalImage, 0, 0, null);
      //Draw in the gap
      Paint deafaultPaint = new Paint();
      canvas.drawRect(0, height, width, height + reflectionGap, deafaultPaint);
      //Draw in the reflection
      canvas.drawBitmap(reflectionImage,0, height + reflectionGap, null);

      //Create a shader that is a linear gradient that covers the reflection
      Paint paint = new Paint(); 
      LinearGradient shader = new LinearGradient(0, originalImage.getHeight(), 0, 
        bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, 
        TileMode.CLAMP); 
      //Set the paint to use this shader (linear gradient)
      paint.setShader(shader); 
      //Set the Transfer mode to be porter duff and destination in
      paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); 
      //Draw a rectangle using the paint with our linear gradient
      canvas.drawRect(0, height, width, 
        bitmapWithReflection.getHeight() + reflectionGap, paint); 

      ImageView imageView = new ImageView(mContext);
      imageView.setImageBitmap(bitmapWithReflection);
      imageView.setLayoutParams(new CoverFlow.LayoutParams(120, 180));
      imageView.setScaleType(ScaleType.MATRIX);
      mImages[index++] = imageView;

      }
   return true;
 }

 public int getCount() {
     return mImageIds.length;
 }

 public Object getItem(int position) {
     return position;
 }

 public long getItemId(int position) {
     return position;
 }

 public View getView(int position, View convertView, ViewGroup parent) {

  //Use this code if you want to load from resources
     ImageView i = new ImageView(mContext);
     i.setImageResource(mImageIds[position]);
     i.setLayoutParams(new CoverFlow.LayoutParams(130, 130));
     i.setScaleType(ImageView.ScaleType.CENTER_INSIDE); 

     //Make sure we set anti-aliasing otherwise we get jaggies
     BitmapDrawable drawable = (BitmapDrawable) i.getDrawable();
     drawable.setAntiAlias(true);
     return i;

  //return mImages[position];
 }
 /** Returns the size (0.0f to 1.0f) of the views 
  * depending on the 'offset' to the center. */ 
  public float getScale(boolean focused, int offset) { 
    /* Formula: 1 / (2 ^ offset) */ 
      return Math.max(0, 1.0f / (float)Math.pow(2, Math.abs(offset))); 
  } 

}
}

最佳答案

LayoutInflater inflater = (LayoutInflater) this
 .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View v = inflater.inflate(R.layout."layout here", null, false);

并使用,例如

 TextView tv=(TextView)v.findViewById(R,id."id here");

关于android - 如何在 XML 中扩展自定义 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8369717/

有关android - 如何在 XML 中扩展自定义 View ?的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  3. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  4. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  5. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  6. ruby-on-rails - 渲染另一个 Controller 的 View - 2

    我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>

  7. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  8. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  9. ruby - 使用 C 扩展开发 ruby​​gem 时,如何使用 Rspec 在本地进行测试? - 2

    我正在编写一个包含C扩展的gem。通常当我写一个gem时,我会遵循TDD的过程,我会写一个失败的规范,然后处理代码直到它通过,等等......在“ext/mygem/mygem.c”中我的C扩展和在gemspec的“扩展”中配置的有效extconf.rb,如何运行我的规范并仍然加载我的C扩展?当我更改C代码时,我需要采取哪些步骤来重新编译代码?这可能是个愚蠢的问题,但是从我的gem的开发源代码树中输入“bundleinstall”不会构建任何native扩展。当我手动运行rubyext/mygem/extconf.rb时,我确实得到了一个Makefile(在整个项目的根目录中),然后当

  10. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

随机推荐