How can I call setStatusBarColor on a buttonclick? I have the event listener code but I'm unsure how to call this method. I'm trying to change the status bar color on button click.
Here's my code:
public static void setStatusBarColor(Activity activity, int statusBarColor) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// If both system bars are black, we can remove these from our layout,
// removing or shrinking the SurfaceFlinger overlay required for our views.
Window window = activity.getWindow();
if (statusBarColor == Color.BLACK && window.getNavigationBarColor() == Color.BLACK) {
window.clearFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
} else {
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
}
window.setStatusBarColor(Color.parseColor("#4CAF50"));
}
}
Here is my button listener
public void addButtonListener() {
Button = (Button) findViewById(R.id.Button);
Button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
setStatusBarColor();
}
});
}
Change your method call to this
In Activity
public void onClick(View view) {
setStatusBarColor(this, Color.parseColor("#4CAF50"));
}
In Fragment:
public void onClick(View view) {
setStatusBarColor(getActivity() , Color.parseColor("#4CAF50"));
}
Or remove the parameter from method
public void onClick(View view) {
setStatusBarColor();
}
public static void setStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// If both system bars are black, we can remove these from our layout,
// removing or shrinking the SurfaceFlinger overlay required for our views.
//change here
Window window = activity.getWindow();
// By -->>>>> Window window = getWindow();
//or by this if call in Fragment
// -->>>>> Window window = getActivity().getWindow();
int statusBarColor = Color.parseColor("#4CAF50");
if (statusBarColor == Color.BLACK && window.getNavigationBarColor() == Color.BLACK) {
window.clearFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
} else {
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
}
window.setStatusBarColor(statusBarColor);
}
}
Related
I have set up a button that is meant to check for READ_EXTERNAL_STORAGE permissions, and then open the users phone storage display images. I've done this successfully via the following code:
All of this works perfectly on the first try. The user sees the permission dialog box, presses agree and the image selector opens displaying images on their phone! However, the second time we try to use the same button the app crashes. So basically after the permissions are granted the app crashes every time the button is pressed.
The following error is displayed:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.memory.pod.debug, PID: 26684
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference
at android.content.ContextWrapper.getPackageManager(ContextWrapper.java:98)
at com.memory.pod.camerax.ui.home.HomeActivity.selectImage(HomeActivity.java:144)
at com.memory.pod.camerax.ui.home.HomeActivity.openFileChooser(HomeActivity.java:137)
at com.memory.pod.view.BottomTabView$4.onClick(BottomTabView.java:84)
at android.view.View.performClick(View.java:7259)
at android.view.View.performClickInternal(View.java:7236)
at android.view.View.access$3600(View.java:801)
at android.view.View$PerformClick.run(View.java:27892)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
BottomTabView.java
public class BottomTabView extends FrameLayout implements ViewPager.OnPageChangeListener {
// Initialize content
private ImageView mCenterImageView;
private ImageView mBottomImageView;
private LinearLayout mStartImageView;
private LinearLayout mEndImageView;
private View mIndicator;
private ArgbEvaluator mArgbEvaluator;
private int mCenterColor;
private int mSideColor;
private int mEndViewsTranslationX;
private int mIndicatorTranslationX;
private int mCenterTranslationY;
public BottomTabView(#NonNull Context context) {
this(context, null);
}
public BottomTabView(#NonNull Context context, #Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public BottomTabView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public void setUpWithViewPager(ViewPager viewPager) {
viewPager.addOnPageChangeListener(this);
mStartImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (viewPager.getCurrentItem() != 0)
viewPager.setCurrentItem(0);
}
});
mCenterImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (viewPager.getCurrentItem() != 1)
viewPager.setCurrentItem(1);
}
});
mEndImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (viewPager.getCurrentItem() != 2)
viewPager.setCurrentItem(2);
}
});
mBottomImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (viewPager.getCurrentItem() == 1) {
HomeActivity.openFileChooser(getContext());
}
}
});
}
private void init() {
LayoutInflater.from(getContext()).inflate(R.layout.view_bottom_tabs, this, true);
// Initialize bottom tab view content
mCenterImageView = findViewById(R.id.view_bottom_tabs_camera_iv);
mStartImageView = findViewById(R.id.view_bottom_tabs_start_linear_layout);
mEndImageView = findViewById(R.id.view_bottom_tabs_end_linear_layout);
mBottomImageView = findViewById(R.id.view_bottom_tabs_gallery_iv);
// Initialize bottom tab view indicator, meant to indicate the current tab in view
mIndicator = findViewById(R.id.view_bottom_tabs_indicator);
// Set start color and end color for tab view icons
mCenterColor = ContextCompat.getColor(getContext(), R.color.white);
mSideColor = ContextCompat.getColor(getContext(), R.color.black);
// Evaluate the difference between colors
mArgbEvaluator = new ArgbEvaluator();
// Change the padding of tab icons based on view
// This is the min padding accepted (0)
mIndicatorTranslationX = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 140, getResources().getDisplayMetrics());
// Wait till GalleryImageView has been drawn, once GalleryImageView is drawn then proceed with relative padding calculation
mBottomImageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
// Change padding relative to other icons
mEndViewsTranslationX = (int)((mBottomImageView.getX() - mStartImageView.getX()) - mIndicatorTranslationX);
mBottomImageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// Change the position of the center image
mCenterTranslationY = getHeight() - mBottomImageView.getBottom();
}
});
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (position == 0) {
// Change color of icons based on view
setColor(1 - positionOffset);
// Move the start and end images
moveViews(1 - positionOffset);
// Change indicator position
mIndicator.setTranslationX((positionOffset - 1) * mIndicatorTranslationX);
// Change scale of center image
moveAndScaleCenter(1 - positionOffset);
} else if (position == 1) {
// Change color of icons based on view
setColor(positionOffset);
// Move the start and end images
moveViews(positionOffset);
// Change indicator position
mIndicator.setTranslationX(positionOffset * mIndicatorTranslationX);
// Change scale of center image
moveAndScaleCenter(positionOffset);
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
private void moveAndScaleCenter(float fractionFromCenter) {
float scale = .7 f + ((1 - fractionFromCenter) * .3 f);
// Change scale of center image
mCenterImageView.setScaleX(scale);
mCenterImageView.setScaleY(scale);
int translation = (int)(fractionFromCenter * mCenterTranslationY * 2);
// Move center image down
mCenterImageView.setTranslationY(translation);
mBottomImageView.setTranslationY(translation);
// Fadeout bottom image
mBottomImageView.setAlpha(1 - fractionFromCenter);
}
private void moveViews(float fractionFromCenter) {
mStartImageView.setTranslationX(fractionFromCenter * mEndViewsTranslationX);
mEndImageView.setTranslationX(-fractionFromCenter * mEndViewsTranslationX);
mIndicator.setAlpha(fractionFromCenter);
mIndicator.setScaleX(fractionFromCenter);
}
private void setColor(float fractionFromCenter) {
int color = (int) mArgbEvaluator.evaluate(fractionFromCenter, mCenterColor, mSideColor);
/* mCenterImageView.setColorFilter(color);
mStartImageView.setColorFilter(color);
mEndImageView.setColorFilter(color);
mBottomImageView.setColorFilter(color); */
}
}
I did a log.d to identify where it fails, please refer to previous code to see log.d.
How can I overcome this issue?
EDIT:
HomeActivity:
public class HomeActivity extends AppCompatActivity {
// Initialize image picker
private static final int PICK_IMAGE_REQUEST = 1;
private static final int REQUEST_CODE_STORAGE_PERMISSION = 1;
private static final int REQUEST_CODE_SELECT_IMAGE = 2;
// TODO: FIREBASE TEMPORARY LOGOUT
private static FirebaseAuth mAuth;
private static final String TAG = "HomeActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Initialize views
View background = findViewById(R.id.background_view);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
// Initialize adapter
HomePagerAdapter adapter = new HomePagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
// Initialize BottomTabView
BottomTabView bottomTabView = findViewById(R.id.bottom_tabs);
bottomTabView.setUpWithViewPager(viewPager);
// Initialize TopSearchView
TopSearchView topSearchView = findViewById(R.id.top_search);
topSearchView.setUpWithViewPager(viewPager);
// Initialize TopProfilePictureView
TopProfilePictureView topProfilePictureView = findViewById(R.id.top_profile_picture);
topProfilePictureView.setUpWithViewPager(viewPager);
// Initialize TopVariableFunctionalityButtonView
TopVariableFunctionalityButtonView topVariableFunctionalityButtonView = findViewById(R.id.top_variable_functionality_button);
topVariableFunctionalityButtonView.setUpWithViewPager(viewPager);
// Initialize color for fade effect
final int windowBackgroundColor = ContextCompat.getColor(this, R.color.windowBackground);
final int blackBackgroundColor = ContextCompat.getColor(this, R.color.black);
// Set the default position of the viewPager
viewPager.setCurrentItem(1);
// TODO: Initialize Firebase (TEMPORARY)
//Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
bottomTabView.setOnBottomTabViewClickListener(new BottomTabViewClickListener() {
#Override
public void onClick(View v) {
// call your openFileChooser from here,
//REMOVE THE STATIC
openFileChooser(HomeActivity.this);
}
});
// Callback each time the fragment is changed
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (position == 0) {
background.setBackgroundColor(windowBackgroundColor);
background.setAlpha(1 - positionOffset);
} else if (position == 1) {
background.setBackgroundColor(blackBackgroundColor);
background.setAlpha(positionOffset);
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
// Choose file extended from BottomTabView, opens all images on device
// Check for permissions before hand
public void openFileChooser(Context context) {
Log.d("HomeActivity", "This is the last place a log is observed");
if (ContextCompat.checkSelfPermission(getInstance().getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
((Activity) context),
new String[] {
Manifest.permission.READ_EXTERNAL_STORAGE
},
REQUEST_CODE_STORAGE_PERMISSION
);
} else {
selectImage();
}
}
// Open image selector via phone storage
private void selectImage() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_CODE_SELECT_IMAGE);
}
}
// Request permission results
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE_STORAGE_PERMISSION && grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
selectImage();
} else {
Toast.makeText(this, "Permission Denied!", Toast.LENGTH_SHORT).show();
}
}
}
// TODO: Is it better to use bitmap or URI
// Check if user has selected file and describe next step
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_SELECT_IMAGE && resultCode == RESULT_OK) {
if (data != null) {
// Get image URI
Uri selectedImageUri = data.getData();
if (selectedImageUri != null) {
try {
InputStream inputStream = getContentResolver().openInputStream(selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// Do something with image
// Identify the selected image file, pass onto firebase
File selectedImageFile = new File(getPathFormUri(selectedImageUri));
} catch (Exception exception) {
Toast.makeText(this, exception.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
}
}
private String getPathFormUri(Uri contentUri) {
String filePath;
Cursor cursor = getContentResolver()
.query(contentUri, null, null, null, null);
if (cursor == null) {
filePath = contentUri.getPath();
} else {
cursor.moveToFirst();
int index = cursor.getColumnIndex("_data");
filePath = cursor.getString(index);
cursor.close();
}
return filePath;
}
// TODO: TEMPORARY LOGOUT
public static void logoutUser(Context context) {
mAuth.signOut();
}
}
BottomTabActivity:
public class BottomTabView extends FrameLayout implements ViewPager.OnPageChangeListener {
// Initialize content
BottomTabViewClickListener bottomTabViewClickListener;
private ImageView mCenterImageView;
private ImageView mBottomImageView;
private LinearLayout mStartImageView;
private LinearLayout mEndImageView;
private View mIndicator;
private ArgbEvaluator mArgbEvaluator;
private int mCenterColor;
private int mSideColor;
private int mEndViewsTranslationX;
private int mIndicatorTranslationX;
private int mCenterTranslationY;
//add this function somewhere
public void setOnBottomTabViewClickListener(BottomTabViewClickListener bottomTabViewClickListener) {
this.bottomTabViewClickListener = bottomTabViewClickListener;
}
public BottomTabView(#NonNull Context context) {
this(context, null);
}
public BottomTabView(#NonNull Context context, #Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public BottomTabView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public void setUpWithViewPager(ViewPager viewPager) {
viewPager.addOnPageChangeListener(this);
mStartImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (viewPager.getCurrentItem() != 0)
viewPager.setCurrentItem(0);
}
});
mCenterImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (viewPager.getCurrentItem() != 1)
viewPager.setCurrentItem(1);
}
});
mEndImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (viewPager.getCurrentItem() != 2)
viewPager.setCurrentItem(2);
}
});
mBottomImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (viewPager.getCurrentItem() == 1) {
}
}
});
}
private void init() {
LayoutInflater.from(getContext()).inflate(R.layout.view_bottom_tabs, this, true);
// Initialize bottom tab view content
mCenterImageView = findViewById(R.id.view_bottom_tabs_camera_iv);
mStartImageView = findViewById(R.id.view_bottom_tabs_start_linear_layout);
mEndImageView = findViewById(R.id.view_bottom_tabs_end_linear_layout);
mBottomImageView = findViewById(R.id.view_bottom_tabs_gallery_iv);
// Initialize bottom tab view indicator, meant to indicate the current tab in view
mIndicator = findViewById(R.id.view_bottom_tabs_indicator);
// Set start color and end color for tab view icons
mCenterColor = ContextCompat.getColor(getContext(), R.color.white);
mSideColor = ContextCompat.getColor(getContext(), R.color.black);
// Evaluate the difference between colors
mArgbEvaluator = new ArgbEvaluator();
// Change the padding of tab icons based on view
// This is the min padding accepted (0)
mIndicatorTranslationX = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 140, getResources().getDisplayMetrics());
// Wait till GalleryImageView has been drawn, once GalleryImageView is drawn then proceed with relative padding calculation
mBottomImageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
// Change padding relative to other icons
mEndViewsTranslationX = (int)((mBottomImageView.getX() - mStartImageView.getX()) - mIndicatorTranslationX);
mBottomImageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// Change the position of the center image
mCenterTranslationY = getHeight() - mBottomImageView.getBottom();
}
});
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (position == 0) {
// Change color of icons based on view
setColor(1 - positionOffset);
// Move the start and end images
moveViews(1 - positionOffset);
// Change indicator position
mIndicator.setTranslationX((positionOffset - 1) * mIndicatorTranslationX);
// Change scale of center image
moveAndScaleCenter(1 - positionOffset);
} else if (position == 1) {
// Change color of icons based on view
setColor(positionOffset);
// Move the start and end images
moveViews(positionOffset);
// Change indicator position
mIndicator.setTranslationX(positionOffset * mIndicatorTranslationX);
// Change scale of center image
moveAndScaleCenter(positionOffset);
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
private void moveAndScaleCenter(float fractionFromCenter) {
float scale = .7 f + ((1 - fractionFromCenter) * .3 f);
// Change scale of center image
mCenterImageView.setScaleX(scale);
mCenterImageView.setScaleY(scale);
int translation = (int)(fractionFromCenter * mCenterTranslationY * 2);
// Move center image down
mCenterImageView.setTranslationY(translation);
mBottomImageView.setTranslationY(translation);
// Fadeout bottom image
mBottomImageView.setAlpha(1 - fractionFromCenter);
}
private void moveViews(float fractionFromCenter) {
mStartImageView.setTranslationX(fractionFromCenter * mEndViewsTranslationX);
mEndImageView.setTranslationX(-fractionFromCenter * mEndViewsTranslationX);
mIndicator.setAlpha(fractionFromCenter);
mIndicator.setScaleX(fractionFromCenter);
}
private void setColor(float fractionFromCenter) {
int color = (int) mArgbEvaluator.evaluate(fractionFromCenter, mCenterColor, mSideColor);
/* mCenterImageView.setColorFilter(color);
mStartImageView.setColorFilter(color);
mEndImageView.setColorFilter(color);
mBottomImageView.setColorFilter(color); */
}
}
interface BottomTabViewClickListener {
public void onClick();
}
Your else statement is currently like this, which means you are trying to create a new instance of HomeActivity and call selectimage(), and it does not work that way.
else {
new HomeActivity().selectImage();
}
Please, change it to
else{
selectImage();
}
Please, try this, this should solve your problem.
EDIT: Use of interface and listener pattern
In your BottomTabView add the following
public class BottomTabView extends FrameLayout implements ViewPager.OnPageChangeListener {
// Initialize content
// add this at top level.
BottomTabViewClickListener bottomTabViewClickListener;
//add this function somewhere
public void setOnBottomTabViewClickListener(BottomTabViewClickListener bottomTabViewClickListener){
this.bottomTabViewClickListener = bottomTabViewClickListener;
}
// replace HomeActivity.openFileChooser(getContext());
mBottomImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (viewPager.getCurrentItem() == 1) {
bottomTabViewClickListener.onClick();
}
}
});
}
//end of BottomTab View
//add this after your BottomTabView not inside
interface BottomTabViewClickListener{
public void onClick();
}
Add the following in your HomeActivity
// Initialize BottomTabView
BottomTabView bottomTabView = findViewById(R.id.bottom_tabs);
bottomTabView.setUpWithViewPager(viewPager);
bottomTabView.setOnBottomTabViewClickListener(new BottomTabViewClickListener() {
#Override
public void onClick() {
// call your openFileChooser from here,
//REMOVE THE STATIC
openFileChooser(HomeActivity.this)
}
});
How do I enable the "Next" button after 'Yes' or 'No' from each question is pressed? I want to make my "Next" button active (change the background and enable) only after all the questions have been answered. I don't know whether I should use loop or if it's possible by if-else. Any help is very appreciated.
I have developed my program in a way that users can either press the 'yes' or 'no' button and after answering all questions the "Next" button should get activated (change the background and enable).
int one = 0;
int two = 0;
int three = 0;
int four = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_price_estimate_question_one);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String phone_price = extras.getString("phone_price");
final String numonly = phone_price.replaceAll("[^0-9]", "");
final int phoneprice = Integer.parseInt(numonly);
final Button ques_one_yes = (Button)findViewById(R.id.ques_one_yes);
final Button ques_one_no = (Button)findViewById(R.id.ques_one_no);
final Button ques_two_yes = (Button)findViewById(R.id.ques_two_yes);
final Button ques_two_no = (Button)findViewById(R.id.ques_two_no);
final Button ques_three_yes = (Button)findViewById(R.id.ques_three_yes);
final Button ques_three_no = (Button)findViewById(R.id.ques_three_no);
final Button ques_four_yes = (Button)findViewById(R.id.ques_four_yes);
final Button ques_four_no = (Button)findViewById(R.id.ques_four_no);
final Button nextstep = (Button)findViewById(R.id.next_step);
ques_one_yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
one = 1;
ques_one_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
ques_one_yes.setBackground(getDrawable(R.drawable.button_background));
ques_one_no.setTextColor(getApplication().getResources().getColor(R.color.black));
ques_one_no.setBackground(getDrawable(R.drawable.inactive_button_background));
}
});
ques_one_no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
one = 1;
ques_one_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
ques_one_no.setBackground(getDrawable(R.drawable.button_background));
ques_one_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
ques_one_yes.setBackground(getDrawable(R.drawable.inactive_button_background));
}
});
ques_two_yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
two = 1;
ques_two_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
ques_two_yes.setBackground(getDrawable(R.drawable.button_background));
ques_two_no.setTextColor(getApplication().getResources().getColor(R.color.black));
ques_two_no.setBackground(getDrawable(R.drawable.inactive_button_background));
}
});
ques_two_no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
two = 1;
ques_two_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
ques_two_no.setBackground(getDrawable(R.drawable.button_background));
ques_two_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
ques_two_yes.setBackground(getDrawable(R.drawable.inactive_button_background));
}
});
ques_three_yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
three = 1;
ques_three_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
ques_three_yes.setBackground(getDrawable(R.drawable.button_background));
ques_three_no.setTextColor(getApplication().getResources().getColor(R.color.black));
ques_three_no.setBackground(getDrawable(R.drawable.inactive_button_background));
}
});
ques_three_no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
three = 1;
ques_three_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
ques_three_no.setBackground(getDrawable(R.drawable.button_background));
ques_three_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
ques_three_yes.setBackground(getDrawable(R.drawable.inactive_button_background));
}
});
ques_four_yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
four = 1;
ques_four_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
ques_four_yes.setBackground(getDrawable(R.drawable.button_background));
ques_four_no.setTextColor(getApplication().getResources().getColor(R.color.black));
ques_four_no.setBackground(getDrawable(R.drawable.inactive_button_background));
}
});
ques_four_no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
four = 1;
ques_four_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
ques_four_no.setBackground(getDrawable(R.drawable.button_background));
ques_four_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
ques_four_yes.setBackground(getDrawable(R.drawable.inactive_button_background));
}
});
}
}
Quesions
you can try "RadioGroup" and "RadioButton"
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(RadioGroup rb, int id){
if (id == R.id.ques_one_yes)
}
})
and in layout file
<RadioGroup
android:id="#+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/ques_one_yes"
android:layout_width="wrap_content"
android:BackGround="#drawable/rb_bg"
android:layout_height="wrap_content"/>
</RadioGroup>
and in drawable file rb_bg.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/button_background" android:state_checked="true"/>
<item android:drawable="#drawable/inactive_button_background"/>
</selector>
and the TextColor is other drawable file
The simplest implementation that comes to my mind is to check all of the int values you defined. You can do it in a helper method together with background and color changes
private void helperMethodName (Button buttonNo, Button buttonYes){
buttonNo.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
buttonNo.setBackground(getDrawable(R.drawable.button_background));
buttonYes.setTextColor(getApplication().getResources().getColor(R.color.black));
buttonYes.setBackground(getDrawable(R.drawable.inactive_button_background));
if (one != 0 && two != 0 && three != 0 && fore != 0) {
nextstep.setEnabled(true);
}
}
And then just call this method in your on clicks
public void onClick(View v) {
one = 1;
helperMethodName(ques_one_no, ques_one_yes);
}
Your are taking the initial values for all the options as 0 and making it 1 on OnClick.
Just give an if-else in your onCreate method like:
if(one = 1 && two = 1 && three = 1 && four = 1)
button.setEnable(true);
else
button.setEnable(false);
if all values are 1 then enable the button, else disable it.
In general if you want to achieve this implementation you can try the following ,
To enable/disable the next button:
fun enableNextButton(isEnable: Boolean) {
if(isEnable){
button_next?.alpha = 1.0f
button_next?.isEnabled = true
}else{
button_next?.alpha = 0.5f
button_next?.isEnabled = false
}
}
So call enableNextButton(true) if you want to enable the next button otherwise pass the false param to method. Also alpha sets the button blur which helps you to show the disable button view.
I am building a memory game with four cards(2x2). These four cards have an onClick named "cards". This onClick consists of an If statement that flips the cards back if they are not the same, and keeps them if they are the same.
The front image of the card is the same for the 4, but the back has different images.My problem is that I want the cards to flip, but they already have an onClick. So how can I write "if button clicked" in an If statement or is there another solution?
EDIT:
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
button1.setVisibility(View.INVISIBLE);
pic1 = (ImageView) findViewById(R.id.imageView);
pic2 = (ImageView) findViewById(R.id.imageView2);
pic3 = (ImageView) findViewById(R.id.imageView3);
pic4 = (ImageView) findViewById(R.id.imageView4);
pic1.setImageResource(R.drawable.img1);
pic2.setImageResource(R.drawable.img1);
pic3.setImageResource(R.drawable.img1);
pic4.setImageResource(R.drawable.img1);
pic1.setVisibility(View.VISIBLE);
pic2.setVisibility(View.VISIBLE);
pic3.setVisibility(View.VISIBLE);
pic4.setVisibility(View.VISIBLE);
}
});
}
public void cards(View v) {
if (v.getId() == pic1.getId() ) {
pic1.setImageResource(R.drawable.img2);
pic1.setTag("img2");
} else if (v.getId() == pic2.getId()) {
pic2.setImageResource(R.drawable.img2);
pic2.setTag("img2");
} else if (v.getId() == pic3.getId()) {
pic3.setImageResource(R.drawable.img3);
pic3.setTag("img3");
} else if (v.getId() == pic4.getId()) {
pic4.setImageResource(R.drawable.img3);
pic4.setTag("img3");
}
if (R.drawable.img2 == R.drawable.img2) {
pic1.setImageResource(R.drawable.img2);
pic1.getTag();
pic2.setImageResource(R.drawable.img2);
pic2.getTag();
}
if (R.drawable.img3 == R.drawable.img3) {
pic3.setImageResource(R.drawable.img3);
pic3.getTag();
pic4.setImageResource(R.drawable.img3);
pic4.getTag();
}
if (R.drawable.img2 != R.drawable.img2 || R.drawable.img3 != R.drawable.img3) {
pic1.setImageResource(R.drawable.img1);
pic2.setImageResource(R.drawable.img1);
pic3.setImageResource(R.drawable.img1);
pic4.setImageResource(R.drawable.img1);
}
}
SECOND METHOD I'M TRYING: #Override
public void onClick(View v) {
button1.setVisibility(View.INVISIBLE);
pic1 = (ImageView) findViewById(R.id.imageView);
pic2 = (ImageView) findViewById(R.id.imageView2);
pic3 = (ImageView) findViewById(R.id.imageView3);
pic4 = (ImageView) findViewById(R.id.imageView4);
pic1.setImageResource(R.drawable.img1);
pic2.setImageResource(R.drawable.img1);
pic3.setImageResource(R.drawable.img1);
pic4.setImageResource(R.drawable.img1);
pic1.setVisibility(View.VISIBLE);
pic2.setVisibility(View.VISIBLE);
pic3.setVisibility(View.VISIBLE);
pic4.setVisibility(View.VISIBLE);
if (R.drawable.img2 == R.drawable.img2) {
pic1.setImageResource(R.drawable.img2);
pic2.setImageResource(R.drawable.img2);
}
if (R.drawable.img3 == R.drawable.img3) {
pic3.setImageResource(R.drawable.img3);
pic4.setImageResource(R.drawable.img3);
}
if (R.drawable.img2 != R.drawable.img2 || R.drawable.img3 != R.drawable.img3) {
pic1.setImageResource(R.drawable.img1);
pic2.setImageResource(R.drawable.img1);
pic3.setImageResource(R.drawable.img1);
pic4.setImageResource(R.drawable.img1);
}
}
});
}
public void pic1Click(View v){
pic1.setImageResource(R.drawable.img1);
}
public void pic2Click(View v){
pic2.setImageResource(R.drawable.img1);
}
public void pic3Click(View v){
pic3.setImageResource(R.drawable.img2);
}
public void pic4Click(View v){
pic4.setImageResource(R.drawable.img2);
}
So I think you are looking for a way to figure out which ImageButton the user clicked. You can get this from the view variable being passed to the onClick method.
You also need to keep track of which images have been clicked. You can keep track of this by adding a tag to the image.
public void myClickMethod(View v){
if (v.getId() == pic1.getId() ) {
pic1.setImageResource(R.drawable.img2);
pic1.addTag("img2");
} else if (v.getId() == pic2.getId() {
pic2.setImageResource(R.drawable.img2);
pic2.addTag("img2");
} else if (v.getId() == pic3.getId() {
pic3.setImageResource(R.drawable.img3);
pic3.addTag("img3");
} else if (v.getId() == pic4.getId() {
pic4.setImageResource(R.drawable.img3);
pic4.addTag("img3");
}
Of course you will want to set the tag every time you change the image (and the first time you create the image). So to check if you need a reset, you would need to check that two images have changed away from the default image they started with. You could also do this with global variables, but tags might be a little more intuitive.
You can reference the Android Dev Doc
At first, you need to know what is Event Listeners, and implement it.
After you did it,and then you can Register the Event Listeners with your implementation.
Example Code
// Create an anonymous implementation of OnClickListener
private OnClickListener mCorkyListener = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
}
};
protected void onCreate(Bundle savedValues) {
...
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
// Register the onClick listener with the implementation above
button.setOnClickListener(mCorkyListener);
...
}
Try this
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
b1 = (Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//write your codes here
}
});
}
I create my views dynamically and the buttons,
I want to pass a string parameter in the onclick void that is in my loop, but always take the last value linkbutton node !!
if (type.equals("link") == true )
{
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams
(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
if (classe.equals("text") == true)
{
Button txtlink= new Button(getApplicationContext());
txtlink.setText(value);
txtlink.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
buttonClick(linkButton);
}
});
ll.addView(txtlink);
}
else if(classe.equals("button") == true)
{
Button btn_entregistrer = new Button(getApplicationContext());
btn_entregistrer.setText(value);
ll.addView(btn_entregistrer);
btn_entregistrer.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
buttonClick(linkButton);
}
});
}
}
what to do?
It will always take last value because you did not define and initialize linkButton variable inside the loop.
Before passing the value in click , Declare and initialization of variable compulsaory.
Inside the loop
String linkButton="value";
if (type.equals("link") == true )
{
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams
(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
if (classe.equals("text") == true)
{
Button txtlink= new Button(getApplicationContext());
txtlink.setText(value);
txtlink.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
buttonClick(linkButton);
}
});
ll.addView(txtlink);
}
else if(classe.equals("button") == true)
{
Button btn_entregistrer = new Button(getApplicationContext());
btn_entregistrer.setText(value);
ll.addView(btn_entregistrer);
btn_entregistrer.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
buttonClick(linkButton);
}
});
} }
As I see you are not changing the value for linkButton. That's the reason why always gets the same value.
In my SMS app, I have a dialog that opens when the user clicks on an attached image to expand it.
Everything worked fine until I decided to add animations. This dialog has 3 buttons (one close ImageButton in the top right corner and two buttons in a bottom bar of the dialog). When the user clicks on the image, the buttons anime out/in. This all works fine except the buttons are still clickable even after they're hidden.
Before Animations:
After Animations:
My code for the dialog below:
// Declare these here to increase scope. (Listeners)
private static boolean ContainerChanged;
private static boolean ActionsHidden;
private static boolean AnimStarted;
private static boolean closeAnimFinished;
private static boolean barAnimFinished;
private void showExpandedImageDialog(Uri imgUri)
{
// Initialize Dialog
final Dialog dialog = new Dialog(ActivitySend.this, R.style.FullHeightDialog);
dialog.setContentView(R.layout.dialog_attachment_image_send);
// Initialize Views
final RelativeLayout Container = (RelativeLayout) dialog.findViewById(R.id.Container);
final LinearLayout actions = (LinearLayout) dialog.findViewById(R.id.Actions);
final ImageButton btnClose = (ImageButton) dialog.findViewById(R.id.btnClose);
Button btnReplace = (Button) dialog.findViewById(R.id.btnReplace);
Button btnRemove = (Button) dialog.findViewById(R.id.btnRemove);
ImageView image = (ImageView) dialog.findViewById(R.id.Image);
// Load Image & Make Zoomable
PhotoViewAttacher mAttacher = new PhotoViewAttacher(image);
image.setImageURI(imgUri);
mAttacher.update();
// Get animations ready
final Animation fiCloseAnim = AnimationUtils.loadAnimation(ActivitySend.this, R.anim.fade_in);
fiCloseAnim.setFillEnabled(true);
fiCloseAnim.setFillAfter(true);
final Animation foCloseAnim = AnimationUtils.loadAnimation(ActivitySend.this, R.anim.fade_out);
foCloseAnim.setFillEnabled(true);
foCloseAnim.setFillAfter(true);
final Animation dBarAnim = AnimationUtils.loadAnimation(ActivitySend.this, R.anim.slide_down);
dBarAnim.setFillEnabled(true);
dBarAnim.setFillAfter(true);
final Animation uBarAnim = AnimationUtils.loadAnimation(ActivitySend.this, R.anim.slide_up);
uBarAnim.setFillEnabled(true);
uBarAnim.setFillAfter(true);
// Reset static variables
ActionsHidden = false;
AnimStarted = false;
closeAnimFinished = false;
barAnimFinished = false;
// Initialize listeners
AnimationListener closeAnimListener = new AnimationListener()
{
#Override
public void onAnimationEnd(Animation animation)
{
closeAnimFinished = true;
if (closeAnimFinished && barAnimFinished)
{
AnimStarted = false;
closeAnimFinished = false;
barAnimFinished = false;
if (ActionsHidden)
{
actions.setVisibility(View.VISIBLE);
btnClose.setVisibility(View.VISIBLE);
}
else
{
actions.setVisibility(View.GONE);
btnClose.setVisibility(View.GONE);
}
ActionsHidden = !ActionsHidden;
}
}
#Override
public void onAnimationRepeat(Animation animation)
{
// Nothing
}
#Override
public void onAnimationStart(Animation animation)
{
AnimStarted = true;
}
};
AnimationListener barAnimListener = new AnimationListener()
{
#Override
public void onAnimationEnd(Animation animation)
{
barAnimFinished = true;
if (closeAnimFinished && barAnimFinished)
{
AnimStarted = false;
closeAnimFinished = false;
barAnimFinished = false;
if (ActionsHidden)
{
actions.setVisibility(View.VISIBLE);
btnClose.setVisibility(View.VISIBLE);
}
else
{
actions.setVisibility(View.GONE);
btnClose.setVisibility(View.GONE);
}
ActionsHidden = !ActionsHidden;
}
}
#Override
public void onAnimationRepeat(Animation animation)
{
// Nothing
}
#Override
public void onAnimationStart(Animation animation)
{
AnimStarted = true;
}
};
// Set listeners
fiCloseAnim.setAnimationListener(closeAnimListener);
foCloseAnim.setAnimationListener(closeAnimListener);
dBarAnim.setAnimationListener(barAnimListener);
uBarAnim.setAnimationListener(barAnimListener);
// Actions Appear/Disappear onTap (Animate)
mAttacher.setOnPhotoTapListener(new OnPhotoTapListener()
{
#Override
public void onPhotoTap(View view, float x, float y)
{
if (!AnimStarted && ActionsHidden)
{
actions.startAnimation(uBarAnim);
btnClose.startAnimation(fiCloseAnim);
}
else if (!AnimStarted)
{
actions.startAnimation(dBarAnim);
btnClose.startAnimation(foCloseAnim);
}
}
});
// Make dialog square
ContainerChanged = false;
ViewTreeObserver vto = Container.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener()
{
public boolean onPreDraw()
{
// Set boolean to save processing power
if (!ContainerChanged)
{
int width = Container.getMeasuredWidth();
Container.getLayoutParams().height = width;
ContainerChanged = true;
}
return true;
}
});
// Set button listeners
btnClose.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
dialog.dismiss();
}
});
btnReplace.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
}
});
btnRemove.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
}
});
// Show dialog
dialog.show();
}
Everything works perfectly if I remove the animations and only use view.setVisibility(View.GONE) but I really like the animations...
Any ideas on what I could do to fix this?
I could probably use view.setClickable(false); but I'm sure there's a better solution than that.
You can do it like this:
Let your activity implement AnimationListener. Then there will be an overridden method public void onAnimationEnd(Animation arg0), write setClickable(false) or setEnabled(false) in this method for all three of your buttons, enable them again when you are starting your animation....hope you got me..