我是android的初学者,在我的项目中,我想从库中添加文本和图像,从添加活动和发送到主要活动以在列表视图中显示, 这是主要活动
上的添加按钮的代码export const addtest = (tests) => ({
type: 'ADD_TEST_UNIT',
tests
});
这是添加活动的代码
Intent intentForAdd = new Intent(getApplicationContext(),addActivity.class);
startActivityForResult(intentForAdd,requestcode2);
这是MainActivity中的onActivityResult方法,用于从列表视图中添加活动和置换中接收数据,如何从添加活动接收图像?
boolean ownImage = false;
final private int PICK_IMAGE = 1;
byte[] imageDat;
Button buttonAdd,cameraB;
ImageView imageAdd;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
idAdd = findViewById(R.id.idAdd);
nameAdd = findViewById(R.id.nameAdd);
cameraB = findViewById(R.id.cameraB);
buttonAdd = findViewById(R.id.buttonAdd);
imageAdd = findViewById(R.id.imageAdd);
buttonAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int idA = Integer.parseInt(idAdd.getText().toString());
String nameA = nameAdd.getText().toString();
Intent intent = new Intent();
intent.putExtra("NameAdd", nameA);
intent.putExtra("IdAdd", idA);
intent.putExtra("ImageAdd",imageData);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
cameraB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent,"Choose Image From"),PICK_IMAGE);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_CANCELED){
if (requestCode == PICK_IMAGE){
try{
Uri uri = data.getData();
Bitmap bitmap;
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
imageAdd.setImageBitmap(bitmap);
ownImage = true;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100,byteArrayOutputStream);
imageData = byteArrayOutputStream.toByteArray();
} catch (Exception e) {
Toast.makeText(getBaseContext(),e.toString(),Toast.LENGTH_LONG).show();
}
}else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
最后这是员工类
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == requestcode2){
if(resultCode == Activity.RESULT_OK){
String nameAdd = data.getStringExtra("NameAdd");
int idAdd = data.getIntExtra("IdAdd", 0);
byte[] img = data.getByteArrayExtra("ImageAdd");
Employee e = new Employee(idAdd,nameAdd,img);
list.add(e);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(),"Added Successfully",Toast.LENGTH_LONG).show();
}
}
}
我添加文本时代码运行正常,但Image中的问题没有显示在列表中
答案 0 :(得分:0)
如果您的唯一目标是保存变量并与其他活动共享(您不是这样做以了解如何从意图中获取图像),您是否只能将变量声明为静态?