如何做下面描述的事情

时间:2015-09-24 11:26:02

标签: android

我有act1.xmlact2.xml。我有两个java类文件作为java1和java2。我在java1中编写了方法,例如share,capture,其活动是act1正常工作。我只想在java2中使用那些活动为act2.xml的onClick方法。

 public class SingleItemView extends Activity {
 final static int CAMERA_RESULT = 0;
 ImageView imv;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from singleitemview.xml
    setContentView(R.layout.singleitemview);

    // Get position from intent passed from MainActivity.java
    Intent i = getIntent();

    int position = i.getExtras().getInt("id");

    // Open the Image adapter
    ImageAdapter imageAdapter = new ImageAdapter(this);

    // Locate the ImageView in singleitemview.xml
    ImageView imageView = (ImageView) findViewById(R.id.image);

    // Get image and position from ImageAdapter.java and set into ImageView
    imageView.setImageResource(imageAdapter.mThumbIds[position]);


    i = new Intent("android.media.action.IMAGE_CAPTURE");
    startActivityForResult(i, CAMERA_RESULT);
        }
protected void onActivityResult(int requestCode, int resultCode, Intent       intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (resultCode == RESULT_OK) {
        Bundle extras = intent.getExtras();
        Bitmap bmp = (Bitmap) extras.get("data");
        imv = (ImageView) findViewById(R.id.imageView);
        imv.setImageBitmap(bmp);

    }
}

方法我想重用。

       btntakephoto.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {


            File photostorage =    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            photofile = new File(photostorage, (System.currentTimeMillis()) + ".jpg");


            Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //intent to start camera
            i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photofile));
            startActivityForResult(i, TAKENPHOTO);
        }
    });

2 个答案:

答案 0 :(得分:0)

如果您只想使用firstActivity.class OnClick方法来使用SecondActivity.class的某种方法,那么您可以使用BroadcastManager

但是,如果您想将某些数据从FirstActivity.java传递到SecondActivity.java,那么只需使用IntentBundle

答案 1 :(得分:0)

定义一个类,如下所示:

public class ClickHandler implements View.OnClickListener {
    @Override
    public void onClick(View v) {
        // Your code goes here
    }
}

然后在你的activity1&活动2,像这样使用setOnClickListener:

Button button = (Button)findViewById(R.id.act1_button);
button.setOnClickListener(new ClickHandler());

Button button = (Button)findViewById(R.id.act2_button);
button.setOnClickListener(new ClickHandler());