I am new to Android Butterknife and want to change the background color of floating Button. I am unable to do this.How can i achieve this.Thanks in advance.Application crashes when i use .
floatingActionButton.setBackgroundTintList(ColorStateList.valueOf(Color
.parseColor("#33691E")));
This works fine if i donot integrate Butterknife.
This is my floating Button
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:id="#+id/fab1"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
app:rippleColor="#android:color/white"
android:layout_margin="16dp"
android:src="#drawable/circle"
android:onClick="newForm"
app:layout_anchorGravity="bottom|right|end" />
And in MainActivity
public class MainActivity extends AppCompatActivity implements
SearchView.OnQueryTextListener {
#BindView(R.id.fab1)
FloatingActionButton floatingActionButton;
#BindColor(R.color.colorFolatingButton)
int Floating_Button_Color;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
floatingActionButton.setBackgroundColor(Floating_Button_Color);
}
#OnClick(R.id.fab1)
public void newForm (View view){
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Confirm");
builder.setMessage("Are you sure?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(),BuilderPage.class);
startActivity(intent);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
Use app:backgroundTint="#color/your_color"
I have found this answer from #tdamian-kozlakejjd. Follow this link this might help you
How to change FAB background color
app:backgroundTint="#color/YOURCOLOR"
xmlns:app="http://schemas.android.com/apk/res-auto"
Related
I have a tablayout with a viewpager2 and FragmentStateAdapter. I have 3 tabs, each with a NestedScrollView that wraps a Linear Layout:
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/scrollView"
android:focusableInTouchMode="true"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:descendantFocusability="blocksDescendants">
/* ... */
</LinearLayout>
</androidx.core.widget.NestedScrollView>
When I switch between the tabs in the tablayout, the scrollview does not start at the top. In the onViewCreated() method of each Fragment for the viewPager, I added the following lines, however the scrollview still does not scroll to the top, it starts where it was left off.
public static class MyFragment extends Fragment {
private NestedScrollView scrollView;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
scrollView = view.findViewById(R.id.scrollView);
scrollView.smoothScrollTo(0, 0);
}
}
The solution from #star4z should work, but there is an easier option. What you could do instead, use FragmentPagerAdapter for this and set it's behavior to BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT.
Every time, you change your tab, onResume will be called and there you can call your scrollView.smoothScrollTo(0, 0);
public class MyAdapter extends FragmentPagerAdapter {
...
public MyAdapter(FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}
...
}
And then in your Fragment:
public class MyFragment extends Fragment {
...
public void onResume() {
super.onResume();
scrollView.smoothScrollTo(0, 0);
}
...
}
onViewCreated is only called when the Fragments are first created. A ViewPager does not change the state of the Fragments. You can think of the hidden Fragments being stored, visible, to the sides of the currently visible Fragment.
I accomplished by setting up a callback when the TabLayout changes. The TabLayout is where the listener for this is. You can then have it call a callback method in your FragmentPagerAdapter. In each Fragment, you should implement a method that returns a callback. In the FragmentPagerAdapter, use the getItem(int position) to store the callback from the Fragment in a Map. The callback method in the adapter takes the position from the TabLayout
First, in your Fragments, give them a method that returns some kind of callback (I used a Runnable) that will be called from the adapter.
public class PlaceHolderFragment extends Fragment {
...
public Runnable getOnTabChangedListener() {
return new Runnable() {
#Override
public void run() {
scrollView.smoothScrollTo(0, 0);
}
};
}
...
}
Then, in your FragmentPagerAdapter (I called mine SectionsPagerAdapter), store the callbacks in a map in the getItem() method, and then add a custom callback.
public class SectionsPagerAdapter extends FragmentPagerAdapter {
...
HashMap<Integer, Runnable> tabChangedCallbacks = new HashMap<>();
...
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
PlaceholderFragment fragment = PlaceholderFragment.newInstance(position + 1);
tabChangedCallbacks.put(position, fragment.getOnTabChangedListener());
return fragment;
}
public void onTabChanged(int position) {
tabChangedCallbacks.get(position).run();
}
...
}
In your activity that contains the TabLayout, you will want to call addOnTabSelectedListener() on the TabLayout in the onCreate() method.
protected void onCreate(Bundle savedInstanceState) {
...
final SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
final ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
tabs.addOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
sectionsPagerAdapter.onTabChanged(tab.getPosition());
}
});
...
}
EDIT
The principle is the same, but for this to work using ViewPager2 and FragmentStateAdapter, you will need the follow changes:
The Fragment stays the same.
The adapter is the same, functionally, with some updated methods:
public class SectionsStateAdapter extends FragmentStateAdapter {
HashMap<Integer, Runnable> tabChangedCallbacks = new HashMap<>();
...
public void onTabChanged(int position) {
tabChangedCallbacks.get(position).run();
}
#NonNull
#Override
public Fragment createFragment(int position) {
PlaceholderFragment fragment = PlaceholderFragment.newInstance(position + 1);
tabChangedCallbacks.put(position, fragment.getOnTabChangedListener());
return fragment;
}
#Override
public int getItemCount() {
return 2;
}
...
}
The activity changes the most:
public class MainActivity extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
final SectionsStateAdapter sectionsStateAdapter = new SectionsStateAdapter(this);
final ViewPager2 viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsStateAdapter);
TabLayout tabs = findViewById(R.id.tabs);
// connect the TabLayout to the ViewPager2
new TabLayoutMediator(tabs, viewPager, new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
// set tab text, etc
}
}).attach();
// set the change listener on the ViewPager2
viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
sectionsStateAdapter.onTabChanged(position);
}
});
...
}
}
Note that the only real change is that the ViewPager2 doesn't need the TabLayout to handle the page change. You could still use TabLayout.addOnTabSelectedListener() if you wanted, but you would have to implement your own TabLayout.OnTabSelecterListener since TabLayout.ViewPagerOnTabSelectedListener doesn't work with ViewPager2.
For example:
tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
sectionsStateAdapter.onTabChanged(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
I have a problem with my code I develop a game on android studio and I meet the following concern.
There are two buttons on my app, a Punch button and a Kick Button and an Imageview in which I animate my images.
When I click on the punch button, I create a drawable animation of two images
when I click on the kick button, I create a drawable animation of two images as well.
The problem is that when I execute this code with two drawable animations, the application crashes !!
public class MainActivity extends AppCompatActivity {
private Button btnPunch;
private Button btnKick;
private ImageView imageView1 ;
private ImageView imageView2 ;
private AnimationDrawable[] animationDrawable = new
AnimationDrawable[2];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPunch = (Button) findViewById(R.id.btnPunch);
imageView1 = (ImageView)
findViewById(R.id.imageView1);
imageView1.setBackgroundResource(
R.drawable.animationpunch);
animationDrawable[0] = (AnimationDrawable)
imageView1.getBackground();
imageView2 = (ImageView)
findViewById(R.id.imageView2);
imageView2.setBackground
Resource(R.drawable.animatio
nkick);
animationDrawable[1] = (AnimationDrawable)
imageView2.getBackground();
btnPunch.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
animationDrawable[1].stop();
animationDrawable[0].setOneShot(true);
animationDrawable[0].start();
}
});
btnKick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
animationDrawable[0].stop()
animationDrawable[1].setOneShot(true);
animationDrawable[1].start();
}
});
}
#Override
public void onWindowFocusChanged(boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);
//animationDrawable.start();
}
}
</Code>
I yet use two different imageview for both animations
on the other hand when I remove an animation like the following code, it works well but suddenly I am limited to use the punch button, I would like it to work with both buttons
public class MainActivity extends AppCompatActivity {
private Button btnPunch;
private ImageView imageView1 ;
private AnimationDrawable[] animationDrawable = new
AnimationDrawable[2];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPunch = (Button) findViewById(R.id.btnPunch);
imageView1 = (ImageView)
findViewById(R.id.imageView1);
imageView1.setBackground
Resource(R.drawable.animatio
npunch);
animationDrawable[0] = (AnimationDrawable)
imageView1.getBackground();
btnPunch.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
animationDrawable[1].stop();
animationDrawable[0].setOneShot(true);
animationDrawable[0].start();
}
}}
}
#Override
public void onWindowFocusChanged(boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);
//animationDrawable.start();
}
}
click on punch button, it animates my animation unch
I click on kick button, it animates my animation kick
a help?
So I am trying to make a button that plays a sound, at one point it asked me something about opening the sound file I want on my computer, I did not really see it and click on my PC, so every time I run my app the file gets played on my PC and the app never gets launched, anyone know how I would reset that? (Tried a new project, restarted.)
Here is some of my code:
MainActivity.java
package tech.mitchs.scarcesoundboard;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button bt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (Button)findViewById(R.id.button1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.Hey_Guys);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mp.start();
}
});
}
}
Thanks for any help!
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = MediaPlayer.create(this, R.raw.diwali);
Button play = (Button) findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
#Override
public void onCompletion(MediaPlayer mp) {
Toast.makeText(MainActivity.this, "I'm done!", Toast.LENGTH_SHORT).show();
}
});
}
});
Button pause = (Button) findViewById(R.id.pause);
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.pause();
}
});
}
Activity_main.xml:
<Button
android:id="#+id/play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/play" />
<Button
android:id="#+id/pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pause" />
This worked best for me, including playing and pausing of media that is attached.
This is my CameraView.java (I got it from http://blog.rhesoft.com/)
public class CameraView extends SurfaceView implements SurfaceHolder.Callback{
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraView(Context context, Camera camera){
super(context);
mCamera = camera;
mCamera.setDisplayOrientation(90);
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try{
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("ERROR", "Camera error on surfaceCreated " + e.getMessage());
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) {
if(mHolder.getSurface() == null)
return;
try{
mCamera.stopPreview();
} catch (Exception e){
}
try{
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("ERROR", "Camera error on surfaceChanged " + e.getMessage());
}
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
mCamera.stopPreview();
mCamera.release();
}}
and this is my MainActivity.java.
public class MainActivity extends AppCompatActivity {
private Camera mCamera = null;
private CameraView mCameraView = null;
private FrameLayout camera_view;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
mCamera = Camera.open();
//you can use open(int) to use different cameras
} catch (Exception e){
Log.d("ERROR", "Failed to get camera: " + e.getMessage());
}
if(mCamera != null) {
mCameraView = new CameraView(this, mCamera);//create a SurfaceView to show camera data
camera_view = (FrameLayout)findViewById(R.id.camera_view);
camera_view.addView(mCameraView);//add the SurfaceView to the layout
}
//btn to close the application
final ImageButton imgClose = (ImageButton)findViewById(R.id.imgClose);
final ImageButton capImg = (ImageButton) findViewById(R.id.imgCapture);
imgClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imgClose.setVisibility(View.INVISIBLE);
capImg.setVisibility(View.VISIBLE);
mCamera.startPreview();
}
});
capImg.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
mCamera.stopPreview();
imgClose.setVisibility(View.VISIBLE);
capImg.setVisibility(View.INVISIBLE);
}
});
}
#Override
public void onBackPressed(){
System.exit(0);
}}
and this my activity_main.xml.
<FrameLayout
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"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/camera_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgClose"
android:layout_gravity="right|top"
android:background="#android:drawable/ic_menu_close_clear_cancel"
android:padding="20dp"
android:visibility="invisible" />
<ImageButton
android:layout_width="98dp"
android:layout_height="98dp"
android:id="#+id/imgCapture"
android:layout_gravity="center_horizontal|bottom"
android:background="#android:drawable/ic_menu_camera"
android:padding="20dp"/>
Can I capture this FrameLayout preview as image or do some programing with that preview like delete red color? Can you give me some clue?
So if I understand correctly, you wish to get the image data that is shown when you stop the preview? If you so you can mCamera.takePicture() method. It takes 3 parameters, all of which are useful callbacks. Here is something I recently did to show you.
btn_Capture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCamera == null)
return;
mCamera.takePicture(null, null, mPicture);
}
});
This is my button click listener which is a floating image button (any button will work just fine). The third parameter is a callback that returns an array of pixels that you can convert into a bitmap.
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
mCamera.stopPreview();
Bitmap bMap = BitmapFactory.decodeByteArray(data, 0, data.length);
preview.removeView(mPreview);
img_Captured.setImageBitmap(bMap);
}
};
This is the callback which I passed in the takePicture() method. byte[] data is the image that you are trying to get. As you can see I converted it into a bitmap and displayed it to an ImageView after removing the surfaceview (which holds the camera preview). Just a note, the takePicture() method stops the preview automatically so don't stop the preview before taking the photo. You can do it how I did it in the callback. Also, if you want to take another photo, you can start the preview again.
I hope this helps!! Let me know if I left anything out! By the way, it is all documented on the Android Developer site.
http://developer.android.com/training/camera/cameradirect.html#TaskTakePicture
I'm trying to show a progress bar when loading a custom ListView and afterwards - hide it.
I'm using ASync task, but for some reason - The content view is not set and the previous layout view is stuck until all the list view is loaded.
Here is my code:
private ListView listViewGameResults;
protected View dialogLayout;
protected ArrayList<Game> listGames;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adresults);
GameResultsLoader gameResultsLoader = new GameResultsLoader();
gameResultsLoader.execute();
}
private class GameResultsLoader extends AsyncTask<Void, Void, Void> {
private GameResultsAdapter adapter;
public GameResultsLoader() {
}
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
try {
listGames = GameResultsCache.getInstance().getGameResults();
adapter = new GameResultsAdapter(getBaseContext(), listGames);
listViewGameResults = (ListView)findViewById(R.id.listViewGameResults);
}
catch (Exception e) {
// TODO Auto-generated catch block
finish();
}
return null;
}
#Override
protected void onPostExecute(Void res) {
listViewGameResults.setAdapter(adapter);
listViewGameResults.setDivider(null);
listViewGameResults.setDividerHeight(0);
ProgressBar pb = (ProgressBar)findViewById(R.id.progressbar_loading);
pb.setVisibility(View.GONE);
}
}
ProgressBar and ListView in my layout:
<ProgressBar
style="?android:attr/progressBarStyle"
android:layout_centerInParent="true"
android:id="#+id/progressbar_loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/listViewGameResults"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="1dip"
android:layout_below="#+id/upperstrip"
android:layout_above="#+id/ivDownStrip" />
You need to set default visibility of progressBar gone.and onPreExecute()set Visible and onPostExecute()set gone.
<ProgressBar
style="?android:attr/progressBarStyle"
android:layout_centerInParent="true"
android:id="#+id/progressbar_loading"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/listViewGameResults"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="1dip"
android:layout_below="#+id/upperstrip"
android:layout_above="#+id/ivDownStrip" />
your Activity should look like this
public class demo extends Activity{
private ListView listViewGameResults;
protected View dialogLayout;
protected ArrayList<Game> listGames;
progressBar progress;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adresults);
progress=(ProgressBar)findViewByid(R.id.progressbar_loading);
GameResultsLoader gameResultsLoader = new GameResultsLoader(this);
gameResultsLoader.execute();
}
}
Use one separate class for AsyncTask
public class GameResultsLoader extends AsyncTask<Void, Void, Void> {
private GameResultsAdapter adapter;
Demo demo;
public GameResultsLoader(Demo demo) {
this.demo=demo;
}
#Override
protected void onPreExecute() {
demo.progress.setvisibility(View.Visible);
}
#Override
protected Void doInBackground(Void... params) {
try {
listGames = GameResultsCache.getInstance().getGameResults();
adapter = new GameResultsAdapter(getBaseContext(), listGames);
listViewGameResults = (ListView)findViewById(R.id.listViewGameResults);
}
catch (Exception e) {
// TODO Auto-generated catch block
finish();
}
return null;
}
#Override
protected void onPostExecute(Void res) {
listViewGameResults.setAdapter(adapter);
listViewGameResults.setDivider(null);
listViewGameResults.setDividerHeight(0);
ProgressBar pb = (ProgressBar)findViewById(R.id.progressbar_loading);
demo.progress.setVisibility(View.GONE);
}
}
if your using asnkTask that is work on main Thread so application is much more load.so better solution is using Service.class.
downlaod this example Check this link all are solution are there and download it:
you have to also get list from relaunch this application.
https://github.com/PankajSavaliyaGit/Upload-List
you have to write code to start progressDialog in preExecute method and at the postExecute dismiss it.
#Override
protected void onPreExecute() {
proDialog = new ProgressDialog(context);
proDialog.setTitle("App name");
proDialog.setMessage("Loding...");
proDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//proDialog.setIcon(R.drawable.)
proDialog.setCancelable(true);
proDialog.show();
}
#Override
protected void onPostExecute(Void res) {
proDialog.dismiss();
}
The first thing you can do is put Progress bar code after OnCreate method. But the best thing is to create a simple method for Progress bar and only call it in OnCreate method.
The following code worked fine for me:
private void showDialog() {
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Have a nice time");
progressDialog.setMessage("Please wait while showing Titles :) ");
progressDialog.setCancelable(true);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
}
And then call this method in OnCreate
showDialog();
You can stop Progress when the data is ready to view using:
progressDialog.dismiss();
I hope this is helpful.