How to change from onClick to onTouch method? - java

I'm creating music app and I need a change from onClick to the onTouch method so I can listen the sound at the moment I press the button and not only when release it. I can't figure out clearly what I need to add and change.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private SoundPool mSoundPool;
private int btn2;
private int btn5;
private int btn13;
private int btn14;
private int btn15;
private int btn16;
private int btn17;
private int btn18;
private int btn19;
private int btn20;
private int btn21;
private int btn22;
private float LEFT_VOL = 1.0f;
private float RIGHT_VOL = 1.0f;
private int PRIORITY = 1;
private int LOOP = 0;
private float RATE = 1.0f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
mSoundPool = new SoundPool(24, AudioManager.STREAM_MUSIC,0);
btn2 = mSoundPool.load(getApplicationContext(),R.raw.r,1);
btn5 = mSoundPool.load(getApplicationContext(),R.raw.g,1);
btn13 = mSoundPool.load(getApplicationContext(),R.raw.k,1);
btn14 = mSoundPool.load(getApplicationContext(),R.raw.hat,1);
btn15 = mSoundPool.load(getApplicationContext(),R.raw.s,1);
btn16 = mSoundPool.load(getApplicationContext(),R.raw.a,1);
btn17 = mSoundPool.load(getApplicationContext(),R.raw.d,1);
btn18 = mSoundPool.load(getApplicationContext(),R.raw.c,1);
btn19 = mSoundPool.load(getApplicationContext(),R.raw.f,1);
btn20 = mSoundPool.load(getApplicationContext(),R.raw.e,1);
btn21 = mSoundPool.load(getApplicationContext(),R.raw.h,1);
btn22 = mSoundPool.load(getApplicationContext(),R.raw.b,1);
}
public void playC(View v){
mSoundPool.play(btn2,1,1,0,0,1);
}
public void playD(View v){
mSoundPool.play(btn5,1,1,0,0,1);
}
public void playE(View v){
mSoundPool.play(btn13,1,1,0,0,1);
}
public void playF(View v){
mSoundPool.play(btn14,1,1,0,0,1);
}
public void playG(View v){
mSoundPool.play(btn15,1,1,0,0,1);
}
public void playA(View v){
mSoundPool.play(btn16,1,1,0,0,1);
}
public void playB(View v){
mSoundPool.play(btn17,1,1,0,0,1);
}
public void playCC(View v){
mSoundPool.play(btn18,1,1,0,0,1);
}
public void playCS(View v){
mSoundPool.play(btn19,1,1,0,0,1);
}
public void playDS(View v){
mSoundPool.play(btn20,1,1,0,0,1);
}
public void playFS(View v){
mSoundPool.play(btn21,1,1,0,0,1);
}
public void playGS(View v){
mSoundPool.play(btn22,1,1,0,0,1);
}
Activity_Main XML:
<?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"
android:background="#000000"
android:screenOrientation="landscape"
tools:context=".MainActivity">
<Button
android:id="#+id/btn22"
android:layout_width="76dp"
android:layout_height="70dp"
android:background="#android:color/holo_red_dark"
android:onClick="playGS" />
<Button
android:id="#+id/btn21"
android:layout_width="76dp"
android:layout_height="70dp"
android:background="#android:color/holo_red_dark"
android:onClick="playFS" />
<Button
android:id="#+id/btn20"
android:layout_width="76dp"
android:layout_height="70dp"
android:background="#android:color/holo_red_dark"
android:onClick="playDS" />
<Button
android:id="#+id/btn19"
android:layout_width="76dp"
android:layout_height="70dp"
android:background="#android:color/holo_red_dark"
android:onClick="playCS" />
<Button
android:id="#+id/btn18"
android:layout_width="76dp"
android:layout_height="70dp"
android:background="#android:color/holo_red_dark"
android:onClick="playCC" />
<Button
android:id="#+id/btn17"
android:layout_width="76dp"
android:layout_height="70dp"
android:background="#android:color/holo_red_dark"
android:onClick="playB" />
<Button
android:id="#+id/btn16"
android:layout_width="76dp"
android:layout_height="70dp"
android:background="#android:color/holo_red_dark"
android:onClick="playA" />
<Button
android:id="#+id/btn15"
android:layout_width="87dp"
android:layout_height="80dp"
android:background="#android:color/background_light"
android:onClick="playG"
/>
<Button
android:id="#+id/btn14"
android:layout_width="87dp"
android:layout_height="80dp"
android:background="#android:color/background_light"
android:onClick="playF" />
<Button
android:id="#+id/btn13"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_width="87dp"
android:layout_height="80dp"
android:background="#android:color/background_light"
android:onClick="playE" />
<Button
android:id="#+id/btn2"
style="#style/Widget.AppCompat.Button.Small"
android:layout_width="87dp"
android:layout_height="80dp"
android:background="#android:color/background_light"
android:onClick="playC" />
<Button
android:id="#+id/btn5"
android:layout_width="76dp"
android:layout_height="69dp"
android:background="#android:color/holo_red_dark"
android:onClick="playD" />
I tried follow a lot of examples from internet but has always ended not effective.

