GestureDetector not working on new layout - java

I have created the standard gesture detector that changes a textview depending on the given gesture. All works fine when my XML contains only the relative layout and the text view I wish to change. However when I add a gird layout and a few icons the Gesture Detector no longer works, simply not changing the textview as it did before.
The code is;
<?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/Relative_Layout"
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:background="#drawable/homebackground"
tools:context="com.example.james.fitness.MainActivity"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true">
<GridLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/Grid1">
<TextView
android:id="#+id/someText"
android:text="sometext"
android:foregroundGravity="center_vertical|center_horizontal"
android:gravity="center_vertical|center"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleX="5"
android:scaleY="5"
android:textColor="#color/colorAccent" />
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
app:srcCompat="#drawable/fitnessbutton"
android:id="#+id/fitnessbutton"
android:layout_row="1"
android:layout_column="1"
android:layout_columnWeight="1"
android:layout_gravity="fill_horizontal"
android:gravity="center"
android:paddingBottom="100dp" />
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
app:srcCompat="#drawable/drinkbutton"
android:id="#+id/drinkbutton"
android:layout_column="2"
android:layout_row="1"
android:layout_columnWeight="1"
android:layout_gravity="fill_horizontal"
android:gravity="center"
android:paddingBottom="100dp" />
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
app:srcCompat="#drawable/foodbutton"
android:id="#+id/foodbutton"
android:layout_column="3"
android:layout_row="1"
android:layout_columnWeight="1"
android:layout_gravity="fill_horizontal"
android:gravity="center"
android:paddingBottom="100dp" />
</GridLayout>
</RelativeLayout>
And the Java
import android.app.Activity;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements
GestureDetector.OnGestureListener,
GestureDetector.OnDoubleTapListener {
private TextView someText;
private GestureDetectorCompat gestureDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
someText = (TextView)findViewById(R.id.someText);
this.gestureDetector = new GestureDetectorCompat(this, this);
gestureDetector.setOnDoubleTapListener(this);
}
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
someText.setText("SINGLETAP");
return true;
}
#Override
public boolean onDoubleTap(MotionEvent e) {
someText.setText("DOUBLETAP");
return true;
}
#Override
public boolean onDoubleTapEvent(MotionEvent e) {
someText.setText("DOUBLETAPEVENT");
return true;
}
#Override
public boolean onDown(MotionEvent e) {
someText.setText("DOWN");
return true;
}
#Override
public void onShowPress(MotionEvent e) {
someText.setText("PRESS");
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
someText.setText("SINGLETAPUP");
return true;
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
someText.setText("SCROLL");
return true;
}
#Override
public void onLongPress(MotionEvent e) {
someText.setText("LONGPRESS");
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
someText.setText("FLING");
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return false;
}
}
Note if I comment out the grid layout and the image views then the code works again changing the textview. I can only presume the gesture detector is now buried beneath the grid layout but aren't sure?

Try to remove this lines in your layout, they are useless in your case
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"

Related

Cannot see widgets in tab layout in android studio

