2011-08-05 2 views
1

В настоящее время я работаю над кодом, написанным кем-то другим. Я могу видеть, что он реализован макет магнитофона, как показано нижеКак вставить две кнопки программно?

recorder = new MediaRecorder(); 
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT); 
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); 
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP); 

mPreview = new Preview(VideoRecorder.this,recorder); 
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); 
requestWindowFeature(Window.FEATURE_NO_TITLE); 
setContentView(mPreview); 

Моя проблема, я хочу, чтобы вставить два Button сек в этот mPreview для записи программно и остановиться.

Как я могу это сделать?

полный класс ниже

public class VideoRecorder extends Activity { 

    private SQLiteDatabase db; 
    public ArrayList<String> videocount = new ArrayList<String>(); 

    public static int x = 1; 

    public static boolean recod = false; 
    public static boolean video = true; 

    public boolean onCreateOptionsMenu(Menu menu) { 

     // TODO Auto-generated method stub 
     MenuInflater inflater = getMenuInflater(); 
     inflater.inflate(a.b.R.menu.menus, menu); 
     return true; 
    } 

    public boolean onOptionsItemSelected(MenuItem item) { 
     // TODO Auto-generated method stub 
     switch (item.getItemId()) { 
     case id.record: 

      if (video) { 

       recorder.start(); 
       recod = true; 
       video = false; 
      } else { 
       Toast.makeText(getApplicationContext(), 
         "Stop Recording First..", 2000).show(); 
      } 

      break; 
     case id.stop: 
      if (recod) { 

       String outputfilepath = "/sdcard/RdmsVideo" + x + ".3gpp"; 
       recorder.stop(); 
       recorder.release(); 
       recorder = null; 
       video = true; 
       this.db = this.openOrCreateDatabase("filestore", MODE_PRIVATE, 
         null); 
       this.db.execSQL("CREATE TABLE IF NOT EXISTS videos(urls text)"); 
       db.execSQL("insert into videos values ('" + outputfilepath 
         + "')"); 
       db.close(); 
       x++; 

       // Toast.makeText(getApplicationContext(), outputfilepath, 
       // 2000).show(); 
       Intent i = new Intent(VideoRecorder.this, sendingpage.class); 
       startActivity(i); 
       this.finish(); 

      } else { 
       Toast.makeText(getApplicationContext(), "Record First", 2000) 
         .show(); 
      } 

      // Intent intent = getIntent(); 
      // finish(); 
      // startActivity(intent); 
      break; 

     } 
     return true; 
    } 

