I have activity_main.xml with two Layouts:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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"
android:background="#color/appColor">
<android.support.constraint.ConstraintLayout
android:id="#+id/loading_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/appColor">
<ImageView
android:id="#+id/imageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="#mipmap/ic_launcher"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:contentDescription="" />
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
app:layout_constraintEnd_toEndOf="#+id/imageView"
app:layout_constraintStart_toStartOf="#+id/imageView"
app:layout_constraintTop_toBottomOf="#+id/imageView"
android:indeterminateTint="#color/white"
android:indeterminateTintMode="src_in"/>
</android.support.constraint.ConstraintLayout>
<android.support.constraint.ConstraintLayout
android:id="#+id/webview_layout"
android:visibility="gone"
android:background="#color/appColor"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/appColor"/>
</android.support.constraint.ConstraintLayout>
First I show the loading_layout and when I finish loading the app shows the webview_layout:
ConstraintLayout loadingLayout;
ConstraintLayout webviewLayout;
WebView webview;
String kAppUrl = "*******";
String kDefaultAppUrl = "******";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
loadingLayout = (ConstraintLayout)findViewById(R.id.loading_layout);
webviewLayout = (ConstraintLayout)findViewById(R.id.webview_layout);
webview = (WebView)findViewById(R.id.webView);
webview.clearCache(true);
webview.clearHistory();
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
startLoadingUrlFromServer();
}
private void startLoadingUrlFromServer() {
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, kAppUrl,
new Response.Listener<String>() {
#Override
public void onResponse(final String response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
finishLoadindDataFromServerWithData(response);
}
});
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
runOnUiThread(new Runnable() {
#Override
public void run() {
openWebSite(null);
}
});
}
});
queue.add(stringRequest);
}
private void finishLoadindDataFromServerWithData(String response) {
if (response == null || response.equals("")) {
openWebSite(null);
return;
}
if (!response.startsWith("http://") && !response.startsWith("https://")) {
openWebSite(null);
return;
}
openWebSite(response);
}
private void openWebSite(String url) {
loadingLayout.setVisibility(View.GONE);
webviewLayout.setVisibility(View.VISIBLE);
if (url == null || url.equals("")) {
webview.loadUrl(kDefaultAppUrl);
} else {
webview.loadUrl(url);
}
}
The problem that when I set the Visibility of loadingLayout to GONE and the webviewLayout to VISIBLE the app has a white background for two seconds, Any idea how I can change this background color?
It looks like the color you are finding for two seconds is the application theme background.
Go to your AndroidManifest.xml file and open the theme your Application tag is having (if another theme is defined in Activity tag, open that).
This should open your styles.xml file. Add new item for windowBackground to your AppTheme (Assuming this is your theme name), This will change the white background color to the defined one (in below code, its black).
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.NoActionBar">
<item name="android:windowBackground">#android:color/black</item>
...
..
.
</style>
</resources>
Related
I tried to create a profile preference like WhatsApp where the profile photo is shared with the profile activity. I used the following code which works properly in Android 8 and above. But in Android 7 and below, the shared element animation does not work. This is the result of a test on API 21.
Irrelevant codes have been removed.
SettingsActivity.java :
public class SettingsActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
setupToolbar();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.pref_content, new MainPreferenceFragment())
.commit();
}
private void setupToolbar() {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
try {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
} catch (NullPointerException e) {
e.printStackTrace();
}
}}
MainPreferenceFragment.java :
import android.transition.TransitionInflater;
import androidx.core.app.ActivityOptionsCompat;
import androidx.preference.ListPreference;
import androidx.transition.Explode;
import androidx.transition.Fade;
import androidx.transition.Transition;
public class MainPreferenceFragment extends PreferenceFragmentCompat {
public static final String KEY_PROFILE = "pref_profile_key";
private File myPhotoFile;
private int profileIconSize;
private Preference profile;
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
Context context = getContext();
initPreferences(context);
setListeners(context);
}
#Override
public void onResume() {
super.onResume();
profile.setTitle(MainBroadcastReceiver.getMyDeviceName());
if (myPhotoFile.exists()) {
profile.setIcon(
new BitmapDrawable(getResources(), ThumbnailUtils.extractThumbnail(
BitmapFactory.decodeFile(myPhotoFile.getPath()), profileIconSize, profileIconSize)));
} else {
profile.setIcon(R.drawable.avatar_contact);
}
}
private void initPreferences(Context context) {
profile = findPreference(KEY_PROFILE);
profile.setSummary(MainBroadcastReceiver.getMyDeviceMacAddress());
myPhotoFile = FileManager.myPhotoFile(context);
profileIconSize = ActivityManager.dp2px(context, 67F);
}
private void setListeners(Context context) {
profile.setOnPreferenceClickListener(preference -> {
AppCompatActivity activity = (AppCompatActivity) getActivity();
Intent intent = new Intent(activity, ProfileActivity.class);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
activity.getWindow().setExitTransition(TransitionInflater.from(activity).inflateTransition(R.transition.fade));
View profileView = getListView().getChildAt(profile.getOrder());
ImageView profileImageView = profileView.findViewById(android.R.id.icon);
ActivityOptionsCompat options = ActivityOptionsCompat
.makeSceneTransitionAnimation(activity
, profileImageView, profileImageView.getTransitionName());
startActivity(intent, options.toBundle());
} else {
startActivity(intent);
}
return true;
});
}}
preference_profile.xml :
<androidx.constraintlayout.widget.ConstraintLayout 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:id="#+id/chat_row_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true">
<LinearLayout
android:layout_width="0dp"
android:layout_height="1dp"
android:background="?attr/dividerColor"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#android:id/summary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="12dp"
android:layout_marginRight="12dp"
android:ellipsize="end"
android:gravity="start"
android:maxLines="1"
android:singleLine="true"
android:text="Okay, Bye."
android:textAlignment="gravity"
android:textColor="?android:attr/textColorSecondary"
android:textSize="14sp"
android:transitionName="macTransition"
app:layout_constrainedWidth="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="#android:id/title"
app:layout_constraintTop_toBottomOf="#android:id/title" />
<TextView
android:id="#android:id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"
android:ellipsize="end"
android:gravity="start"
android:maxLines="1"
android:singleLine="true"
android:text="Robert Downey"
android:textAlignment="gravity"
android:textColor="#android:color/black"
android:textSize="22sp"
android:transitionName="nameTransition"
app:layout_constrainedWidth="true"
app:layout_constraintBottom_toTopOf="#android:id/summary"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintHorizontal_chainStyle="spread_inside"
app:layout_constraintStart_toEndOf="#android:id/icon"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="packed" />
<de.hdodenhof.circleimageview.CircleImageView
android:id="#android:id/icon"
android:layout_width="67dp"
android:layout_height="67dp"
android:layout_marginStart="14dp"
android:layout_marginLeft="14dp"
android:layout_marginTop="17dp"
android:layout_marginBottom="17dp"
android:src="#drawable/avatar_contact"
android:transitionName="imageTransition"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
preferences.xml:
<androidx.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.preference.Preference
android:icon="#drawable/avatar_contact"
android:key="pref_profile_key"
android:layout="#layout/preference_profile"
android:summary="u:n:k:n:o:w:n"
android:title="#string/unknown" />
</androidx.preference.PreferenceScreen>
ProfileActivity.java :
import android.transition.Transition;
import android.transition.TransitionInflater;
public class ProfileActivity extends BaseActivity {
private SimpleDraweeView imageDrawee;
private ImageView setImageImageView;
private boolean isBackPressed = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
setupTransition();
}
private void setupTransition() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setAllowEnterTransitionOverlap(true);
Transition fade = TransitionInflater.from(this).inflateTransition(R.transition.fade);
fade.excludeTarget(R.id.setImage, true);
getWindow().setEnterTransition(fade);
getWindow().getSharedElementEnterTransition().addListener(new Transition.TransitionListener() {
#Override
public void onTransitionStart(Transition transition) {
}
#Override
public void onTransitionEnd(Transition transition) {
if (!isBackPressed) {
setImageImageView.setVisibility(View.VISIBLE);
ScaleAnimation scaleUp = new ScaleAnimation(0f, 1f, 0f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
scaleUp.setDuration(150);
scaleUp.setFillAfter(true);
setImageImageView.startAnimation(scaleUp);
}
}
#Override
public void onTransitionCancel(Transition transition) {
}
#Override
public void onTransitionPause(Transition transition) {
}
#Override
public void onTransitionResume(Transition transition) {
}
});
} else {
setImageImageView.setVisibility(View.VISIBLE);
ScaleAnimation scaleUp = new ScaleAnimation(0f, 1f, 0f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
scaleUp.setDuration(150);
scaleUp.setFillAfter(true);
setImageImageView.startAnimation(scaleUp);
}
}
#Override
public void onBackPressed() {
isBackPressed = true;
ScaleAnimation scaleUp = new ScaleAnimation(1f, 0f, 1f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
scaleUp.setDuration(150);
scaleUp.setFillAfter(true);
scaleUp.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
setImageImageView.setVisibility(View.INVISIBLE);
ProfileActivity.super.onBackPressed();
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
setImageImageView.startAnimation(scaleUp);
}}
activity_profile.xml :
<androidx.constraintlayout.widget.ConstraintLayout 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">
<com.facebook.drawee.view.SimpleDraweeView
android:id="#+id/image"
android:layout_width="160dp"
android:layout_height="160dp"
android:layout_marginTop="24dp"
android:transitionName="imageTransition"
app:actualImageScaleType="centerCrop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/appbar"
app:placeholderImage="#drawable/ic_settings_profile"
app:placeholderImageScaleType="centerCrop"
app:roundAsCircle="true" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/setImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="2dp"
android:layout_marginRight="2dp"
android:layout_marginBottom="2dp"
android:clickable="true"
android:focusable="true"
android:src="#drawable/ic_home_camera"
android:tint="#color/white"
android:visibility="invisible"
app:backgroundTint="#color/colorPrimaryLight"
app:fabCustomSize="48dp"
app:layout_constraintBottom_toBottomOf="#+id/image"
app:layout_constraintEnd_toEndOf="#+id/image"
app:rippleColor="#color/white" />
</androidx.constraintlayout.widget.ConstraintLayout>
syles.xml :
<resources>
<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar" />
<style name="AppTheme" parent="AppTheme.Base">
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
</resources>
styles.xml (v21) :
<resources>
<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowActivityTransitions">true</item>
<item name="android:windowEnterTransition">#transition/explode</item>
<item name="android:windowExitTransition">#transition/explode</item>
<item name="android:windowSharedElementEnterTransition">
#transition/change_image_transform
</item>
<item name="android:windowSharedElementExitTransition">
#transition/change_image_transform
</item>
</style>
</resources>
change_image_transition.xml :
<transitionSet>
<changeImageTransform />
<changeBounds />
</transitionSet>
explode.xml (v21) :
<explode xmlns:android="http://schemas.android.com/apk/res/android">
<targets>
<target android:excludeId="#android:id/statusBarBackground" />
<target android:excludeId="#android:id/navigationBarBackground" />
<target android:excludeId="#id/appbar" />
</targets>
</explode>
fade.xml (v21) :
<fade xmlns:android="http://schemas.android.com/apk/res/android">
<targets>
<target android:excludeId="#android:id/statusBarBackground" />
<target android:excludeId="#android:id/navigationBarBackground" />
<target android:excludeId="#id/appbar" />
</targets>
</fade>
APIs below 26 simple have different stuff so you might want to consider replacing your animation with another in api 26 and below ( and other stuff but maybe not in this application in general you can google and go to andoid official website to check that.
So simply your might not most of the devices which have api 26 and below.
Consider testing on physical devices as well to be sure.
go here and make sure to chose 26 in api drop menu top left.
https://developer.android.com/reference/android/view/animation/package-summary
good luck
I found the cause of this problem and the solution. The problem was not with the code I wrote in the question, but with the use of dynamic language in my BaseActivity. The dynamic language I implemented, in Android 7 and below recreated activity each time on the onResume method. And every time an activity was recreated, the transition animation did not work. To solve this problem, I disabled the dynamic language for my ProfileActivity.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.liliyu.easyresumebuilder, PID: 11145
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.liliyu.easyresumebuilder/com.example.liliyu.easyresumebuilder.MainActivity}: android.view.InflateException: Binary XML file line #10: RecyclerView has no LayoutManager android.support.v7.widget.RecyclerView{df7f7c9 VFED..... ......I. 0,0-0,0 #7f070061 app:id/main_activity1}, adapter:null, layout:null, context:com.example.liliyu.easyresumebuilder.MainActivity#2857d33
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2434)
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
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:id="#+id/main_activity1"
tools:context="com.example.liliyu.easyresumebuilder.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="#dimen/spacing_medium"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/user_name_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/spacing_small"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#+id/user_picture"
android:gravity="center_vertical">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/caption_text_size"
tools:text="Your name" />
</LinearLayout>
<TextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/user_name_layout"
android:layout_toLeftOf="#+id/user_picture"
tools:text="Your email" />
</RelativeLayout>
</LinearLayout>
</android.support.v7.widget.RecyclerView>
MainActivity.java
#SuppressWarnings("ConstantConditions")
public class MainActivity extends AppCompatActivity {
private BasicInfo basicInfo;
private RecyclerView recyclerView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadData();
setupUI();
}
private void setupUI() {
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.main_activity1);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
setupBasicInfo();
}
private void setupBasicInfo() {
((TextView) findViewById(R.id.name)).setText(TextUtils.isEmpty(basicInfo.name)
? "Your name"
: basicInfo.name);
((TextView) findViewById(R.id.email)).setText(TextUtils.isEmpty(basicInfo.email)
? "Your email"
: basicInfo.email);
ImageView userPicture = (ImageView) findViewById(R.id.user_picture);
if (basicInfo.imageUri != null) {
ImageUtils.loadImage(this, basicInfo.imageUri, userPicture);
} else {
userPicture.setImageResource(R.drawable.user_ghost);
}
findViewById(R.id.edit_basic_info).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, BasicInfoEditActivity.class);
intent.putExtra(BasicInfoEditActivity.KEY_BASIC_INFO, basicInfo);
startActivityForResult(intent, REQ_CODE_EDIT_BASIC_INFO);
}
});
}
private void loadData() {
connectAndGetApiData();
basicInfo = basicInfo == null ? new BasicInfo() : basicInfo;
}
public void connectAndGetApiData() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
ResumeService resumeService=retrofit.create(ResumeService.class);
Call<Resume> call =resumeService.getResume();
try {
call.enqueue(new Callback<Resume>() {
#Override
public void onResponse(Call<Resume> call, Response<Resume> response) {
recyclerView.setAdapter(new ResumeAdapter(getApplicationContext(),response.body()));
}
#Override
public void onFailure(Call<Resume> call, Throwable throwable) {
System.out.println(throwable.toString());
}
});
}catch(Throwable e){
e.printStackTrace();
}
}
}
Add a parentLayout (could be LinearLayout) to your RecyclerView and remove child from your RecyclerView.
You can't put children inside a RecyclerView in XML. It looks like what you have there currently is what you want to be in your ViewHolder. That's not how to do it.
Make a new layout XML file and move what's wrapped in your RecyclerView into that file.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_activity1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
//delete all elements
</android.support.v7.widget.RecyclerView
>
I am creating a qr code scanning app, which continuously scan the qr code and show the result on the same screen without closing the camera.
I am using ZXing library but when I trigger the continuous scanning activity it fails to open the camera. I can't figure out the issue. Please check, I already added camera permission in my manifest.
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.journeyapps.barcodescanner.DecoratedBarcodeView
android:id="#+id/barcode_scanner"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_above="#+id/buttonsLayout"
android:layout_alignParentTop="true">
</com.journeyapps.barcodescanner.DecoratedBarcodeView>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:id="#+id/buttonsLayout"
android:layout_toLeftOf="#+id/centerHorizont">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Pause"
android:onClick="pause" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Resume"
android:onClick="resume" />
</LinearLayout>
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:id="#+id/centerHorizont" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/centerHorizont"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignTop="#id/buttonsLayout"
android:id="#+id/barcodePreview" />
</RelativeLayout>
Java Code:
public class ContinuousCaptureActivity extends Activity {
private static final String TAG = ContinuousCaptureActivity.class.getSimpleName();
private DecoratedBarcodeView barcodeView;
private BeepManager beepManager;
private String lastText;
private BarcodeCallback callback = new BarcodeCallback() {
#Override
public void barcodeResult(BarcodeResult result) {
if(result.getText() == null || result.getText().equals(lastText)) {
// Prevent duplicate scans
return;
}
lastText = result.getText();
barcodeView.setStatusText(result.getText());
beepManager.playBeepSoundAndVibrate();
//Added preview of scanned barcode
ImageView imageView = (ImageView) findViewById(R.id.barcodePreview);
imageView.setImageBitmap(result.getBitmapWithResultPoints(Color.YELLOW));
}
#Override
public void possibleResultPoints(List<ResultPoint> resultPoints) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.continuous_scan);
barcodeView = (DecoratedBarcodeView) findViewById(R.id.barcode_scanner);
Collection<BarcodeFormat> formats = Arrays.asList(BarcodeFormat.QR_CODE, BarcodeFormat.CODE_39);
barcodeView.getBarcodeView().setDecoderFactory(new DefaultDecoderFactory(formats));
barcodeView.decodeContinuous(callback);
beepManager = new BeepManager(this);
}
#Override
protected void onResume() {
super.onResume();
barcodeView.resume();
}
#Override
protected void onPause() {
super.onPause();
barcodeView.pause();
}
public void pause(View view) {
barcodeView.pause();
}
public void resume(View view) {
barcodeView.resume();
}
public void triggerScan(View view) {
barcodeView.decodeSingle(callback);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return barcodeView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
}
Here is the error message, I am getting!
The problem occur because of the permission. I have added code to request permission manually, Now problem is solved.
Thanks to #Roberto Manfreda
I want to Set Image viewed in app as wallpaper.
While trying to do so image doesn't fit to screen of my device but its viewed properly using centerCrop.
This is my Code for the app.
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"
tools:context=".MainActivity">
<ImageView
android:id="#+id/imageView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:scaleType="centerCrop"
app:srcCompat="#drawable/image" />
<Button
android:id="#+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#color/transparent"
android:text="Set Wallpaper"
android:textColor="#ffffff" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setWallpaper();
}
});
}
private void setWallpaper(){
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
WallpaperManager manager = WallpaperManager.getInstance(getApplicationContext());
try {
manager.setBitmap(bitmap);
Toast.makeText(this, "Wallpaper Set", Toast.LENGTH_SHORT).show();
}
catch (IOException e){
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
}
}
}
This is image used in App
Live App Screen
After Setting Wallpaper in android Device
How can I set image as wallpaper perfectly as used in XML file (scale to centerCrop) for setting it as perfect fit wallpaper for any android devices?
Use:
android:background="#drawable/image"
instead of:
app:srcCompat="#drawable/image"
I have a PreferenceFragment containing some TextEditPreferences etc. and then I have this custom Preference that uses Volley NetworkImageView instead of the default ImageView and has a "Go to" icon at the end. Layout-wise otherwise it's copy-pasted from compat-v14 preference.xml file.
The problem is, I can't get any focus, selection or click events to fire when touching the Custom Preference item. I've tries everything I've come up: onClick(), onPreferenceTreeClick(), setOnPreferenceClickListener, setting layout xml android:selectable="true", android:enabled="true", android:descendantFocusability="blocksDescendants"...
xml/preferences.xml
<PreferenceCategory android:title="Icon">
<dev.niko.project.views.GravatarIconPreference android:key="auth.user.avatar"
android:title="Gravatar" android:summary="This has no focus animation, no click events are fired and certainly no Intent"
android:selectable="true" android:enabled="true"
android:layout="#layout/preference_gravatar"
android:defaultValue="">
<intent android:action="android.intent.action.VIEW" android:data="https://en.gravatar.com/connect/" />
</dev.niko.project.views.GravatarIconPreference>
<Preference
android:title="Gravatar" android:summary="This works fine">
<intent android:action="android.intent.action.VIEW" android:data="https://en.gravatar.com/connect/" />
</Preference>
</PreferenceCategory>
MyPreferencesFragment.java
public class AccountSettingsFragment extends PreferenceFragment
implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
preferences = context.getSharedPreferences(PREF_NAME_AUTH, Context.MODE_PRIVATE);
GravatarIconPreference gravatarIconPref = ((GravatarIconPreference)findPreference(AVATAR));
gravatarIconPref.setImageUrl(API.gravatar(preferences.getString(EMAIL, null)));
gravatarIconPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Log.wtf(TAG, "gravatarIconPref.onPreferenceClick()");
return false;
}
});
for (String key : preferences.getAll().keySet()) {
onSharedPreferenceChanged(preferences, key);
}
}
#Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
Log.wtf(TAG, "onPreferenceTreeClick(..., "+preference.getKey()+")");
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, final String key) {
final Preference preference = findPreference(key);
if (preference != null) {
Log.d(TAG, "onSharedPreferenceChanged. key="+key+" preference.getKey="+preference.getKey());
}
}
}
GravatarIconPreference.java
public class GravatarIconPreference extends Preference {
private static final String TAG = GravatarIconPreference.class.getSimpleName();
private Context context;
private View view;
private Drawable icon;
private String url;
public GravatarIconPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setSelectable(true);
setEnabled(true);
this.context = context;
}
// also tried overriding onCreateView, no change
#Override
protected void onBindView(View view) {
super.onBindView(view);
view.setClickable(true);
if (view != null && !TextUtils.isEmpty(url)) {
NetworkImageView gravatar = ((NetworkImageView) view.findViewById(R.id.gravatar));
if (gravatar != null) {
gravatar.setImageUrl(url, App.getInstance().getImageLoader());
}
}
}
#Override
protected void onClick() {
Log.wtf(TAG, "onClick()!!!");
super.onClick();
}
#Override
public Drawable getIcon() {
// TODO: gravatar-networkimageview
return super.getIcon();
}
public void setImageUrl(#Nullable String url) { this.url = url; }
}
preference_gravatar.xml source
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:gravity="center_vertical"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:background="?android:attr/activatedBackgroundIndicator"
android:clipToPadding="false"
android:focusable="true" android:descendantFocusability="blocksDescendants"
android:baselineAligned="false">
<LinearLayout android:id="#+id/icon_frame"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="-4dp"
android:minWidth="60dp"
android:gravity="start|center_vertical"
android:orientation="horizontal"
android:paddingEnd="12dp"
android:paddingTop="4dp"
android:paddingBottom="4dp" android:focusable="false">
<com.android.volley.toolbox.NetworkImageView android:id="#+id/gravatar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:maxWidth="48dp"
app:maxHeight="48dp"
android:layout_marginStart="#dimen/list_icon_margin"
android:layout_gravity="center" />
</LinearLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingTop="16dp"
android:paddingBottom="16dp">
<TextView android:id="#android:id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearanceListItem"
android:ellipsize="marquee"
android:layout_alignParentStart="true"
android:layout_toStartOf="#+id/chevron"/>
<TextView android:id="#android:id/summary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#android:id/title"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="?android:attr/textColorSecondary"
android:maxLines="10"
android:layout_alignParentStart="true"
android:layout_toStartOf="#+id/chevron"/>
<ImageView android:id="#+id/chevron"
android:src="#mipmap/ic_chevron_right_black_48dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentEnd="true"
android:alpha="0.5"
android:contentDescription="go to url" />
</RelativeLayout>
<!-- Preference should place its actual preference widget here. -->
<LinearLayout android:id="#android:id/widget_frame"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="end|center_vertical"
android:paddingStart="16dp"
android:orientation="vertical" />
</LinearLayout>
For custom preference, you need to set the click listener programmatically.
#Override
protected void onBindView(View view) {
super.onBindView(view);
view.setClickable(true);
if (view != null && !TextUtils.isEmpty(url)) {
NetworkImageView gravatar = ((NetworkImageView) view.findViewById(R.id.gravatar));
if (gravatar != null) {
gravatar.setImageUrl(url, App.getInstance().getImageLoader());
gravatar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("test","clicked");
}
}
}
}
}