在开发过程中经常需要将代码封装后交付使用,在Android中也是如此

下面是封装的步骤

创建一个没有Activity的Android的工程

Android中以JAR形式封装控件 或者类库

1将res中的资源全部删除

Android中以JAR形式封装控件 或者类库

2删除AndroidManifest.xml中资源的引用

类似这样的代码android:icon="@drawable/icon" android:label="@string/app_name"

其实AndroidManifest在我们发布jar的时候并不发布,之所以这样做不过是为了编译时好看而已。

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="MyAndroid.Widget" android:versionCode="1" android:versionName="1.0"> </manifest>

3建立自己的Java控件

package MyAndroid.Widget; import java.io.InputStream; import java.net.URL; import android.content.Context; import android.content.res.AssetManager; import android.util.AttributeSet; import android.view.View; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; public class MyView extends View { public MyView(Context context) { super(context); // TODO Auto-generated constructor stub } public MyView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub } public MyView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); canvas.drawColor(Color.GRAY); Paint paint=new Paint(); paint.setAntiAlias(true); paint.setColor(Color.RED); canvas.drawRect(new Rect(10,10,20,20), paint); Bitmap bgImg = getImageFromAssetFile("png-040.png"); canvas.drawBitmap(bgImg, 20, 20, null); } private Bitmap getImageFromAssetFile(String fileName){ Bitmap image = null; try{ AssetManager am = getContext().getAssets(); InputStream is = am.open(fileName); image = BitmapFactory.decodeStream(is); is.close(); }catch(Exception e){ } return image; } }

注意 如果要在jar中封装自己的资源,要把资源放入assets目录中

我的demo包中我打入了一个png图片,资源的名字不能和工程中的资源名字重复。

4 在 Package Explorer Panel的工程名上 点击右键,选择 Export

Android中以JAR形式封装控件 或者类库

Java-> JAR file 点下一步

Android中以JAR形式封装控件 或者类库

去掉.classpath, .project, AndroidManifest.xlm, default.properties上的选择

输入 Jar的输出路径 点Finish

Android中以JAR形式封装控件 或者类库

这样我们的libary 就创建完成了

使用方法

在打开工程的Properties窗口

选择Java Build Path中的Libraries页

点击 Add External JARs 选择我们刚刚生成的jar文件

Android中以JAR形式封装控件 或者类库

这样我们就可以使用了编译好的jar库了

Android中以JAR形式封装控件 或者类库

<MyAndroid.Widget.MyView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/myview"
>
</MyAndroid.Widget.MyView>

MyView myview=(MyView) findViewById(R.id.myview);

相关文章:

  • 2021-06-15
  • 2022-12-23
  • 2022-12-23
  • 2023-03-13
  • 2021-10-14
  • 2021-05-17
  • 2021-09-21
猜你喜欢
  • 2021-09-22
  • 2021-10-18
  • 2021-07-07
  • 2021-12-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案