I am facing the problem of cannot see widgets in tab layouts. I have created textview and button in Overview Fragment but I cannot see them when run code. Is it right to initialize textviews and buttons in oncreateview() of fragment which we don't want to transfer to another tab. I have searched a lot about my problem but cannot get any hint. Code is given below:
package com.example.progluattempt;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import com.google.android.material.tabs.TabItem;
import com.google.android.material.tabs.TabLayout;
public class GlucosePlotterTips extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_glucose_plotter_tips);
TabLayout Tablayout1 = findViewById(R.id.Tablayout1);
TabItem OverviewTab = findViewById(R.id.Overviewtab);
TabItem HistoryTab = findViewById(R.id.Historytab);
TabItem TipsTab = findViewById(R.id.Tipstab);
ViewPager Viewpager1 = findViewById(R.id.viewpagery1);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), Tablayout1.getTabCount());
Viewpager1.setAdapter(pagerAdapter);
Tablayout1.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Viewpager1.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
//PgeAdapter
package com.example.progluattempt;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
public class PagerAdapter extends FragmentPagerAdapter {
private int numoftabs;
public PagerAdapter(FragmentManager fm, int numoftabs){
super(fm);
this.numoftabs = numoftabs;
}
#NonNull
#Override
public Fragment getItem(int position) {
switch(position){
case 0:
return new OverviewFragment();
case 1:
return new HistoryFragment();
case 2:
return new TipsFragment();
default:
return null;
}
}
#Override
public int getCount() {
return numoftabs;
}
}
//Main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".GlucosePlotterTips">
<com.google.android.material.tabs.TabLayout
android:id="#+id/Tablayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.004">
<com.google.android.material.tabs.TabItem
android:id="#+id/Overviewtab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Overview" />
<com.google.android.material.tabs.TabItem
android:id="#+id/Historytab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="History" />
<com.google.android.material.tabs.TabItem
android:id="#+id/Tipstab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tips" />
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewpagery1"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
//fragmentOverview
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".OverviewFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="183dp"
android:orientation="vertical">
<TextView
android:id="#+id/textViewov2"
android:layout_width="match_parent"
android:layout_height="56dp"
android:text="#string/overview1"
android:textColor="#color/black"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textViewov3"
android:layout_width="match_parent"
android:layout_height="46dp"
android:text="TextView"
android:textColor="#color/black"
android:textSize="18sp" />
</LinearLayout>
<Button
android:id="#+id/buttonov2"
android:layout_width="277dp"
android:layout_height="93dp"
android:layout_gravity="center"
android:text="#string/planner"
android:textColor="#color/black"
android:textSize="24sp"
app:backgroundTint="#color/Yellow" />
//OverviewFragment
package com.example.progluattempt;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class OverviewFragment extends Fragment {
TextView Results, Condition;
Button Mybuttonov2;
public OverviewFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_overview, container, false);
Results = (TextView) view.findViewById(R.id.textViewov2);
Intent i =getActivity().getIntent();
String LatestReading=i.getStringExtra("TimeofReading");
Results.setText("Last Checked: " +LatestReading);
//type
Condition = (TextView) view.findViewById(R.id.textViewov3);
String TypeofDiab = i.getStringExtra("Concentration");
Condition.setText("" +TypeofDiab);
//Button
Mybuttonov2 = (Button) view.findViewById(R.id.buttonov2);
//to display conditon of user
if(Condition.getText() != null){
String num;
int numi=0;
num = Condition.getText().toString();
try{
numi = Integer.parseInt(num);
}catch(NumberFormatException ex){
}
if(numi <= 70){
System.out.println("Hypoglycemia");}
else if(numi >=70 & numi <= 140){
System.out.println("Fine");}
else if(numi>140 & numi <200){
System.out.println("Prediabetes");}
else {
System.out.println("Hyperglycemia");
}
}
//to add click event for button
Mybuttonov2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent i3 = new Intent(getActivity(), SensorScreen.class );
startActivity(i3);
}
});
return view;
}
}
Logcat
When run emulator

How to slide the main layout and force it to resize?

