Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to custom an inherited Fragment class
    primarykey
    data
    text
    <p>I don't know how to custom my own Fragment which inherite another Fragment class.</p> <p>I'd like to add button and catch every click on them, but I don't how to do that.</p> <p>As you'll see, I'm using <a href="http://actionbarsherlock.com/" rel="nofollow">actionBarSherlock</a> and <a href="https://code.google.com/p/zxing/" rel="nofollow">Zxing</a> (a sub-library of Zxing actually: "<a href="http://code.google.com/p/barcodefraglibv2" rel="nofollow">barcodeFragLibV2</a>") and the <a href="http://developer.android.com/design/patterns/navigation-drawer.html" rel="nofollow">navigation drawer</a>.</p> <hr> <p>Here my code:</p> <p><em>MainActivity.java:</em></p> <pre><code>public class MainActivity extends SherlockFragmentActivity { private static final String TAG = MainActivity.class.getSimpleName(); /** * The navigation drawer layout. */ DrawerLayout mDrawerLayout; /** * The elements list of the menu. */ ListView mDrawerList; /** * The button to open/close the menu. */ ActionBarDrawerToggle mDrawerToggle; /** * The helper item of the local database. */ private DatabaseHelper dbHelper = null; /** * The current fragment title. */ String mTitle = ""; /** * @author LG * @category Property */ private boolean mShowOptionMenu; private int fragmentStatus = 0; private Menu mMenu = null; private MenuItem mGoItem; private static final int GO_ITEM_ID = 1; private static final int CLEAR_ITEM_ID = 2; public String getmTitle() { return mTitle; } public void setmTitle(String mTitle) { this.mTitle = mTitle; } /** * Method called when the activity is loaded. * * @param savedInstanceState * the bundle sent. */ @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "================= onCreate ================="); if (!isTablet()) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } setContentView(R.layout.activity_main); mTitle = (String) getTitle(); mShowOptionMenu = false; // result_view = findViewById(R.id.result_view); // result_view.setVisibility(View.GONE); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.drawer_list); mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) { /** Called when drawer is closed */ public void onDrawerClosed(View view) { getSupportActionBar().setTitle(mTitle); invalidateOptionsMenu(); } /** Called when a drawer is opened */ public void onDrawerOpened(View drawerView) { getSupportActionBar().setTitle("Menu"); invalidateOptionsMenu(); } }; mDrawerLayout.setDrawerListener(mDrawerToggle); MenuListAdapter adapter = new MenuListAdapter(getBaseContext()); mDrawerList.setAdapter(adapter); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mDrawerList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { view.setSelected(true); displayView(position); } private void displayView(int position) { String[] menu = getResources().getStringArray(R.array.menu); mTitle = menu[position]; MainActivity.this.fragmentStatus = position; SherlockFragment rFragment = null; Log.d(TAG, "================= mDrawerList.setOnItemClickListener ================="); if (position == 0) rFragment = new SearchFragment(); else if (position == 1) { mShowOptionMenu = true; rFragment = new AdvanceSearchFragment(); } else if (position == 2) { rFragment = new QrCodeScannerFragment(); // WORKS } else if (position == 3) rFragment = new FavorisFragment(); else if (position == 4) rFragment = new HistoriqueFragment(); else if (position == 5) rFragment = new InformationsFragment(); if (rFragment != null) { Bundle data = new Bundle(); data.putInt("position", position); rFragment.setArguments(data); FragmentManager fragmentManager = getSupportFragmentManager(); while (fragmentManager.getBackStackEntryCount() &gt; 0) fragmentManager.popBackStackImmediate(); FragmentTransaction ft = fragmentManager.beginTransaction(); // ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.replace(R.id.content_frame, rFragment); ft.addToBackStack(null); ft.commit(); mDrawerLayout.closeDrawer(mDrawerList); } } } ); SearchFragment rFragment = new SearchFragment(); Bundle data = new Bundle(); rFragment.setArguments(data); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction ft = fragmentManager.beginTransaction(); ft.replace(R.id.content_frame, rFragment); ft.commit(); } /** * Method called after the activity is loaded. * * @param savedInstanceState * the bundle sent. */ @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); Log.d(TAG, "================= onPostCreate ================="); mDrawerToggle.syncState(); } /** * Inflate the menu; this adds items to the action bar if it is present. * * @param menu * the menu */ @Override public boolean onCreateOptionsMenu(Menu menu) { Log.d(TAG, "================= onCreateOptionsMenu ================= fragSt: " + fragmentStatus); getSupportMenuInflater().inflate(R.menu.main, (Menu) menu); if (fragmentStatus == 1) { Log.i(TAG, "Show optionMenu"); mGoItem = menu.add(0, GO_ITEM_ID, 0, null); mGoItem.setIcon(R.drawable.abs__ic_go).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); mShowOptionMenu = false; } return true; } /** * Called whenever we call invalidateOptionsMenu() * * @param menu * the menu */ @Override public boolean onPrepareOptionsMenu(Menu menu) { // If the drawer is open, hide action items related to the content view Log.d(TAG, "================= onPrepareOptionsMenu ================= fragSt: " + fragmentStatus); return super.onPrepareOptionsMenu(menu); } /** * Method called when an menu's item is selected. * * @param item * the item selected */ @Override public boolean onOptionsItemSelected(MenuItem item) { Log.d(TAG, "================= onOptionsItemSelected ================= fragSt: " + fragmentStatus); switch (item.getItemId()) { case android.R.id.home: if (mDrawerLayout.isDrawerOpen(mDrawerList)) { mDrawerLayout.closeDrawer(mDrawerList); } else { mDrawerLayout.openDrawer(mDrawerList); } return true; } return false; } /** * Method to get device button actions * * @param keyCode * the code of the button pressed * @param event * the event */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { Log.d(TAG, "================= onKeyDown ================= fragSt: " + fragmentStatus); Log.w(TAG, "KeyEven: " + keyCode); if (keyCode == KeyEvent.KEYCODE_MENU ) { boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList); if (!drawerOpen) mDrawerLayout.openDrawer(Gravity.LEFT); else mDrawerLayout.closeDrawer(Gravity.LEFT); return true; } else if (keyCode == KeyEvent.KEYCODE_BACK) { Log.d(TAG, "TouchKeyBack"); } return super.onKeyDown(keyCode, event); } /** * Method called when the back button is pressed */ @Override public void onBackPressed() { FragmentManager fm = getSupportFragmentManager(); if (mShowOptionMenu == true) mShowOptionMenu = false; Log.d(TAG, "onBackPressed"); int tt = fm.getBackStackEntryCount(); // Log.d(TAG, "BackStackEntry name : " + // fm.getBackStackEntryAt(tt).getName()); if (fm.getBackStackEntryCount() &gt; 0) { Log.i("MainActivity", "popping backstack"); getSupportFragmentManager().popBackStack(); } else { Log.i("MainActivity", "nothing on backstack, calling super"); super.onBackPressed(); } } /** * Method to know if the device is tablet or smartphone * * @return a boolean indicating if the device is a tablet */ public boolean isTablet() { Log.d(TAG, "================= isTablet ================="); boolean xlarge = ((getResources().getConfiguration().screenLayout &amp; Configuration.SCREENLAYOUT_SIZE_MASK) == 4); boolean large = ((getResources().getConfiguration().screenLayout &amp; Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE); return (xlarge || large); } /** * Method called when the activity is deallocated */ protected void onDestroy() { super.onDestroy(); Log.d(TAG, "================= onDestroy ================="); if (dbHelper != null) { OpenHelperManager.releaseHelper(); dbHelper = null; } } /** * Return the database helper */ public DatabaseHelper getHelper() { if (dbHelper == null) { dbHelper = (DatabaseHelper) OpenHelperManager.getHelper(this, DatabaseHelper.class); } return dbHelper; } /** * Method called when the activity start. Used for Google Analytics */ @Override public void onStart() { super.onStart(); Log.d(TAG, "================= onStart ================="); EasyTracker.getInstance(this).activityStart(this); } /** * Method called when the activity stop. Used for Google Analytics */ @Override public void onStop() { Log.d(TAG, "================= onStop ================="); super.onStop(); EasyTracker.getInstance(this).activityStop(this); } } </code></pre> <hr> <p><em>QrCodeScannerFragment.java:</em></p> <pre><code>public class QrCodeScannerFragment extends BarcodeFragment { public static final String TAG = QrCodeScannerFragment.class.getSimpleName(); public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setScanResultHandler(new IScanResultHandler() { @Override public void scanResult(ScanResult result) { Log.w(TAG, "ScanResult"); } }); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub return super.onCreateView(inflater, container, savedInstanceState); } } </code></pre> <hr> <p><em>BarcodeFragment.java:</em></p> <pre><code>public class BarcodeFragment extends SherlockFragment implements SurfaceHolder.Callback { private static final String TAG = BarcodeFragment.class.getSimpleName(); private static final long BULK_MODE_SCAN_DELAY_MS = 1000L; private CameraManager cameraManager; private CaptureFragmentHandler handler; private Result savedResultToShow; private ViewfinderView viewfinderView; private boolean hasSurface; private Collection&lt;BarcodeFormat&gt; decodeFormats; private Map&lt;DecodeHintType, ?&gt; decodeHints; private String characterSet; private InactivityTimer inactivityTimer; private AmbientLightManager ambientLightManager; private IScanResultHandler resultHandler; public ViewfinderView getViewfinderView() { return viewfinderView; } public Handler getHandler() { return handler; } public CameraManager getCameraManager() { return cameraManager; } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); hasSurface = false; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { FrameLayout frameLayout = new FrameLayout(getActivity()); FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); frameLayout.setLayoutParams(layoutParams); surfaceView = new SurfaceView(getActivity()); surfaceView.setLayoutParams(layoutParams); viewfinderView = new ViewfinderView(getActivity()); viewfinderView.setLayoutParams(layoutParams); frameLayout.addView(surfaceView); frameLayout.addView(viewfinderView); View v = frameLayout; inactivityTimer = new InactivityTimer(this.getActivity()); ambientLightManager = new AmbientLightManager(this.getActivity()); return v; } SurfaceView surfaceView; @SuppressWarnings("deprecation") @Override public void onResume() { super.onResume(); // CameraManager must be initialized here, not in onCreate(). This is // necessary because we don't // want to open the camera driver and measure the screen size if we're // going to show the help on // first launch. That led to bugs where the scanning rectangle was the // wrong size and partially // off screen. cameraManager = new CameraManager(this.getActivity(), getView()); viewfinderView.setCameraManager(cameraManager); handler = null; resetStatusView(); SurfaceHolder surfaceHolder = surfaceView.getHolder(); if (hasSurface) { // The activity was paused but not stopped, so the surface still // exists. Therefore // surfaceCreated() won't be called, so init the camera here. initCamera(surfaceHolder); } else { // Install the callback and wait for surfaceCreated() to init the // camera. surfaceHolder.addCallback(this); surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } ambientLightManager.start(cameraManager); inactivityTimer.onResume(); decodeFormats = null; characterSet = null; } @Override public void onPause() { if (handler != null) { handler.quitSynchronously(); handler = null; } inactivityTimer.onPause(); ambientLightManager.stop(); cameraManager.closeDriver(); if (!hasSurface) { SurfaceView surfaceView = this.surfaceView; SurfaceHolder surfaceHolder = surfaceView.getHolder(); surfaceHolder.removeCallback(this); } super.onPause(); } @Override public void onDestroy() { inactivityTimer.shutdown(); super.onDestroy(); } public void restart() { restartPreviewAfterDelay(BULK_MODE_SCAN_DELAY_MS); } private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result) { // Bitmap isn't used yet -- will be used soon if (handler == null) { savedResultToShow = result; } else { if (result != null) { savedResultToShow = result; } if (savedResultToShow != null) { Message message = Message.obtain(handler, IDS.id.decode_succeeded, savedResultToShow); handler.sendMessage(message); } savedResultToShow = null; } } @Override public void surfaceCreated(SurfaceHolder holder) { if (holder == null) { Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!"); } if (!hasSurface) { hasSurface = true; initCamera(holder); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { hasSurface = false; } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } /** * A valid barcode has been found, so give an indication of success and show * the results. * * @param rawResult * The contents of the barcode. * @param scaleFactor * amount by which thumbnail was scaled * @param barcode * A greyscale bitmap of the camera data which was decoded. */ public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) { inactivityTimer.onActivity(); ScanResult resultHandler = ResultHandlerFactory.parseResult(rawResult); boolean fromLiveScan = barcode != null; if (fromLiveScan) { drawResultPoints(barcode, scaleFactor, rawResult); } handleDecodeInternally(rawResult, resultHandler, barcode); } /** * Superimpose a line for 1D or dots for 2D to highlight the key features of * the barcode. * * @param barcode * A bitmap of the captured image. * @param scaleFactor * amount by which thumbnail was scaled * @param rawResult * The decoded results which contains the points to draw. */ private void drawResultPoints(Bitmap barcode, float scaleFactor, Result rawResult) { ResultPoint[] points = rawResult.getResultPoints(); if (points != null &amp;&amp; points.length &gt; 0) { Canvas canvas = new Canvas(barcode); Paint paint = new Paint(); paint.setColor(Color.parseColor("#c099cc00")); if (points.length == 2) { paint.setStrokeWidth(4.0f); drawLine(canvas, paint, points[0], points[1], scaleFactor); } else if (points.length == 4 &amp;&amp; (rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A || rawResult.getBarcodeFormat() == BarcodeFormat.EAN_13)) { // Hacky special case -- draw two lines, for the barcode and // metadata drawLine(canvas, paint, points[0], points[1], scaleFactor); drawLine(canvas, paint, points[2], points[3], scaleFactor); } else { paint.setStrokeWidth(10.0f); for (ResultPoint point : points) { canvas.drawPoint(scaleFactor * point.getX(), scaleFactor * point.getY(), paint); } } } } private static void drawLine(Canvas canvas, Paint paint, ResultPoint a, ResultPoint b, float scaleFactor) { if (a != null &amp;&amp; b != null) { canvas.drawLine(scaleFactor * a.getX(), scaleFactor * a.getY(), scaleFactor * b.getX(), scaleFactor * b.getY(), paint); } } // Put up our own UI for how to handle the decoded contents. private void handleDecodeInternally(Result rawResult, ScanResult resultHandler, Bitmap barcode) { viewfinderView.setVisibility(View.GONE); if (this.resultHandler != null) { this.resultHandler.scanResult(resultHandler); } } private void initCamera(SurfaceHolder surfaceHolder) { if (surfaceHolder == null) { throw new IllegalStateException("No SurfaceHolder provided"); } if (cameraManager.isOpen()) { Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?"); return; } try { cameraManager.openDriver(surfaceHolder); // Creating the handler starts the preview, which can also throw a // RuntimeException. if (handler == null) { handler = new CaptureFragmentHandler(this, decodeFormats, decodeHints, characterSet, cameraManager); } decodeOrStoreSavedBitmap(null, null); } catch (IOException ioe) { Log.w(TAG, ioe); displayFrameworkBugMessageAndExit(); } catch (RuntimeException e) { // Barcode Scanner has seen crashes in the wild of this variety: // java.?lang.?RuntimeException: Fail to connect to camera service Log.w(TAG, "Unexpected error initializing camera", e); displayFrameworkBugMessageAndExit(); } } private void displayFrameworkBugMessageAndExit() { AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity()); builder.setTitle(getString(R.string.app_name)); builder.setMessage("Sorry, the Android camera encountered a problem. You may need to restart the device."); builder.setPositiveButton("OK", new FinishListener(this.getActivity())); builder.setOnCancelListener(new FinishListener(this.getActivity())); builder.show(); } public void restartPreviewAfterDelay(long delayMS) { if (handler != null) { handler.sendEmptyMessageDelayed(IDS.id.restart_preview, delayMS); } resetStatusView(); } private void resetStatusView() { viewfinderView.setVisibility(View.VISIBLE); } public void drawViewfinder() { viewfinderView.drawViewfinder(); } public IScanResultHandler getScanResultHandler() { return resultHandler; } public void setScanResultHandler(IScanResultHandler resultHandler) { this.resultHandler = resultHandler; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload