Mobile vision how to resize? - java

I've been looking for information on Google for 2 days. But all
without results.
I want to use not the full screen mode, but the reduced one, so that
you can scan a certain area.
In Api Google, I also did not find what I needed.
The variant with resizing in SurfaceView is attached with a picture.
As you can see, the result is deplorable ((.
Is there a solution to my problem?
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:layout_centerInParent="true"
android:id="#+id/surface_view"
android:layout_width="match_parent"
android:layout_height="100dp"/>
<TextView
android:id="#+id/txtView"
android:text="No Text"
android:layout_alignParentBottom="true"
android:textColor="#android:color/white"
android:textSize="20sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
public class MainActivity extends AppCompatActivity {
#BindView(R.id.surface_view) SurfaceView cameraView;
#BindView(R.id.txtView) TextView txtView;
CameraSource cameraSource;
final int RequestCameraPermissionID = 1001;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case RequestCameraPermissionID:
if (grantResults[0]==PackageManager.PERMISSION_GRANTED){
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
cameraSource.start(cameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!textRecognizer.isOperational()) {
Log.e("MainActivity", "onCreate= " + "Detecter");
} else {
cameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer )
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedFps(2.0f)
.setAutoFocusEnabled(true)
.build();
cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA},
RequestCameraPermissionID);
return;
}
cameraSource.start(cameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
final SparseArray<TextBlock> items=detections.getDetectedItems();
if (items.size()!=0){
txtView.post(() -> {
StringBuilder stringBuilder=new StringBuilder();
for (int i = 0; i < items.size(); i++) {
TextBlock item=items.valueAt(i);
stringBuilder.append(item.getValue());
stringBuilder.append("\n");
}
txtView.setText(stringBuilder.toString());
});
}
}
});
}
}
}

Related

Text doen't appear after speech in adroid studio

Today i am posting my first question here in stackoverflow.
My app's subject is speech to text application all the app is working but the text doen't appear in its zone after saying the speech. So i am here asking you all for help.
Belong my xml file :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Tap Mic to Speak"
android:padding="20dp"
android:textColor="#000000"
android:textSize="20sp" />
<ImageButton
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/edittext"
android:layout_centerHorizontal="true"
android:padding="40dp"
android:background="#color/white"
android:src="#drawable/ic_baseline_mic_24" />
</RelativeLayout>
And my main code:
package com.example.translationapp;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPermission();
final EditText edittext = findViewById(R.id.edittext);
final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
Locale.getDefault());
mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
//getting all the matches
ArrayList<String> matches = bundle
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
//displaying the first match
if (matches != null) {
edittext.setText(matches.get(0));
}
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
findViewById(R.id.button).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
mSpeechRecognizer.stopListening();
edittext.setHint("You will see input here");
break;
case MotionEvent.ACTION_DOWN:
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
edittext.setText("");
edittext.setHint("Listening...");
break;
}
return false;
}
});
}
private void checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + getPackageName()));
startActivity(intent);
finish();
}
}
}
}
So please again and thank you all for your time.

Flashlight Fragment Android Studio