I want to create an text editor with options at the top (bold,..).
I also want to be able to hide those options; using the exact transition style shown in the picture below.
My problem is that the EditText that I use never has the intended behavious. (In the GIF below for exemple it does not resize after being moved).
I tried using animate (which is what is shown here on the picture).
I also tried with layout animation, combined with setVisibility(View.GONE) when the animation ends (its nearly perfect but for one frame between the two we can see what's happening).
I finally tried setting android:animateLayoutChanges="true". Which works great but I cannot animate the transition as I want.
I also tried combining the three in various ways, but never was successful.
Java:
public class MainActivity extends AppCompatActivity {
boolean optionVisible = true;
LinearLayout Main;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Main = findViewById(R.id.main);
}
public void show(View v) {
if (optionVisible) {
Main.animate().setDuration(300).translationYBy(-Options.getHeight());
} else {
Main.animate().setDuration(300).translationYBy(Options.getHeight());
}
optionVisible = !optionVisible;
}
}
XML:
<?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:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/options"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:fillAfter="true">
... Defining buttons and slider ...
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
... Defining Title EditText ...
</RelativeLayout>
<EditText
android:id="#+id/writter"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:gravity="top"
android:padding="0dp"
android:text="azertyuio"
android:textAlignment="gravity"
android:textColor="#color/text"
android:textSize="20sp"
tools:ignore="HardcodedText"
android:background="#null"
/>
</LinearLayout>
Well I finally managed to get it working properly. I still find the solution akward and would be glad to here another suggestion.
Anyway what I finally did was to use Animations (and not animate), and to have 2 main view basically being set GONE and VISIBLE at oppisite time depending on the presence of options or not.
Here is the code (I used an external class to synchronize the two EditText)
activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<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">
<LinearLayout
android:id="#+id/main_with_opt"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:visibility="gone">
<LinearLayout
android:id="#+id/options"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:fillAfter="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<Button
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/underline"/>
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<Button
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/italic"/>
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<Button
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/bold"/>
</FrameLayout>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/size"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="aA"
android:paddingHorizontal="10dp"
android:paddingVertical="5dp"
tools:ignore="HardcodedText"
android:layout_alignParentStart="true"/>
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toEndOf="#id/size"
android:layout_toStartOf="#+id/size_int"/>
<TextView
android:id="#+id/size_int"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/text_size"
android:paddingHorizontal="10dp"
android:paddingVertical="5dp"
tools:ignore="HardcodedText"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<EditText
android:id="#+id/title_with_opt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lines="1"
android:text="#string/title"
android:maxLines="1"
android:textColor="#color/title"
android:layout_marginStart="10dp"
android:layout_toStartOf="#+id/arrow_with_opt"/>
<ImageButton
style="#style/Widget.AppCompat.Button.Borderless"
android:id="#+id/arrow_with_opt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:src="#drawable/arrow_less"
android:onClick="show"/>
</RelativeLayout>
<com.example.mynotes.SyncEditText
android:id="#+id/typer_with_opt"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:gravity="top"
android:padding="0dp"
android:textAlignment="gravity"
android:textColor="#color/text"
android:textSize="20sp"
android:background="#null"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<EditText
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="1"
android:text="#string/title"
android:textColor="#color/title"
android:layout_marginStart="10dp"
android:layout_toStartOf="#+id/arrow"/>
<ImageButton
style="#style/Widget.AppCompat.Button.Borderless"
android:id="#+id/arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:src="#drawable/arrow_less"
android:onClick="show"/>
</RelativeLayout>
<com.example.mynotes.SyncEditText
android:id="#+id/typer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:gravity="top"
android:padding="0dp"
android:textAlignment="gravity"
android:textColor="#color/text"
android:textSize="20sp"
android:background="#null"
/>
</LinearLayout>
</FrameLayout>
Main Activity.java :
package com.example.mynotes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
LinearLayout Options;
boolean optionVisible = false;
LinearLayout Main;
LinearLayout Main_with_opt;
LayoutAnimationController show_lessAnimation;
LayoutAnimationController show_moreAnimation;
com.example.mynotes.SyncEditText Typer;
com.example.mynotes.SyncEditText Typer_with_opt;
int mSelection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Main_with_opt = findViewById(R.id.main_with_opt);
Options = findViewById(R.id.options);
Main = findViewById(R.id.main);
Typer = findViewById(R.id.typer);
Typer_with_opt = findViewById(R.id.typer_with_opt);
Typer.setDependencies(Typer_with_opt);
Typer_with_opt.setDependencies(Typer);
show_lessAnimation = AnimationUtils.loadLayoutAnimation(this, R.anim.show_less_layout);
show_moreAnimation = AnimationUtils.loadLayoutAnimation(this, R.anim.show_more_layout);
}
public void show(View v) {
if (optionVisible) {
Main_with_opt.setLayoutAnimationListener(show_lessAnimationListener);
Main_with_opt.setLayoutAnimation(show_lessAnimation);
Typer.requestFocus();
Typer.setSelection(Typer_with_opt.getSelectionStart());
Typer.scrollTo(Typer_with_opt.getScrollX(), Typer_with_opt.getScrollY());
Main_with_opt.startLayoutAnimation();
} else {
Main_with_opt.setLayoutAnimationListener(show_moreAnimationListener);
Main_with_opt.setLayoutAnimation(show_moreAnimation);
Main_with_opt.setVisibility(View.VISIBLE);
Typer_with_opt.requestFocus();
Typer_with_opt.setSelection(Typer.getSelectionStart());
Typer_with_opt.scrollTo(Typer.getScrollX(), Typer.getScrollY());
Main.setVisibility(View.GONE);
Main_with_opt.startLayoutAnimation();
}
optionVisible = !optionVisible;
}
Animation.AnimationListener show_lessAnimationListener = new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
Main.setVisibility(View.VISIBLE);
Main_with_opt.setVisibility(View.GONE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
};
Animation.AnimationListener show_moreAnimationListener = new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
};
}
And the cutom class :
SyncEditText.java :
package com.example.mynotes;
import android.content.Context;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
public class SyncEditText extends AppCompatEditText implements TextWatcher {
private SyncEditText[] mDependencies;
private boolean shouldSync = true;
public SyncEditText(Context context) {
super(context);
}
public SyncEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SyncEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// This is to avoid text changed event is called multiple time per character because auto suggestion
setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
addTextChangedListener(this);
}
private void addTextChangedListener(SyncEditText syncEditText) {
}
public void setDependencies(SyncEditText... dependencies) {
mDependencies = dependencies;
}
public void setText(CharSequence text, boolean syncDependencies) {
shouldSync = syncDependencies;
setText(text);
Log.d("Log", "Text sync: " + text);
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { }
#Override
public void afterTextChanged(Editable editable) { }
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (mDependencies == null)
return;
if (!shouldSync) {
// If this text is sync from other SyncEditText, ignore the change
shouldSync = true;
return;
}
Log.d("Log", "Text input: " + charSequence);
// Sync to all dependencies
for (SyncEditText syncEditText : mDependencies) {
syncEditText.setText(charSequence, false);
}
}
}