Step 1: Remove the android:onClick attributes so
<Button
android:id="#+id/btn5"
android:layout_width="76dp"
android:layout_height="69dp"
android:background="#android:color/holo_red_dark"
android:onClick="playD" />
becomes
<Button
android:id="#+id/btn5"
android:layout_width="76dp"
android:layout_height="69dp"
android:background="#android:color/holo_red_dark" />
Step 2: In the end of onCreate() method (just after btn22 = mSoundPool.load(getApplicationContext(),R.raw.b,1); and just before the closing }) insert this code
findViewById(R.id.btn5).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction()==MotionEvent.ACTION_DOWN) playD(v);
return false;
}
});
Try it out with one of the buttons first, when it works proceed to the next buttons.
There are a lot of other ways of doing it, for example you could remove the method
public void playD(View v){
mSoundPool.play(btn5,1,1,0,0,1);
}
and instead have this in onCreate():
findViewById(R.id.btn5).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction()==MotionEvent.ACTION_DOWN) mSoundPool.play(btn5,1,1,0,0,1);
return false;
}
});
#Pratik_Butani pointed at How to define setOnTouchListener for multiple buttons in Android fragment which are a little more complicated but will be fine to look at when you get a little more understanding, later on.

Related

How to make messages appear on different sides?