I have created a flashlight fragment for my app and I have implemented this code and turning the flashlight on works, but I can't turn it off.
I tried to switch the light on and off from one button or like now from two but it made no difference.
When I switch the fragment, the light turns off.
I hope anyone knows what to do.
Thx
public class Flashlight extends Fragment implements SurfaceHolder.Callback {
private View view;
Button button_On, button_Off;
private boolean lightIsOn = false;
Camera camera;
android.hardware.Camera.Parameters parameters;
#Override
public void onStart() {
super.onStart();
SurfaceView preview = (SurfaceView) getView().findViewById(R.id.PREVIEW);
SurfaceHolder mHolder = preview.getHolder();
mHolder.addCallback(this);
}
#Override
public void onPause() {
super.onPause();
turnOffLight();
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
final Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_flashlight, container, false);
button_On = (Button) view.findViewById(R.id.button_On);
button_Off = (Button) view.findViewById(R.id.button_Off);
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA,}, PackageManager.PERMISSION_GRANTED);
}
if (!getActivity().getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
Toast.makeText(getActivity(), "Device has no flashlight", Toast.LENGTH_SHORT).show();
}
button_On.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
turnOnLight();
}
});
button_Off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
turnOffLight();
}
});
return view;
}
Turn On/Off Light:
private void turnOnLight() {
if (!lightIsOn) {
if (camera == null || parameters == null) {
return;
}
parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
lightIsOn = true;
}
}
private void turnOffLight() {
if (lightIsOn) {
if (camera == null || parameters == null) {
return;
}
parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.stopPreview();
lightIsOn = false;
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (camera != null) {
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (camera == null) {
camera = Camera.open();
parameters = camera.getParameters();
try {
camera.setPreviewDisplay(holder);
} catch (IOException e) {
camera.release();
camera = null;
}
}
}
}
Manifest:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Flashlight">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:id="#+id/PREVIEW"
android:layout_width="1dp"
android:layout_height="1dp"
android:layout_marginBottom="730dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/button_On"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="on" />
<Button
android:id="#+id/button_Off"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="off" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</FrameLayout>
Okay update the permission in the manifest file as below:
<permission android:name="android.permission.FLASHLIGHT"
android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"
android:protectionLevel="normal"
android:label="#string/permlab_flashlight"
android:description="#string/permdesc_flashlight" />
Try to off the light using the below code:
cam.stopPreview();
cam.release(); // Very Important line
In which line?
private void turnOffLight() {
if (lightIsOn) {
if (camera == null || parameters == null) {
return;
}
camera = Camera.open();
parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.stopPreview();
camera.release(); // Very Important line
lightIsOn = false;
button_OnOff.setText("On");
}
}

Java android change color tab selected tab

I want to change a background color tab selected. I want change a color background my tab on green when is selected and changed a color background unselected tab to #a8a8a8
But when I swipe in logs I see this :
Process: pl.smok, PID: 28410
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.drawable.Drawable.setColorFilter(int, android.graphics.PorterDuff$Mode)' on a null object reference
at pl..smok.ui.activity.MainActivity$2.onTabUnselected(MainActivity.java:163)
at android.support.design.widget.TabLayout.dispatchTabUnselected(TabLayout.java:1163)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1149)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1124)
at android.support.design.widget.TabLayout$Tab.select(TabLayout.java:1419)
at android.support.design.widget.TabLayout$TabView.performClick(TabLayout.java:1524)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
This is full code :
public class MainActivity extends AppCompatActivity {
#BindView(R.id.view_pager)
ViewPager viewPager;
#BindView(R.id.tab_layout)
TabLayout tabLayout;
ActionBar actionBar;
SharedPreferences sp;
SharedPreferences.Editor editor;
int choose;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sp = getSharedPreferences("pfref", Activity.MODE_PRIVATE);
editor = sp.edit();
choose = sp.getInt("screen", 1);
// String token = FirebaseInstanceId.getInstance().getToken();
// Log.e( "Token: ", token);
if(choose == 1 )
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
else
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
actionBar = getSupportActionBar();
hideActionBar();
String[] tabs = {"start", "status", "wiadomości", "nowa wiadomość"};
viewPager.setOffscreenPageLimit(4);
viewPager.setAdapter(new PageAdapter(getFragmentManager(), tabs));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
CommonUtil.hideKeyboard(MainActivity.this);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(viewPager);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(getResources().getColor(R.color.colorBrown));
}
getFragmentManager()
.beginTransaction()
.add(R.id.top_bar_container, new TopBarFragment(), TopBarFragment.class.getName())
.commit();
processIntent(getIntent());
createTabIcons();
setupTabIcons();
}
#Override
protected void onResume() {
super.onResume();
choose = sp.getInt("screen", 1);
if(choose == 1 )
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
else
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
private void setupTabIcons() {
// tabLayout.getTabAt(1).getIcon().setColorFilter(Color.parseColor("#a8a8a8"), PorterDuff.Mode.SRC_IN);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
// tab.getIcon().mutate().setColorFilter(Color.GREEN, PorterDuff.Mode.SRC_IN);
Log.e("tab count " , tab.getPosition() + " " );
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
// tab.getIcon().setColorFilter(Color.parseColor("#a8a8a8"), PorterDuff.Mode.SRC_IN);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
protected void onStart() {
super.onStart();
App.getBus().register(this);
runServices();
}
#Override
protected void onStop() {
super.onStop();
App.getBus().unregister(this);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
processIntent(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
protected void processIntent(Intent intent) {
if (intent != null && intent.getIntExtra(Const.KEY_GOTO, 0) == 1 && viewPager != null) {
viewPager.setCurrentItem(2);
}
}
#Subscribe
public void onPermissionRequestedEvent(PermissionRequestedEvent event) {
PermissionUtil.getPermission(this, event.getPermission());
}
#Subscribe
public void onPermissionGrantedEvent(PermissionGrantedEvent event) {
if (event.getPermission().equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
runLocationService();
}
}
#Subscribe
public void onPageNavigateEvent(PageNavigateEvent event) {
Intent intent;
switch (event.getPage()) {
case Const.APP_SETTINGS_LOCATION:
CommonUtil.hideKeyboard(this);
intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
break;
case Const.PAGE_START:
viewPager.setCurrentItem(0);
break;
case Const.PAGE_STATUSES:
viewPager.setCurrentItem(1);
break;
case Const.PAGE_MESSAGES:
viewPager.setCurrentItem(2);
break;
case Const.PAGE_SEND_MESSAGE:
viewPager.setCurrentItem(3);
break;
default: break;
}
}
#Subscribe(sticky = true)
public void onLoggedOutEvent(LoggedOutEvent event) {
String user = Hawk.get(HawkConst.LOGIN_USER);
String company = Hawk.get(HawkConst.LOGIN_COMPANY);
String password = Hawk.get(HawkConst.LOGIN_PASSWORD);
Hawk.clear();
Hawk.put(HawkConst.LOGIN_USER, user);
Hawk.put(HawkConst.LOGIN_COMPANY, company);
Hawk.put(HawkConst.LOGIN_PASSWORD, password);
stopLocationService();
stopTrackerService();
stopConfigService();
FileUtil.clearDirs();
Intent intent = new Intent(MainActivity.this, StartActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
App.getBus().removeStickyEvent(LoggedOutEvent.class);
}
#Subscribe
public void onPhotoRequestedEvent(PhotoRequestedEvent event) {
Intent intent;
switch (event.getRequestCode()) {
case Const.PHOTO_GALLERY:
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.choose_image_title)), event.getRequestCode());
break;
case Const.PHOTO_CAMERA:
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, FileUtil.getOutputTempUri("images"));
startActivityForResult(intent, event.getRequestCode());
break;
default: break;
}
}
#Subscribe
public void onFileViewRequestEvent(FileViewRequestEvent event) {
File file = FileUtil.getFile(event.getEvent().getId());
if (file == null) {
Toast.makeText(this, getResources().getString(R.string.file_not_exists), Toast.LENGTH_LONG).show();
} else {
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try {
String type = FileUtil.getMimeType(file.getPath());
intent.setDataAndType(uri, type);
startActivity(intent);
App.getBus().post(new FileViewedEvent(event.getEvent()));
} catch (Exception e) {
e.printStackTrace();
try {
intent.setDataAndType(uri, "*/*");
startActivity(intent);
App.getBus().post(new FileViewedEvent(event.getEvent()));
} catch (Exception ee) {
ee.printStackTrace();
Toast.makeText(this, getResources().getString(R.string.no_file_app), Toast.LENGTH_LONG).show();
}
}
}
}
#Subscribe
public void onHideKeyboardEvent() {
CommonUtil.hideKeyboard(this);
}
#Subscribe
public void onMoveAppBackgroundEvent(MoveAppBackgroundEvent event) {
moveTaskToBack(true);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case Const.PHOTO_GALLERY:
App.getBus().postSticky(new PhotoSelectedEvent(data.getData())); break;
case Const.PHOTO_CAMERA:
Uri uri = FileUtil.renameFile(App.getConfigRepository().getPhotoMaxWidth());
App.getBus().postSticky(new PhotoSelectedEvent(uri)); break;
default: break;
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case Const.PERMISSIONS_REQUEST_LOCATION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
App.getBus().post(new PermissionGrantedEvent(Manifest.permission.ACCESS_FINE_LOCATION));
}
break;
default:
break;
}
}
protected void runServices() {
if (LocationUtil.isLocationEnabled(getBaseContext())) {
if (checkPermission()) {
runLocationService();
}
} else {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage(getResources().getString(R.string.location_settings_disabled));
dialog.setPositiveButton(getString(R.string.go_to_location_settings), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
App.getBus().post(new PageNavigateEvent(Const.APP_SETTINGS_LOCATION));
}
});
dialog.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
finish();
}
});
dialog.show();
}
runTrackerService();
runConfigService();
}
protected void runLocationService() {
startService(new Intent(this, LocationService.class));
}
protected void stopLocationService() {
stopService(new Intent(this, LocationService.class));
}
protected void runTrackerService() {
startService(new Intent(this, TrackerService.class));
}
protected void stopTrackerService() {
stopService(new Intent(this, TrackerService.class));
}
protected void runConfigService() {
startService(new Intent(this, ConfigService.class));
}
protected void stopConfigService() {
stopService(new Intent(this, ConfigService.class));
}
protected boolean checkPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
App.getBus().post(new PermissionRequestedEvent(Manifest.permission.ACCESS_FINE_LOCATION));
return false;
}
return true;
}
protected void hideActionBar() {
if (actionBar != null) {
actionBar.hide();
}
}
private void createTabIcons(){
}
}
And this is xml code for this activity . activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
tools:context="pl.eltegps.smokkomunikator.ui.activity.MainActivity">
<FrameLayout
android:id="#+id/top_bar_container"
android:layout_width="match_parent"
android:layout_height="70dp" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/top_bar_container">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="?attr/actionBarSize">
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_vertical_margin"
android:paddingRight="#dimen/activity_vertical_margin"
android:paddingTop="#dimen/activity_vertical_margin" />
</LinearLayout>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="center_horizontal"
android:minHeight="?attr/actionBarSize"
android:paddingTop="#dimen/activity_vertical_margin"
app:tabGravity="center"
app:tabIndicatorColor="#fff"
app:tabMode="scrollable"
app:tabTextAppearance="#style/MyCustomTextAppearance" />
</RelativeLayout>
</RelativeLayout>
Hello you can set this color in xml only no need to write in code
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="35dp"
app:tabSelectedTextColor="#color/colorSplashBackground"
app:tabTextAppearance="#android:style/TextAppearance.Widget.TabWidget"
app:tabTextColor="#color/colorBottomLine">
</android.support.design.widget.TabLayout>
this will be the xml of tab layout and you have to pass your color in line
app:tabSelectedTextColor="#color/colorSplashBackground"