Android Gesture is not working for child in its parent

I am developing an application with accessing gesture of android. I am not able to swipe over the layout where some texts are visible,but able to swipe in blank spaces of activity.
my java code
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.tomcast.libin.anxiety.R;
import com.tomcast.libin.anxiety.models.Questions;
import com.tomcast.libin.anxiety.utils.OnSwipeTouchListener;
import com.tomcast.libin.anxiety.utils.SlideAnimationUtil;
import java.util.ArrayList;
public class DFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private ArrayList<Questions> questionlist = new ArrayList<Questions>();
private static int START_POSITION=0;
private static int FINAL_POSITION=6;
private static int CURRENT_POSTION =0;
ConstraintLayout llQuestion;
TextView question;
ImageView iconA;
ImageView iconB;
ImageView iconC ;
ImageView iconD;
float x1,y1,x2,y2,t1,t2;
`enter code here`int CLICK_DURATION = 10;
private OnFragmentInteractionListener mListener;
public DFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static Fragment newInstance(String param1, String param2) {
Fragment fragment = new Fragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.sliding_question_layout, container, false);
init( view);
return view ;
}
void init(final View view){
llQuestion=(ConstraintLayout) view.findViewById(R.id.constraintLayout);
iconA= view.findViewById(R.id.ic_option_a);
iconB= view.findViewById(R.id.ic_option_b);
iconC= view.findViewById(R.id.ic_option_c);
iconD= view.findViewById(R.id.ic_option_d);
Questions q0 = new Questions();
q0.setQuestion("Feeling Nervous ");
q0.setSelected_answer("");
questionlist.add(q0);
Questions q1= new Questions();
q1.setQuestion("Anixious,or on edge");
q1.setSelected_answer("");
questionlist.add(q1);
Questions q2= new Questions();
q2.setQuestion("Not being able to stop or control worrying");
q2.setSelected_answer("");
questionlist.add(q2);
Questions q3 = new Questions();
q3 .setQuestion("Worry to much about differnt things ?");
q3 .setSelected_answer("");
questionlist.add(q3 );
Questions q4= new Questions();
q4.setQuestion("Troble relaxing");
q4.setSelected_answer("");
questionlist.add(q4);
Questions q5= new Questions();
q5.setQuestion("Being so restless that it's hard to set still");
q5.setSelected_answer("");
questionlist.add(q5);
Questions q6= new Questions();
q6.setQuestion("Becoming easily annyed or irritable");
q6.setSelected_answer("");
questionlist.add(q6);
final TextView t= view.findViewById(R.id.question);
t.setText(questionlist.get(CURRENT_POSTION).getQuestion());
RelativeLayout rOptionA=(RelativeLayout) view.findViewById(R.id.rel_option_a);
RelativeLayout rOptionB=(RelativeLayout) view.findViewById(R.id.rel_option_b);
RelativeLayout rOptionC=(RelativeLayout) view.findViewById(R.id.rel_option_c);
RelativeLayout rOptionD=(RelativeLayout) view.findViewById(R.id.rel_option_d);
rOptionA.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// Interpret MotionEvent data
// Handle touch here
questionlist.get(CURRENT_POSTION).setSelected_answer("A");
iconA.setImageResource(R.drawable.ic_success);
iconB.setImageResource(R.drawable.ic_dot);
iconC.setImageResource(R.drawable.ic_dot);
iconD.setImageResource(R.drawable.ic_dot);
return false;
}
});
rOptionB.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// Interpret MotionEvent data
// Handle touch heresuper.onTouchEvent(event);
questionlist.get(CURRENT_POSTION).setSelected_answer("B");
iconA.setImageResource(R.drawable.ic_dot);
iconB.setImageResource(R.drawable.ic_success);
iconC.setImageResource(R.drawable.ic_dot);
iconD.setImageResource(R.drawable.ic_dot);
return true;
}
});
rOptionC.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// Interpret MotionEvent data
// Handle touch here
questionlist.get(CURRENT_POSTION).setSelected_answer("C");
iconA.setImageResource(R.drawable.ic_dot);
iconB.setImageResource(R.drawable.ic_dot);
iconC.setImageResource(R.drawable.ic_success);
iconD.setImageResource(R.drawable.ic_dot);
return true;
}
});
rOptionD.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
questionlist.get(CURRENT_POSTION).setSelected_answer("D");
iconA.setImageResource(R.drawable.ic_dot);
iconB.setImageResource(R.drawable.ic_dot);
iconC.setImageResource(R.drawable.ic_dot);
iconD.setImageResource(R.drawable.ic_success);
return true;
}
});
ConstraintLayout cl= view.findViewById(R.id.constraintLayout);
cl.setOnTouchListener(new OnSwipeTouchListener(getActivity()) {
#Override
public void onSwipeDown() {
}
#Override
public void onSwipeLeft() {
if(CURRENT_POSTION < FINAL_POSITION) {
CURRENT_POSTION = CURRENT_POSTION + 1;
iconA.setImageResource(R.drawable.ic_dot);
iconB.setImageResource(R.drawable.ic_dot);
iconC.setImageResource(R.drawable.ic_dot);
iconD.setImageResource(R.drawable.ic_dot);
Log.i("ggg", String.valueOf(CURRENT_POSTION));
question = view.findViewById(R.id.question);
question.setText(questionlist.get(CURRENT_POSTION).getQuestion());
if((questionlist.get(CURRENT_POSTION).getSelected_answer()).equals("")){
iconA.setImageResource(R.drawable.ic_dot);
iconB.setImageResource(R.drawable.ic_dot);
iconC.setImageResource(R.drawable.ic_dot);
iconD.setImageResource(R.drawable.ic_dot);
}
else{
Log.d("ELSE",( questionlist.get(CURRENT_POSTION).getSelected_answer()).toString());
if((questionlist.get(CURRENT_POSTION).getSelected_answer()).equals("A")){
iconA.setImageResource(R.drawable.ic_success);
}
if((questionlist.get(CURRENT_POSTION).getSelected_answer()).equals("B")){
iconB.setImageResource(R.drawable.ic_success);
} if((questionlist.get(CURRENT_POSTION).getSelected_answer()).equals("C")){
iconC.setImageResource(R.drawable.ic_success);
}
if((questionlist.get(CURRENT_POSTION).getSelected_answer()).equals("D")){
iconD.setImageResource(R.drawable.ic_success);
}
}
SlideAnimationUtil.slideInFromRight(getContext(),llQuestion);
} else{
}
}
#Override
public void onSwipeUp() {
}
#Override
public void onSwipeRight() {
if(CURRENT_POSTION >START_POSITION) {
CURRENT_POSTION = CURRENT_POSTION -1;
Log.i("ggg", String.valueOf(CURRENT_POSTION));
iconA.setImageResource(R.drawable.ic_dot);
iconB.setImageResource(R.drawable.ic_dot);
iconC.setImageResource(R.drawable.ic_dot);
iconD.setImageResource(R.drawable.ic_dot);
TextView t = view.findViewById(R.id.question);
t.setText(questionlist.get(CURRENT_POSTION).getQuestion());
if((questionlist.get(CURRENT_POSTION).getSelected_answer()).equals("")){
iconA.setImageResource(R.drawable.ic_dot);
iconB.setImageResource(R.drawable.ic_dot);
iconC.setImageResource(R.drawable.ic_dot);
iconD.setImageResource(R.drawable.ic_dot);
}
else{
Log.d("ELSE",( questionlist.get(CURRENT_POSTION).getSelected_answer()).toString());
if((questionlist.get(CURRENT_POSTION).getSelected_answer()).equals("A")){
iconA.setImageResource(R.drawable.ic_success);
}
if((questionlist.get(CURRENT_POSTION).getSelected_answer()).equals("B")){
iconB.setImageResource(R.drawable.ic_success);
} if((questionlist.get(CURRENT_POSTION).getSelected_answer()).equals("C")){
iconC.setImageResource(R.drawable.ic_success);
}
if((questionlist.get(CURRENT_POSTION).getSelected_answer()).equals("D")){
iconD.setImageResource(R.drawable.ic_success);
}
}
SlideAnimationUtil.slideInFromLeft(getContext(),llQuestion);
}
}
});
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
// mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
CURRENT_POSTION=0;
mListener = null;
}
}
My xml code
<?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">
<ImageView
android:id="#+id/imageView2"
android:layout_width="0dp"
android:layout_height="0dp"
android:scaleType="fitXY"
android:src="#drawable/three"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintVertical_bias="0.0" />
<android.support.constraint.ConstraintLayout
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginRight="0dp"
android:background="#d4ffffff"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="0dp"
app:layout_constraintTop_toTopOf="parent">
<android.support.constraint.ConstraintLayout
android:id="#+id/constraintLayout"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0">
<android.support.constraint.Guideline
android:id="#+id/guideline4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.25"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="152dp" />
<TextView
android:id="#+id/question"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:text="TextView"
android:textAlignment="center"
android:textColor="#color/colorPrimary"
android:textSize="35sp"
app:layout_constraintBottom_toTopOf="#+id/guideline4"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.25" />
<RelativeLayout
android:id="#+id/rel_option_a"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:background="#drawable/edge_rounded_border"
android:clickable="true"
android:padding="#dimen/option_relative_padding"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="#+id/guideline4">
<ImageView
android:id="#+id/ic_option_a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:tag="im_optA"
app:srcCompat="#drawable/ic_dot" />
<TextView
android:id="#+id/option_a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:layout_toEndOf="#+id/ic_option_a"
android:text="#string/option_a"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="17sp" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/rel_option_b"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="14dp"
android:background="#drawable/edge_rounded_border"
android:padding="#dimen/option_relative_padding"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/rel_option_a">
<TextView
android:id="#+id/option_b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:layout_toEndOf="#+id/ic_option_b"
android:text="#string/option_b"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="17sp" />
<ImageView
android:id="#+id/ic_option_b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:tag="im_optB"
app:srcCompat="#drawable/ic_dot" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/rel_option_c"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="14dp"
android:background="#drawable/edge_rounded_border"
android:padding="#dimen/option_relative_padding"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/rel_option_b">
<ImageView
android:id="#+id/ic_option_c"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:tag="im_optC"
app:srcCompat="#drawable/ic_dot" />
<TextView
android:id="#+id/option_c"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:layout_toEndOf="#+id/ic_option_c"
android:background="#drawable/edge_rounded"
android:text="#string/option_c"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="17sp" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/rel_option_d"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:background="#drawable/edge_rounded_border"
android:padding="#dimen/option_relative_padding"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/rel_option_c">
<ImageView
android:id="#+id/ic_option_d"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:tag="im_optD"
app:srcCompat="#drawable/ic_dot" />
<TextView
android:id="#+id/option_d"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:layout_toEndOf="#+id/ic_option_d"
android:background="#drawable/edge_rounded"
android:text="#string/option_d"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="17sp" />
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>
Above is my full code of fragment.I need to swipe without selecting the layer.how can I code.this image show the selection of particular layer,I am not able to swipe over this layer without selection.