I make a chat app using a video tutorial, but this tutorial does not show how to make messages from different people appear on different sides. The sender and receiver see all messages on the left. Could you please give some advices on this? Thanks in advance.
Now it looks like this
Main code
public class MainActivity extends AppCompatActivity {
private static int SIGN_IN_CODE=1;
private RelativeLayout activity_main;
private FirebaseListAdapter<Message> adapter;
private FloatingActionButton sendBtn;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==SIGN_IN_CODE) {
if(requestCode == RESULT_OK) {
Snackbar.make(activity_main, "You are authorized", Snackbar.LENGTH_LONG).show();
displayAllMessages();
} else {
Snackbar.make(activity_main, "You are not authorized", Snackbar.LENGTH_LONG).show();
finish();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity_main=findViewById(R.id.activity_main);
sendBtn = findViewById(R.id.btnSend);
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText textField = findViewById(R.id.messageField);
if(textField.getText().toString().equals(""))
return;
FirebaseDatabase.getInstance().getReference().push().setValue(
new Message(
FirebaseAuth.getInstance().getCurrentUser().getEmail(),
textField.getText().toString()));
textField.setText("");
}
});
//Пользователь ещё не авторизован
if (FirebaseAuth.getInstance().getCurrentUser()==null)
startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(), SIGN_IN_CODE);
//Пользователь авторизован
else {
Snackbar.make(activity_main, "You are authorized", Snackbar.LENGTH_LONG).show();
displayAllMessages();
}
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
private void displayAllMessages() {
ListView listOfMessages = findViewById(R.id.list_of_messages);
FirebaseListOptions<Message> options =
new FirebaseListOptions.Builder<Message>()
.setQuery(FirebaseDatabase.getInstance().getReference(), Message.class)
.setLayout(R.layout.list_item)
.build();
adapter = new FirebaseListAdapter<Message>(options){
#Override
protected void populateView(View v, Message model, int position) {
TextView mess_user, mess_time;
BubbleTextView mess_text;
mess_user = v.findViewById(R.id.message_user);
mess_time = v.findViewById(R.id.message_time);
mess_text = v.findViewById(R.id.message_text);
mess_user.setText(model.getUserName());
mess_text.setText(model.getTextMessage());
mess_time.setText(DateFormat.format("dd-MM-yyyy HH:mm:ss", model.getMessageTime()));
}
};
listOfMessages.setAdapter(adapter);
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
Message Class
public class Message {
private String UserName;
private String TextMessage;
private long MessageTime;
public Message() {}
public Message (String UserName, String TextMessage){
this.UserName = UserName;
this.TextMessage = TextMessage;
this.MessageTime = new Date().getTime();
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public String getTextMessage() {
return TextMessage;
}
public void setTextMessage(String textMessage) {
TextMessage = textMessage;
}
public long getMessageTime() {
return MessageTime;
}
public void setMessageTime(long messageTime) {
MessageTime = messageTime;
}
}
Main XML
<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"
android:id="#+id/activity_main">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:src="#drawable/ic_send_button"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
app:fabSize="normal">
</com.google.android.material.floatingactionbutton.FloatingActionButton>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/text_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#id/btnSend"
>
<EditText
android:id="#+id/messageField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint=" Message..."
/>
</com.google.android.material.textfield.TextInputLayout>
<ListView
android:id="#+id/list_of_messages"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/text_layout"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:divider="#android:color/transparent"
android:dividerHeight="12dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll">
</ListView>
</RelativeLayout>
XML for the message bubbles
<RelativeLayout
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="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/message_user"
android:textStyle="normal|bold"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:id="#+id/message_time"
/>
<com.github.library.bubbleview.BubbleTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:id="#+id/message_text"
android:layout_marginTop="9dp"
android:layout_below="#id/message_user"
android:textSize="18sp"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#fff"
android:padding="10dp"
app:angle="10dp"
app:arrowWidth="8dp"
app:arrowHeight="10dp"
app:arrowPosition="10dp"
app:bubbleColor="#03dac5"
/>
</RelativeLayout>
Try adding layout_gravity attribute in your BubbleTextView when you need this like this:
android:layout_gravity="right"
Every user will have a unique email - Let say here in the example - d#mail.ru is your email. You need to add user logic to dynamically check to decide whether you want a bubble test layout to be LEFT or RIGHT.
Update the message bubble layout.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/message_user"
android:textStyle="normal|bold"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:id="#+id/message_time"
/>
<com.github.library.bubbleview.BubbleTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:id="#+id/message_text"
android:layout_marginTop="9dp"
android:layout_below="#id/message_user"
android:textSize="18sp"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#fff"
android:padding="10dp"
app:angle="10dp"
app:arrowWidth="8dp"
app:arrowHeight="10dp"
app:arrowPosition="10dp"
app:bubbleColor="#03dac5"
/>
</RelativeLayout>
Adapter code:- you can update as you need either LEFT or RIGHT.
adapter = new FirebaseListAdapter<Message>(options){
#Override
protected void populateView(View v, Message model, int position) {
TextView mess_user, mess_time;
BubbleTextView mess_text;
RelativeLayout Layout = v.findViewById(R.id.parentlayout);
mess_user = v.findViewById(R.id.message_user);
mess_time = v.findViewById(R.id.message_time);
mess_text = v.findViewById(R.id.message_text);
mess_user.setText(model.getUserName());
mess_text.setText(model.getTextMessage());
mess_time.setText(DateFormat.format("dd-MM-yyyy HH:mm:ss", model.getMessageTime()));
if(!model.getUserName().equals("d#mail.ru")) {
mess_text.setGravity(Gravity.LEFT)
} else {
mess_text.setGravity(Gravity.RIGHT)
}
}
};
Check this link as a reference - https://github.com/rpadma/Trip-Planner/blob/master/app/src/main/java/com/etuloser/padma/rohit/homework09a/ChatAdapter.java

TextView is not selectable with ontouchListener

I have implemented ontouchListener in my activity to detect swipes left and right. However, enabling this feature stopped me from being able to make my text selectable and accordingly getting the default android text selection cursor, menu.
After many trials, now i can perfectly call the onLongClick() method when long clicking the textView. However, still the text is not selectable. also, whenever I disable the swipe detection, the Text selection works perfectly.
public class PreviewActivity extends AppCompatActivity
{
TextView question;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preview);
question = (TextView)findViewById(R.id.question);
question.setTextSize(TextViewSize);
question.setTextIsSelectable(true);
question.setLongClickable(true);
question.setFocusableInTouchMode(true);
View prev_act = (View) findViewById(R.id.question);
prev_act.setOnTouchListener(new OnSwipeTouchListener(this) {
#Override public void onSwipeLeft() {
if(RowIndex>0){
Qtitle = ListItems.get(RowIndex-1);
Query();
//text = Query();
//question.setText(text);
questionSC.scrollTo(0,0);
RowIndex--;
}
}
#Override public void onSwipeRight() {
if(RowIndex<ListItems.size()-1){
Qtitle = ListItems.get(RowIndex+1);
Query();
//text = Query();
//question.setText(text);
questionSC.scrollTo(0,0);
RowIndex++;
}
}
#Override public void onLongClick() {
Log.v(this.toString(), "Long click.");
question.setCursorVisible(true);
question.performLongClick();
}
});
}
And the OnSwipeTouchListener class is as the following:
public class OnSwipeTouchListener implements OnTouchListener {
private final GestureDetector gestureDetector;
public OnSwipeTouchListener (Context ctx){
gestureDetector = new GestureDetector(ctx, new GestureListener());
}
#Override public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class GestureListener extends SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 250;
private static final int SWIPE_VELOCITY_THRESHOLD = 200;
#Override
public void onLongPress(MotionEvent e) {
onLongClick();
super.onLongPress(e);
}
#Override
public boolean onDown(MotionEvent e) {
return true;
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
boolean result = false;
try {
float diffY = e2.getY() - e1.getY();
float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
onSwipeRight();
} else {
onSwipeLeft();
}
result = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
public void onSwipeRight() {
}
public void onSwipeLeft() {
}
public void onSwipeTop() {
}
public void onSwipeBottom() {
}
public void onLongClick() {
}
}
I want to be able to select a portion (text) from the TextView and having the swipe detector along it.
Edited: added the XML file of the mentioned Activity
<?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:id="#+id/activity_preview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="50dp"
android:paddingRight="20dp"
android:paddingLeft="20dp"
android:paddingBottom="30dp"
android:background="#drawable/bg"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageButton
android:id="#+id/next"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:background="#0000"
android:scaleType="fitCenter"
android:src="#drawable/ic_navigate_before_black_24dp" />
<ImageButton
android:id="#+id/share"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:background="#0000"
android:padding="9dp"
android:scaleType="fitCenter"
android:src="#drawable/ic_share_black_24dp" />
<ImageButton
android:id="#+id/star"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:background="#0000"
android:padding="9dp"
android:scaleType="fitCenter"
android:src="#drawable/star_border" />
<ImageButton
android:id="#+id/copy"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:background="#0000"
android:padding="9dp"
android:scaleType="fitCenter"
android:src="#drawable/ic_content_copy_black_24dp" />
<ImageButton
android:id="#+id/previous"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:background="#0000"
android:scaleType="fitCenter"
android:src="#drawable/ic_navigate_next_black_24dp" />
</LinearLayout>
<ScrollView
android:id="#+id/questionSC"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="30dp"
android:layout_marginTop="50dp">
<LinearLayout
android:id="#+id/question_lo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/question"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fontFamily="#font/ge_thameen_book"
android:paddingBottom="20dp"
android:paddingTop="10dp"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="20dp"
android:autoLink="web"
/>
</LinearLayout>
</ScrollView>
After trying for a while this is what worked highlighting and selecting text enabling copy,paste,selectall ... etc
you will need to add onTouch snippet in the prev_act.setOnTouchListener(new OnSwipeTouchListener(this) {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_DOWN) {
//do stuff here
Log.i("clicking", "onActionDown");
}else if(event.getAction() == MotionEvent.ACTION_UP) {
question.performLongClick();
}
return false;
}
#Override public void onLongClick() {
}
The answer was very simple:
#Override
public boolean onDown(MotionEvent e) {
return false;
}
I had to set the onDown() to return false.