SurfaceView doesn't display camera

I am trying to display a camera on in my android app, but all I am getting is a black box where the SurfaceView is located.
I am using this simple XML layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.lazylayer.photoshoot.MainActivity">
<SurfaceView
android:id="#+id/surface_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
With this Activity:
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback {
SurfaceView surfaceView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = (SurfaceView)findViewById(R.id.surface_view);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try{
CameraManager cameraManager = (CameraManager)getSystemService(Context.CAMERA_SERVICE);
String[] cameras = cameraManager.getCameraIdList();
cameraManager.openCamera(cameras[0], deviceCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {}
CameraDevice.StateCallback deviceCallback = new CameraDevice.StateCallback() {
#Override
public void onOpened(CameraDevice camera) {
try {
List<Surface> surfaceList = Collections.singletonList(surfaceView.getHolder().getSurface());
camera.createCaptureSession(surfaceList, sessionCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#Override
public void onDisconnected(CameraDevice camera) {}
#Override
public void onError(CameraDevice camera, int error) {}
};
CameraCaptureSession.StateCallback sessionCallback = new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(CameraCaptureSession session) {
}
#Override
public void onConfigureFailed(CameraCaptureSession session) {}
};
}
Here is what gets displayed when the app is ran on my phone:
I was able to fix the issue by using a FrameLayout instead of a SurfaceView
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/camera_view">
</FrameLayout>

Admob view is not visible until onResume

AdMob view is not visible, but clickable. If call onResume() view become visible. When I use
AdMob library all work fine, but if use google play services for AdMob I got this issue.
My code is bellow.
protected void initAdMob(){
if (mAdView == null) {
mAdView = new AdView(MainActivity.this);
mAdView.setAdUnitId(getString(R.string.admob_id));
mAdView.setAdSize(AdSize.SMART_BANNER);
mAdView.loadAd(new AdRequest.Builder().build());
mAdView.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
super.onAdClosed();
}
#Override
public void onAdFailedToLoad(int errorCode) {
super.onAdFailedToLoad(errorCode);
}
#Override
public void onAdLeftApplication() {
super.onAdLeftApplication();
}
#Override
public void onAdOpened() {
super.onAdOpened();
}
#Override
public void onAdLoaded() {
super.onAdLoaded();
}
});
}
}
private void showAdMob() {
initAdMob();
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER_HORIZONTAL;
mAdView.setLayoutParams(params);
FrameLayout fl = (FrameLayout) mainView.findViewById(R.id.adView);
if (fl != null) {
fl.removeAllViews();
fl.addView(mAdView, params);
}
}
#Override
public void onResume() {
if(mAdView != null){
mAdView.resume();
}
super.onResume();
}
view xml:
<FrameLayout
android:id="#+id/gameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<FrameLayout
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
Need to use Mediation ID instead Publisher ID in AdMob

Categories