Why is my text aligned to the left?

I'm new to Android developing, and I just couldn't fix this problem. When I build this app, my initial text is centered, but when I click the button or long click it, the response text is left aligned. And also, double tap, scrolling and flinging gestures don't work at all. What can be the reason?
MainActivity.java:
package com.revolise.gesturehandling;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.view.View;
import android.view.MotionEvent;
import android.view.GestureDetector;
import android.support.v4.view.GestureDetectorCompat;
public class MainActivity extends AppCompatActivity implements
GestureDetector.OnGestureListener,GestureDetector.OnDoubleTapListener
{
private Button button1;
private GestureDetectorCompat gestureDetect;
private TextView txt1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button)findViewById(R.id.button1);
txt1 = (TextView)findViewById(R.id.textView1);
this.gestureDetect = new GestureDetectorCompat(this, this);
gestureDetect.setOnDoubleTapListener(this);
button1.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
txt1.setText("clicked to the button whooaoaaa");
}
}
);
button1.setOnLongClickListener(
new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
txt1.setText("long clicked to the button woww");
return false;
}
}
);
}
#Override
public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
return true;
}
#Override
public boolean onDoubleTap(MotionEvent motionEvent) {
txt1.setText("Hey, you double tapped");
return true;
}
#Override
public boolean onDoubleTapEvent(MotionEvent motionEvent) {
txt1.setText("Aaaand now you're swiping.");
return true;
}
#Override
public boolean onDown(MotionEvent motionEvent) {
return true;
}
#Override
public void onShowPress(MotionEvent motionEvent) {
}
#Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
return true;
}
#Override
public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
txt1.setText("Scrolling weee");
return true;
}
#Override
public void onLongPress(MotionEvent motionEvent) {
txt1.setText("Long pressed");
}
#Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
txt1.setText("Whoaa flinginggg");
return true;
}
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.revolise.gesturehandling.MainActivity">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="160dp"
android:text="#string/initial_text"
android:textSize="30sp"
app:layout_constraintBottom_toTopOf="#+id/button1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="100dp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_text"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.501"
android:layout_marginBottom="200dp" />
</android.support.constraint.ConstraintLayout>
For first problem (wrong text aligned)
You should set your TextView width as match_parent and gravity to center_horizontal. So your code should be something like this:
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="160dp"
android:text="#string/initial_text"
android:textSize="30sp"
android:layout_gravity="center_horizontal"
app:layout_constraintBottom_toTopOf="#+id/button1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="100dp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp" />