Strange behavior in app that wont play sound unless a Toast line is inserted

So I'm making a xylophone app and it weirdly works(plays sound) only when inserted a seemingly unimportant line which Toasts the loaded soundID and I'm not sure what to make of it.If you remove the Toast line the onClick function wont play sound at all.
The aforementioned line is in the onClick function within the for loop
public class MainActivity extends AppCompatActivity {
// Helpful Constants
private final int NR_OF_SIMULTANEOUS_SOUNDS = 7;
private final float LEFT_VOLUME = 1.0f;
private final float RIGHT_VOLUME = 1.0f;
private final int NO_LOOP = 0;
private final int PRIORITY = 0;
private final float NORMAL_PLAY_RATE = 1.0f;
//Adding IDs here
int[] xyloIDs =
{
R.id.c_key,
R.id.d_key,
R.id.e_key,
R.id.f_key,
R.id.g_key,
R.id.a_key,
R.id.b_key,
};
int[] soundIDs =
{
R.raw.note1_c,
R.raw.note2_d,
R.raw.note3_e,
R.raw.note4_f,
R.raw.note5_g,
R.raw.note6_a,
R.raw.note7_b,
};
private SoundPool mSoundPool;
private int mSoundId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating a new SoundPool
mSoundPool = new SoundPool(NR_OF_SIMULTANEOUS_SOUNDS, AudioManager.STREAM_MUSIC, 0);
}
public void onClick(View view)
{
for(int i=0; i < xyloIDs.length ; i++ )
{
if(view.getId() == xyloIDs[i]) {
//Load and get the IDs to identify the sounds
mSoundId = mSoundPool.load(this, soundIDs[i], 1);
Toast.makeText(this, String.valueOf(mSoundId) , Toast.LENGTH_SHORT).show();
mSoundPool.play(mSoundId, LEFT_VOLUME, RIGHT_VOLUME, PRIORITY, NO_LOOP, NORMAL_PLAY_RATE);
}
}
}
And here is my activity_main.xml if it makes any difference
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.londonappbrewery.xylophonepm.MainActivity">
<Button
style="#style/KeyStyle"
android:id="#+id/c_key"
android:background="#color/red"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"/>
<Button
style="#style/KeyStyle"
android:id="#+id/d_key"
android:background="#color/orange"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
/>
<Button
style="#style/KeyStyle"
android:id="#+id/e_key"
android:background="#color/yellow"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
/>
<Button
style="#style/KeyStyle"
android:id="#+id/f_key"
android:background="#color/green"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
/>
<Button
style="#style/KeyStyle"
android:id="#+id/g_key"
android:background="#color/turquoise"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
/>
<Button
style="#style/KeyStyle"
android:id="#+id/a_key"
android:background="#color/blue"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
/>
<Button
style="#style/KeyStyle"
android:id="#+id/b_key"
android:background="#color/purple"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
/>
May be your file on loading so it can not be play,
the Toasts make your load and play delay more.
You may need implement setOnLoadCompleteListener and call the play inside the listener.
mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener()
{
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId,int status) {
mSoundPool.play(sampleId, LEFT_VOLUME, RIGHT_VOLUME, PRIORITY, NO_LOOP, NORMAL_PLAY_RATE);
}
});