    @Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) { 
     // TODO Auto-generated method stub 

     switch (keyCode) { 
     case KeyEvent.KEYCODE_BACK: 

      homepage ff = new homepage(); 
      if (ff.vid == 1) { 
       Intent i = new Intent(VideoRecorder.this, homepage.class); 
       startActivity(i); 
       this.finish(); 
      } else { 
       Intent i = new Intent(VideoRecorder.this, tabpage.class); 
       startActivity(i); 
       this.finish(); 
      } 

      break; 

     default: 
      break; 
     } 
     return super.onKeyDown(keyCode, event); 
    } 

    // Create objects of MediaRecorder and Preview class 
    private MediaRecorder recorder; 
    private Preview mPreview; 

    boolean flag = false; 
    boolean startedRecording = false; 
    boolean stoppedRecording = false; 

    // In this method, create an object of MediaRecorder class. Create an object 
    // of 
    // RecorderPreview class(Customized View). Add RecorderPreview class object 
    // as content of UI. 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     recorder = new MediaRecorder(); 
     recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT); 
     recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); 
     recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP); 

     mPreview = new Preview(VideoRecorder.this, recorder); 
     setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); 
     requestWindowFeature(Window.FEATURE_NO_TITLE); 
     setContentView(mPreview); 
     final LayoutParams lparams = new LayoutParams(
       LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
     final Button record = new Button(VideoRecorder.this); // Activity goes 
                   // here 
     record.setText("Record"); 
     record.setLayoutParams(lparams); 
     // record.setOnClickListener(...); 
     //mPreview.add 

    } 

    /* 
    * ! <p> Initialize the contents of the Activity's standard options menu. 
    * Menu items are to be placed in to menu. This is called on each press of 
    * menu button. In this options to start and stop recording are provided. 
    * Option for start recording has group id 0 and option to stop recording is 
    * 1. (first parameter of menu.add method). Start and stop have different 
    * group id, if recording is already started then it shows stop option else 
    * it shows start option. </p> 
    */ 

    /* 
    * ! <p> This method receives control when Item in menu option is selected. 
    * It contains implementations to be performed on selection of menu item. 
    * </p> 
    */ 

    class Preview extends SurfaceView implements SurfaceHolder.Callback { 
     // Create objects for MediaRecorder and SurfaceHolder. 
     SurfaceHolder mHolder; 
     MediaRecorder tempRecorder; 

     // Create constructor of Preview Class. In this, get an object of 
     // surfaceHolder class by calling getHolder() method. After that add 
     // callback to the surfaceHolder. The callback will inform when surface 
     // is 
     // created/changed/destroyed. Also set surface not to have its own 
     // buffers. 
     public Preview(Context context, MediaRecorder recorder) { 
      super(context); 
      tempRecorder = recorder; 
      mHolder = getHolder(); 
      mHolder.addCallback(this); 
      mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 

      // TODO Auto-generated constructor stub 
     } 

     public Surface getSurface() { 
      return mHolder.getSurface(); 
     } 

     // Implement the methods of SurfaceHolder.Callback interface 

     // SurfaceCreated : This method gets called when surface is created. 
     // In this, initialize all parameters of MediaRecorder object. 
     // The output file will be stored in SD Card. 

     public void surfaceCreated(SurfaceHolder holder) { 

      tempRecorder.setOutputFile("/sdcard/RdmsVideo" + x + ".3gpp"); 
      tempRecorder.setPreviewDisplay(mHolder.getSurface()); 
      try { 
       tempRecorder.prepare(); 
      } catch (Exception e) { 
       String message = e.getMessage(); 
       tempRecorder.release(); 
       tempRecorder = null; 
      } 
     } 

     public void surfaceDestroyed(SurfaceHolder holder) { 
      if (tempRecorder != null) { 
       tempRecorder.release(); 
       tempRecorder = null; 
      } 
     } 

     public void surfaceChanged(SurfaceHolder holder, int format, int w, 
       int h) { 

     } 
    } 
} 

ответ

2
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {   
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
    final Button record = new Button(this); //Activity goes here 
    record.setText("Record"); 
    record.setLayoutParams(lparams); 
    record.setOnClickListener(...); 
    parent.addView(record); 
} 
+0

Я получаю сообщение об ошибке синтаксиса «Метод addView (кнопка) не определена для типа VideoRecorder.Preview " –

+0

Попытайтесь добавить в onCreateView, потому что у поверхностиView нет метода addView. Если вы переопределите onCreateView, вы получите представление, которое вы установили в setContentView(). Я внес некоторые изменения в свой код. – kameny

0

Я расположены еще один пример в этом

случае R.id.btnRecord:

{
AudioLog.logString ("Начать запись «);

((Button) findViewById (R.id.btnStart)). SetVisibility (View.GONE);

((Button) findViewById (R.id.btnStop)). SetVisibility (View.VISIBLE);

enableButtons (true);

началоRecording();

break;

}

случай R.id.btnStop:

{

AudioLog.logString ("Остановить запись");

((Button) findViewById (R.id.btnStop)). SetVisibility (View.GONE);

   ((Button)findViewById(R.id.btnStart)).setVisibility(View.VISIBLE); 

       enableButtons(false); 

       stopRecording(); 

       break; 

}

и XML часть

<Button 

     android:id="@+id/btnStop" android:textStyle="bold" android:textColor="#ffffff" android:textSize="17sp" 
     android:text="Stop" android:background="@drawable/allotherbuttonstop" 
     android:layout_weight="1.0"/> 
Смежные вопросы