listView won't populate from bottom

I'm making a chat activity for a school project and I want the newest messages at the bottom of the listView. Adding the code below does not work. I simply want the newest message to appear at the bottom and make the listView automatically scroll to the last list item. Thanks in advance!
android:transcriptMode="alwaysScroll"
android:stackFromBottom="true"
Link to image of current situation
XML:
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#1a1a1a"
android:id="#+id/relativeLayout_Messages"
android:layout_below="#id/my_toolbar"
android:layout_alignBottom="#+id/imageView_Separator">
<ListView
android:id="#+id/listView_Messages"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stackFromBottom="true"
/>
</RelativeLayout>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/imageView_Separator"
android:background="#1a1a1a"
android:src="#drawable/seperator"
android:layout_above="#+id/relativeLayout_ChatInput"
/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:id="#+id/relativeLayout_ChatInput"
android:background="#1a1a1a">
<EditText
android:layout_width="wrap_content"
android:layout_height="50dp"
android:id="#+id/editText_ChatInput"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="5dp"
android:background="#drawable/search_field"
android:layout_toStartOf="#+id/imageButton_Send"
android:layout_alignBottom="#+id/imageButton_Send"
android:inputType="textPersonName"
android:hint="#string/chat_field_hint"
android:textColor="#f4f5f6"
android:textColorHint="#f4f5f6"/>
<ImageButton
android:layout_width="32dp"
android:layout_height="32dp"
android:id="#+id/imageButton_Send"
android:background="#android:color/transparent"
android:src="#drawable/send_button"
android:scaleType="fitCenter"
android:layout_marginTop="10dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="6dp"
android:layout_marginBottom="8dp"
android:layout_alignParentEnd="true"
android:onClick="sendButtonClicked"
/>
</RelativeLayout>
</RelativeLayout>
JAVA
package com.example.muhryn.resonatem;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.content.Context;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import java.util.*;
public class ChatActivity extends AppCompatActivity{
public void hideKeyboard() {
try {
InputMethodManager imm=(InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
} catch (Exception ex) { }
}
private ListView chatListView;
private Button submitButton;
private EditText chatEditText;
private Chat chat;
private ArrayList receivedList=new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
chatListView=(ListView)findViewById(R.id.listView_Messages);
chatEditText=(EditText)findViewById(R.id.editText_ChatInput);
chat=new Chat("A","Resonate");
chat.setListener(new Chat.Listener(){
public void received(final String received) {
System.out.println("Received: "+received);
runOnUiThread(new Runnable() {
public void run() {
hideKeyboard();
receivedList.add(0, received);
chatListView.setAdapter(new ChatList(ChatActivity.this, receivedList));
}
});
//////((ArrayAdapter)chatListView.getAdapter()).insert(received,0);
}
});
}
public void sendButtonClicked(View view){
String textToSubmit=chatEditText.getText().toString().trim();
if(textToSubmit.isEmpty())
return;
if(chat.submitted(textToSubmit)) {
receivedList.add(0,"Sent: "+textToSubmit);
chatListView.setAdapter(new ChatList(ChatActivity.this, receivedList));
} else
Toast.makeText(this,"Failed to submit "+textToSubmit+".",Toast.LENGTH_SHORT).show();
}
#Override
public void onStop () {
super.onStop();
chat.stop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.chat_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.view_profile:
finish();
return true;
case R.id.report_match:
finish();
return true;
case R.id.add_match:
finish();
return true;
case R.id.unmatch:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Try the below code.
chatListView.smoothScrollByOffset(receivedList.size()-1);
It will scroll down to latest chat.

Categories

Resources