App Crashes when using setVisibility

As the title says,
When using startLabel.setVisibility(View.GONE);
The app Crashes and I am not sure how to fix
The Java code below.
public class Main extends AppCompatActivity {
private TextView scoreLabel;
private TextView startLabel;
private ImageView box;
private ImageView orange;
private ImageView pink;
private ImageView black;
// Position
private int boxY;
private int boxX;
// Initialize Class
private Handler handler = new Handler();
private Timer timer = new Timer();
//Status Check
private boolean action_flg = false;
private boolean start_flg = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scoreLabel = (TextView) findViewById(R.id.scoreLabel);
scoreLabel = (TextView) findViewById(R.id.startLabel);
box = (ImageView) findViewById(R.id.box);
orange = (ImageView) findViewById(R.id.orange);
pink = (ImageView) findViewById(R.id.pink);
black = (ImageView) findViewById(R.id.black);
//Moves images to out of the screen
//orange.setX(-80.0f);
orange.setY(-80.0f);
// pink.setX(-80.0f);
pink.setY(-80.0f);
//black.setX(-80.0f);
black.setY(-80.0f);
boxY = 200;
}
public void changePos()
{
//Move box
if (action_flg == true)
{
// touching
boxY -= 20;
} else {
//released
boxY += 20;
}
box.setY(boxY);
}
public boolean onTouchEvent(MotionEvent me)
{
if (start_flg == false)
{
start_flg = true;
//Issue here with setting the visibility of the start
// startLabel.setVisibility(View.GONE);
timer.schedule(new TimerTask()
{
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
changePos();
}
});
}
// Changing these numbers slows down how fast the box moves.
}, 0, 100);
}else {
if(me.getAction() == MotionEvent.ACTION_DOWN)
{
action_flg = true;
}else if (me.getAction() == MotionEvent.ACTION_UP){
action_flg = false;
}
}
return true;
}
}
Here is the XML version of the code.
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="me.scott.nathan.catchtheball.Main">
<TextView
android:id="#+id/scoreLabel"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="Score : 300"
android:textSize="18sp"
android:paddingLeft="10dp"
android:gravity="center_vertical">
</TextView>
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/startLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tap to Start"
android:textSize="30sp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="130dp"
/>
<ImageView
android:id="#+id/box"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/box"
android:layout_gravity="center_vertical"
/>
<ImageView
android:id="#+id/orange"
android:layout_width="20dp"
android:layout_height="20dp"
android:src="#drawable/orange" />
<ImageView
android:id="#+id/black"
android:layout_width="24dp"
android:layout_height="24dp"
android:src="#drawable/black" />
<ImageView
android:id="#+id/pink"
android:layout_width="16dp"
android:layout_height="16dp"
android:src="#drawable/pink" />
</FrameLayout>
<!--
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.22" />
-->
</LinearLayout>
Anyone help appreciated to fix this issue, Thanks
Your startLabel is null (copy paste problem?^^). Replace this:
scoreLabel = (TextView) findViewById(R.id.startLabel);
with this:
startLabel = (TextView) findViewById(R.id.startLabel);

