В onCreate () моей деятельности я добавляю следующий слушатель onClick к кнопке, наложенной на мой предварительный просмотр SurfaceView (в Интернете есть множество примеров для предварительного просмотра):
ImageButton useOtherCamera = (ImageButton) findViewById(R.id.useOtherCamera);
//if phone has only one camera, hide "switch camera" button
if(Camera.getNumberOfCameras() == 1){
useOtherCamera.setVisibility(View.INVISIBLE);
}
else {
useOtherCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (inPreview) {
camera.stopPreview();
}
//NB: if you don't release the current camera before switching, you app will crash
camera.release();
//swap the id of the camera to be used
if(currentCameraId == Camera.CameraInfo.CAMERA_FACING_BACK){
currentCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
}
else {
currentCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
}
camera = Camera.open(currentCameraId);
//Code snippet for this method from somewhere on android developers, i forget where
setCameraDisplayOrientation(CameraActivity.this, currentCameraId, camera);
try {
//this step is critical or preview on new camera will no know where to render to
camera.setPreviewDisplay(previewHolder);
} catch (IOException e) {
e.printStackTrace();
}
camera.startPreview();
}
На моем тестовом устройстве задняя камера имеет идентификатор 0, а передняя имеет идентификатор 1. Я предлагаю использовать статические переменные Camera.CameraInfo для идентификаторов вашей камеры, а не для значений в жестком коде. Я уверен, что это вызовет проблемы только на других устройствах.
Вы можете создать свой собственный класс, унаследованный от DataGridViewCell, и переопределить соответствующие виртуальные члены (InitializeEditingControls, EditType, возможно, несколько других). Затем вы можете создать DataGridViewColumn с экземпляром этого класса в качестве шаблона ячейки
Вы можете создать столбец шаблона с обоими элементами управления, скрыть тот, который вам не нужен, и привязать другой к источнику данных в коде.
Недавно у меня был аналогичный вариант использования, и я написал что-то вроде приведенного ниже кода:
Напишите собственный класс Cell и Column и переопределите методы EditType и InitializeEditingControl в ячейке, чтобы при необходимости возвращать различные элементы управления (здесь я просто привязываю данные к списку настраиваемого класса с помощью. useCombo поле, указывающее, какой элемент управления использовать):
// Define a column that will create an appropriate type of edit control as needed.
public class OptionalDropdownColumn : DataGridViewColumn
{
public OptionalDropdownColumn()
: base(new PropertyCell())
{
}
public override DataGridViewCell CellTemplate
{
get
{
return base.CellTemplate;
}
set
{
// Ensure that the cell used for the template is a PropertyCell.
if (value != null &&
!value.GetType().IsAssignableFrom(typeof(PropertyCell)))
{
throw new InvalidCastException("Must be a PropertyCell");
}
base.CellTemplate = value;
}
}
}
// And the corresponding Cell type
public class OptionalDropdownCell : DataGridViewTextBoxCell
{
public OptionalDropdownCell()
: base()
{
}
public override void InitializeEditingControl(int rowIndex, object
initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
{
// Set the value of the editing control to the current cell value.
base.InitializeEditingControl(rowIndex, initialFormattedValue,
dataGridViewCellStyle);
DataItem dataItem = (DataItem) this.OwningRow.DataBoundItem;
if (dataItem.useCombo)
{
DataGridViewComboBoxEditingControl ctl = (DataGridViewComboBoxEditingControl)DataGridView.EditingControl;
ctl.DataSource = dataItem.allowedItems;
ctl.DropDownStyle = ComboBoxStyle.DropDownList;
}
else
{
DataGridViewTextBoxEditingControl ctl = (DataGridViewTextBoxEditingControl)DataGridView.EditingControl;
ctl.Text = this.Value.ToString();
}
}
public override Type EditType
{
get
{
DataItem dataItem = (DataItem)this.OwningRow.DataBoundItem;
if (dataItem.useCombo)
{
return typeof(DataGridViewComboBoxEditingControl);
}
else
{
return typeof(DataGridViewTextBoxEditingControl);
}
}
}
}
Затем просто добавьте столбец в свой DataGridView этого типа, и следует использовать правильный элемент управления редактирования.