android unity 文件读写_Unity 读取android自定义控件及布局文件

本文介绍了在Unity游戏中如何调用Android原生功能,特别是如何处理Unity重新打包导致的资源文件无法正常读取的问题。通过创建自定义控件、修改资源文件读取方式,以及在Android项目中引用这些控件,实现了Unity与Android之间的有效交互。
摘要由CSDN通过智能技术生成

在unity中开发游戏时,难免会用到一些android的原生功能,另外在调用第三方sdk的过程中也会经常有类似的需求。但是在unity中调用android jar包中的布局文件或者图片等资源时,由于unity的重新打包,生成了新的R文件,导致原来jar包中通过R读取的资源文件都找不到。所以就必须修改读取方式来达到正常读取的需求。

1、创建一个自定义控件。

1)布局文件如下:

如图:

2)代码中读取布局文件,获得控件实例。

public class MyView extendsLinearLayout{privateImageView img;privateEditText edt;publicMyView(Context context) {super(context);//TODO Auto-generated constructor stub

}publicMyView(Context context, AttributeSet attrs) {super(context, attrs);//TODO Auto-generated constructor stub

LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);/**此种做法是无效的,空引用

View v = inflater.inflate(R.layout.mybtnlayout, null);

img = (ImageView)v.findViewById(R.id.imageView1);

edt = (EditText)v.findViewById(R.id.editText1);*/

/***有效的做法*/View v= inflater.inflate(MResource.getIdByName(context, "layout", "mybtnlayout"), this);

img=(ImageView)v.findViewById(MResource.getIdByName(context, "id", "imageView1"));

edt=(EditText)v.findViewById(MResource.getIdByName(context, "id", "editText1"));

}/*** 设置图片资源*/

public void setImageResource(intresId) {

img.setImageResource(resId);

}/*** 设置显示的文字*/

public voidsetTextViewText(String text) {

edt.setText(text);

}

}

3)重要:资源文件读取方式:

packagecom.example.myview;importjava.io.IOException;importjava.io.InputStream;importandroid.content.Context;importandroid.content.res.AssetManager;importandroid.graphics.drawable.Drawable;public classMResource {/*** 根据资源的名字获取其ID值

*

*@authormining

**/

public static intgetIdByName(Context context, String className, String name) {//此处的包名不能通过context获取,因为在unity中这样获取到的是unity额外设定的包名,不是jar包里面的包名

String packageName = "com.example.updateg

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值