How to hide part of layout when editText is selected

Is there a way how to hide some buttons when i click on EditText and keybord shows?
I have this layout
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/InnerRelativeLayout">
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1"
android:id="#+id/table">
<TableRow
android:id="#+id/tariffRow">
<TextView
android:layout_column="1"
android:text="Název"
android:padding="3dip" />
<EditText
android:id="#+id/tariffName"
android:gravity="right"
android:padding="3dip" />
</TableRow>
</TableLayout>
</ScrollView>
<LinearLayout android:id="#+id/InnerRelativeLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignParentBottom="true">
<Button android:id="#+id/okBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="Ok"/>
<Button android:id="#+id/stornoBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="Storno" />
</LinearLayout>
Now when the editText is clicked to type some value i need to hide that linearLayout android:id="#+id/InnerRelativeLayout" because otherwise it is still visible above the keyboard.
Need to set a FocusChangeListener to the EditText which triggers whenever focus changes on that EditText as follow:
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
// hide relative layout
} else {
// show relative layout
}
}
});
It is not actually that simple, here is my solution how I got it working.
First Need to create MyEditText.java
public class MyEditText extends EditText {
private KeyImeChange keyImeChangeListener;
public MyEditText(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
public void setKeyImeChangeListener(KeyImeChange keyImeChange){
keyImeChangeListener = keyImeChange;
}
public interface KeyImeChange {
public boolean onKeyIme(int keyCode, KeyEvent keyEvent);
}
#Override
public boolean onKeyPreIme (int keyCode, KeyEvent keyEvent){
if(keyImeChangeListener != null){
return keyImeChangeListener.onKeyIme(keyCode, keyEvent);
}
return false;
}
}
Then layout.xml, change following
<EditText
android:id="#+id/tariffName"
android:gravity="right"
android:padding="3dip" />
Into
<!-- change yourapp -->
<com.yourapp.MyEditText
android:id="#+id/tariffName"
android:gravity="right"
android:padding="3dip" />
Add also android:focusable="true" to your LinearLayout
<LinearLayout android:id="#+id/InnerRelativeLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignParentBottom="true"
android:focusable="true">
Then put into your activity like MainActivity.java,
import fi.hgs.apps.MyEditText.KeyImeChange;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
removeFocus();
MyEditText myEditText = (MyEditText) findViewById(R.id.tariffName);
myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus) {
showLinearLayout();
} else {
hideLinearLayout();
}
}
});
myEditText.setKeyImeChangeListener(new KeyImeChange() {
#Override
public boolean onKeyIme(int keyCode, KeyEvent event) {
if (KeyEvent.KEYCODE_BACK == event.getKeyCode()) {
removeFocus();
}
return false;
}
});
}
Add also these to do the actual job.
public void removeFocus() {
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.InnerRelativeLayout);
linearLayout.requestFocus();
}
public void showLinearLayout() {
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.InnerRelativeLayout);
linearLayout.setVisibility(View.VISIBLE);
}
public void hideLinearLayout() {
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.InnerRelativeLayout);
linearLayout.setVisibility(View.INVISIBLE);
}

Categories