I am making boxing countdown timer and to set how long round supposed to last I am using two button first "+" and second "-" my time add every 5 seconds ex "5,10,15,20,25..." but I always I have to click to add 5 second. I would like to hold button and my value will add automatically what should I do?
I hope I add every important information in my question
my code from buttons and display
public void dodawanie1(View view) {
iloscrund=iloscrund+1;
display(iloscrund);
public void odejmowanie1(View view) {
if(iloscrund>1){
iloscrund=iloscrund-1;
display(iloscrund);
}
}
private void display(int numer) {
TextView displayInteger=(TextView) findViewById(R.id.textView16);
displayInteger.setText("" + numer);
}
odejmowanie means decrease value
dodawanie means increase value
If you mean to determine between click and hold, use onTouchListener to determine hold button event.
onTouchListener
I think you should use Runnable and Handler class for do it.
this link should be useful.
Android: Implement a 1 second interval timer before calling a function
activity_auto_inc.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=".AutoIncActivity">
<TextView
android:id="#+id/num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:gravity="center"
android:text="1"
android:textSize="26sp"
android:textColor="#color/black"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/add"
android:text="add"
android:textColor="#color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/num" />
</androidx.constraintlayout.widget.ConstraintLayout>
AutoIncActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AutoIncActivity extends AppCompatActivity implements
View.OnLongClickListener, View.OnTouchListener {
Button add;
TextView txt;
boolean isAddPressed = false;
Handler handler;
final int TIME_INTERVAL = 100;
final int STEP = 1;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_inc);
handler = new Handler();
add = findViewById(R.id.add);
txt = findViewById(R.id.num);
add.setOnLongClickListener(this);
add.setOnTouchListener(this);
}
#Override
public boolean onLongClick(View view) {
if (view.getId() == R.id.add) {
isAddPressed = true;
handler.postDelayed(new AutoInc(), TIME_INTERVAL);
}
return false;
}
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_UP ||
motionEvent.getAction() == MotionEvent.ACTION_CANCEL) {
isAddPressed = false;
}
return false;
}
private class AutoInc implements Runnable {
#Override
public void run() {
if (isAddPressed) {
txt.setText(String.valueOf(Integer.parseInt(txt.getText().toString()) +
STEP));
handler.postDelayed(this, TIME_INTERVAL);
}
}
}
}
I have three tabs with an unique fragment. How by images:
3 tab and a fragment
First problem is that when I click on "I watch it" on a movie and swipe on Watched's tab, this tab isn't updated.
https://i.imgur.com/AnnN3Zq.png?1
https://i.imgur.com/DsLGn3r.png
After if I swipe/tap on Notify's tab and comeback on Watched's tab, the tab has been updated. Why? Where am I wrong?
CoreActivity.java
package com.example.msnma.movienotifier;
import android.annotation.TargetApi;
import android.app.FragmentTransaction;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.example.msnma.movienotifier.MoviesFragment;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TabHost;
import android.widget.Toast;
import com.example.msnma.movienotifier.adapter.MoviesAdapter;
import com.example.msnma.movienotifier.notify.NotificationReceiver;
import com.example.msnma.movienotifier.event.TwoPaneEvent;
import org.greenrobot.eventbus.EventBus;
import butterknife.BindView;
import static android.support.v4.view.PagerAdapter.POSITION_NONE;
import static com.google.common.reflect.Reflection.initialize;
import static java.security.AccessController.getContext;
public class CoreActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
SectionsPageAdapter mSectionsPageAdapter;
#BindView(R.id.movies)
ViewPager mViewPager;
#BindView(R.id.tabs)
TabLayout tabLayout;
boolean twoPane;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_core);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
if (findViewById(R.id.movie_detail) != null) {
twoPane = true;
}
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager(), twoPane);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setOffscreenPageLimit(1);
mViewPager.setAdapter(mSectionsPageAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.addOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(mViewPager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
final int numTab = tab.getPosition();
//Toast.makeText(getApplicationContext(),tab.getText(), Toast.LENGTH_LONG).show();
switch (tab.getPosition()) {
case 0: {
MoviesAdapter.setTipo(String.valueOf(MoviesFragment.Type.NOTIFY));
break;
}
case 1: {
MoviesAdapter.setTipo(String.valueOf(MoviesFragment.Type.SUGGESTED));
break;
}
case 2: {
MoviesAdapter.setTipo(String.valueOf(MoviesFragment.Type.WATCHED));
break;
}
}
}
});
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
//mViewPager.setCurrentItem(position);
// ci sono vicinissimo alla soluzione.
if(position == 0 || position == 2) {
Fragment getFragment = getSupportFragmentManager().getFragments().get(position);
if (getFragment instanceof MoviesFragment) {
MoviesFragment thisFragment = (MoviesFragment) getFragment;
thisFragment.onRefresh();
Log.i("REFRESH","Dovrebbe essere refreshato");
}
Log.i("PAGINASELEZIONATA", "Esegue onResume " + position);
}
//Toast.makeText(CoreActivity.this,"Tab "+position,Toast.LENGTH_LONG).show();
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
EventBus.getDefault().postSticky(new TwoPaneEvent(twoPane));
}
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_second, menu);
//MenuItem item = menu.findItem(R.id.search);
//searchView.setMenuItem(item);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
public void pressAccountButton(MenuItem item)
{
Intent intent = new Intent(this, AccountActivity.class);
startActivity(intent);
}
//nuovo codice
#Override
protected void onResume()
{
super.onResume();
if (!(mSectionsPageAdapter == null)) {
mSectionsPageAdapter.notifyDataSetChanged();
Log.i("INFOonResume", "Metodo onResume eseguito");
}
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
//Log.i("INFOTAB", "La tabella selezionata è "+tab.getTag());
onResume();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
Tap Notify's tap (believe also could tap on Suggested) and tap again Watched's tap
Second problem
In Watched's tab the textView are cut, why? How can I solve this?
MoviesAdapter.java
package com.example.msnma.movienotifier.adapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.example.msnma.movienotifier.MainActivity;
import com.example.msnma.movienotifier.MoviesFragment;
import com.example.msnma.movienotifier.R;
import com.example.msnma.movienotifier.database.MovieDatabase;
import com.example.msnma.movienotifier.databaseModel.MovieDBModel;
import com.example.msnma.movienotifier.model.Movie;
import java.util.Calendar;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Optional;
import static android.app.PendingIntent.getActivity;
import static com.example.msnma.movienotifier.MoviesFragment.*;
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.ViewHolder>{
private Context context;
private List<Movie> movies;
private View itemView;
private RecyclerView rv;
//per la data
private EditText fromDateEtxt;
private boolean active = false;
//private Context context;
private static String tipo = "NOTIFY";
public MoviesAdapter(Context context, List<Movie> movies) {
this.context = context;
this.movies = movies;
}
#Override
public MoviesAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView;
/*if(getTipo().equals("Suggested"))
{
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_movie, parent, false);
return new ViewHolder(itemView);
}
else if(getTipo().equals("Watched"))
{
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_movie_watched, parent, false);
return new ViewHolder(itemView);
}
else if(getTipo().equals("Notify"))
{*/
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_movie, parent, false);
return new ViewHolder(itemView);
//}
//return null;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
Movie movie = movies.get(position);
Glide.with(context)
.load(movie.getPosterUrl())
.placeholder(R.drawable.poster_placeholder)
.into(holder.posterView);
holder.title_movie.setText(movie.getTitle());
// prende solo la data + anno
String yourString = String.valueOf(movie.getReleaseDate());
String date = yourString.substring(0, 10);
String year = yourString.substring(yourString.length()-5,yourString.length());
holder.release_date.setText(date+year);
if(getTipo().equals("NOTIFY"))
{
Toast.makeText(context,"Notify", Toast.LENGTH_LONG).show();
holder.notifyButton.setVisibility(View.GONE);
holder.watchedButton.setVisibility(View.GONE);
holder.removeButton.setVisibility(View.VISIBLE);
}
//solo se è di tipo suggested
if(getTipo().equals("SUGGESTED"))
{
//disabilitare bottone remove
holder.removeButton.setVisibility(View.GONE);
holder.notifyButton.setVisibility(View.VISIBLE);
holder.watchedButton.setVisibility(View.VISIBLE);
Toast.makeText(context,"Suggested", Toast.LENGTH_LONG).show();
holder.notifyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*String testo = movies.get(position).getTitle().toString();
Toast tostato = Toast.makeText(context,testo,Toast.LENGTH_SHORT);
tostato.show();*/
alertFormElements(position);
}
});
holder.watchedButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*String testo = movies.get(position).getTitle()+ "\n" + "I WATCH IT";
Toast tostato = Toast.makeText(context,testo,Toast.LENGTH_SHORT);
tostato.show();*/
// public MovieDBModel(int id, String title, String overview, String posterUrl, String backdropUrl, String trailerUrl,
// Date releaseDate, float rating, boolean adult){
MovieDBModel mdm = new MovieDBModel(movies.get(position).getId(), movies.get(position).getTitle(), movies.get(position).getOverview(),
movies.get(position).getPosterUrl(), movies.get(position).getBackdropUrl(), movies.get(position).getTrailerUrl(),
movies.get(position).getReleaseDate(), movies.get(position).getRating(), movies.get(position).isAdult());
MovieDatabase.insertMovie(mdm, 2, MainActivity.getMovieDatabase());
String testo = "Added " + movies.get(position).getTitle() + "\n" + "in tab watched";
Toast tostato = Toast.makeText(context, testo, Toast.LENGTH_SHORT);
tostato.show();
}
});
}
if (getTipo().equals("WATCHED"))
{
holder.notifyButton.setVisibility(View.GONE);
holder.watchedButton.setVisibility(View.GONE);
holder.removeButton.setVisibility(View.VISIBLE);
holder.removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
//da implementare
}
});
Toast.makeText(context,"WATCHED", Toast.LENGTH_LONG).show();
}
}
//nuovo codice riguardo l'alerDialog
public final void alertFormElements(final int position)
{
/*
* Inflate the XML view. activity_main is in
* res/layout/form_elements.xml
*/
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.form_elements,
null, false);
// You have to list down your form elements
/*final CheckBox myCheckBox = (CheckBox) formElementsView
.findViewById(R.id.myCheckBox);*/
final RadioGroup genderRadioGroup = (RadioGroup) formElementsView
.findViewById(R.id.NotifyAlertRadioGroup);
//nuovo codice
genderRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
switch (checkedId)
{
case R.id.OneDayRadioButton:
actv(false);
break;
case R.id.ReleaseDayRadioButton:
actv(false);
break;
case R.id.OnRadioButton:
actv(true);
break;
}
}
});
//questo sarà sostituito con un calendario.
/*final EditText nameEditText = (EditText) formElementsView
.findViewById(R.id.nameEditText);*/
//parte data
fromDateEtxt = (EditText) formElementsView.findViewById(R.id.nameEditText);
fromDateEtxt.setEnabled(active);
fromDateEtxt.setClickable(active);
fromDateEtxt.setInputType(InputType.TYPE_NULL);
fromDateEtxt.requestFocus();
//metodo data
//setDateTimeField();
//fromDatePickerDialog.show();
fromDateEtxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar c = Calendar.getInstance();
DatePickerDialog dpd = new DatePickerDialog( context ,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
fromDateEtxt.setText(dayOfMonth + "-"
+ (monthOfYear + 1) + "-" + year);
}
},
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
dpd.show();
}
});
// the alert dialog
new AlertDialog.Builder(context).setView(formElementsView)
.setTitle(movies.get(position).getTitle()+" Notify")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#TargetApi(11)
public void onClick(DialogInterface dialog, int id) {
//fromDateEtxt.setText(dateFormatter.format(newDate.getTime()));
String toastString = "";
String titleMovie = movies.get(position).getTitle();
String releaseDate = String.valueOf(movies.get(position).getReleaseDate());
String date = releaseDate.substring(0, 10);
String year = releaseDate.substring(releaseDate.length()-5,releaseDate.length());
releaseDate = date+year;
toastString = toastString + titleMovie + "\n" + releaseDate +"\n";
/*
* Detecting whether the checkbox is checked or not.
*/
/*if (myCheckBox.isChecked()) {
toastString += "Happy is checked!\n";
} else {
toastString += "Happy IS NOT checked.\n";
}*/
/*
* Getting the value of selected RadioButton.
*/
// get selected radio button from radioGroup
int selectedId = genderRadioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
RadioButton selectedRadioButton = (RadioButton) formElementsView
.findViewById(selectedId);
if(selectedRadioButton.getId() == R.id.OnRadioButton)
{
toastString += "Selected radio button is: " + fromDateEtxt.getText();
}
else {
toastString += "Selected radio button is: "
+ selectedRadioButton.getText() + "!\n";
}
/*
* Getting the value of an EditText.
*/
/*toastString += "Name is: " + nameEditText.getText()
+ "!\n";*/
Toast toast = Toast.makeText(context, toastString, Toast.LENGTH_LONG);
toast.show();
dialog.cancel();
}
}).show();
}
//nuovo codice
/*#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_movie, null);
holder = new ViewHolder();
holder.title_movie = (TextView) convertView.findViewById(R.id.movie_title);
holder.release_date = (TextView) convertView
.findViewById(R.id.movie_release_date);
Movie row_pos = movies.get(position);
//holder.profile_pic.setImageResource(row_pos.getProfile_pic_id());
holder.title_movie.setText(row_pos.getTitle());
holder.release_date.setText((CharSequence) row_pos.getReleaseDate());
//holder.contactType.setText(row_pos.getContactType());
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}*/
#Override
public void onViewRecycled(ViewHolder holder) {
super.onViewRecycled(holder);
Glide.clear(holder.posterView);
}
#Override
public int getItemCount() {
return movies.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.poster)
public ImageView posterView;
#BindView(R.id.movie_title)
public TextView title_movie;
#BindView(R.id.movie_release_date)
public TextView release_date;
#BindView(R.id.editNotify)
public Button notifyButton;
#BindView(R.id.iWatchItMovie)
public Button watchedButton;
#BindView(R.id.remove)
public Button removeButton;
public ViewHolder(View v) {
super(v);
ButterKnife.bind(this, v);
}
}
//parte per attivare/disattivare l'editText
private void actv(final boolean active)
{
fromDateEtxt.setEnabled(active);
if (active)
{
fromDateEtxt.requestFocus();
}
}
public static void setTipo(String tipo) {
MoviesAdapter.tipo = tipo;
}
public static String getTipo() {
return tipo;
}
}
For first, you can try adding similar logic to onPageScrolled
Fragment getFragment = getSupportFragmentManager().getFragments().get(position);
if (getFragment instanceof MoviesFragment) {
MoviesFragment thisFragment = (MoviesFragment) getFragment;
if ((position == 0 || position == 2) && positionOffset == 0.0 && positionOffsetPixels == 0)
thisFragment.onRefresh();
}
OK, #user47845 for (This is my list_item_movie.xml) you can try changed to this and tell us how are you doing.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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="350px">
<android.support.constraint.ConstraintLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/card_background">
<ImageView
android:id="#+id/poster"
android:layout_width="120dp"
android:layout_height="139dp"
android:layout_marginEnd="10dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="10dp"
android:layout_marginStart="2dp"
android:contentDescription="TODO"
android:scaleType="centerCrop"
android:src="#drawable/poster_placeholder"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/movie_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:textSize="20dip"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/poster"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/movie_release_date"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="20dip"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/poster"
app:layout_constraintTop_toBottomOf="#+id/movie_title" />
<Button
android:id="#+id/editNotify"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:onClick="pressEditNotifyButton"
android:text="Notify"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/poster" />
<Button
android:id="#+id/iWatchItMovie"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:text="I watch it"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold"
app:layout_constraintEnd_toStartOf="#+id/remove"
app:layout_constraintStart_toEndOf="#+id/movie_title"
app:layout_constraintBottom_toBottomOf="parent" />
<Button
android:id="#+id/remove"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="21dp"
android:layout_marginRight="21dp"
android:background="#android:color/transparent"
android:text="Remove"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/iWatchItMovie" />
</android.support.constraint.ConstraintLayout>
</FrameLayout>
This is my list_item_movie.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="350px">
<!--android:layout_height="?android:attr/listPreferredItemHeight">-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:background="#drawable/card_background">
<ImageView
android:id="#+id/poster"
android:layout_width="185px"
android:layout_height="277px"
android:src="#drawable/poster_placeholder"
android:scaleType="centerCrop"
android:contentDescription="TODO" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center_vertical">
<TextView
android:id="#+id/movie_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textStyle="bold"
android:layout_gravity="left|center_vertical"
android:textSize="20dip"
android:layout_marginLeft="10dip"
/>
<TextView
android:id="#+id/movie_release_date"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="left|center_vertical"
android:textSize="20dip"
android:layout_marginLeft="10dip"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="bottom"
android:orientation="horizontal">
<Button
android:id="#+id/editNotify"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:onClick="pressEditNotifyButton"
android:text="Notify"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold" />
<Button
android:id="#+id/iWatchItMovie"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:text="I watch it"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold" />
<Button
android:id="#+id/remove"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:text="Remove"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</FrameLayout>
EDIT:
I have solved so:
<?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="350px">
<!--android:layout_height="?android:attr/listPreferredItemHeight">-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="2dp"
android:layout_marginTop="4dp"
android:layout_marginRight="2dp"
android:layout_marginBottom="4dp"
android:orientation="horizontal"
android:background="#drawable/card_background">
<ImageView
android:id="#+id/poster"
android:layout_width="185px"
android:layout_height="277px"
android:contentDescription="TODO"
android:scaleType="centerCrop"
android:src="#drawable/poster_placeholder" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/movie_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:layout_marginLeft="10dip"
android:layout_weight="1"
android:textSize="20dip"
android:textStyle="bold" />
<TextView
android:id="#+id/movie_release_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:layout_marginLeft="10dip"
android:layout_weight="1"
android:textSize="20dip" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="bottom"
android:orientation="horizontal">
<Button
android:id="#+id/editNotify"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:onClick="pressEditNotifyButton"
android:text="Notify"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold" />
<Button
android:id="#+id/iWatchItMovie"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:text="I watch it"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold" />
<Button
android:id="#+id/remove"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:text="Remove"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</FrameLayout>
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"
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.
Okay, this happened when I created a simple ImageButton. I don't see what I'm doing wrong though... Here's my code:
(My Activity.Xml File):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/tapbgh"
android:orientation="vertical" >
<TextView
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center"
android:text="#string/level01"
android:textColor="#FFFFFF" />
<TextView
android:id="#+id/Score"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center"
android:text="#string/click0"
android:textColor="#FFFFFF"
android:textSize="16pt" />
<Chronometer
android:id="#+id/Timer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center_horizontal"
android:text="01:00"
android:textColor="#FFFFFF" />
<Button
android:id="#+id/Tap"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.81"
android:background="#drawable/buttonbg" />
<Button
android:id="#+id/Menu"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Menu" />
<ImageButton
android:id="#+id/Reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/resetbtn"
android:src="#drawable/resetbtn" />
</LinearLayout>
(My .Java File):
package my.first.app;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.Button;
//Click Events Below This Line
public class Tap_Game_Activity extends Activity {
private Button tapBtn;
private Button rstBtn;
int scr = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Menu = (Button) findViewById(R.id.Menu);
registerForContextMenu(Menu);
tapBtn = (Button) findViewById(R.id.Tap);
rstBtn = (Button) findViewById(R.id.Reset);
rstBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
TextView Score = (TextView) findViewById(R.id.Score);
Score.setText("0");
scr = 0;
}
});
tapBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
scr = scr + 1;
TextView Score = (TextView) findViewById(R.id.Score);
Score.setText(String.valueOf(scr));
}
});
}
// Options Menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
menu.setHeaderTitle("Menu");
menu.add(0, view.getId(), 0, "Resume");
menu.add(0, view.getId(), 0, "Quit");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if(item.getTitle()=="Invoke Context Function 1") {
contextFunction1(item.getItemId());
}
else if(item.getTitle()=="Invoke Context Function 2") {
contextFunction2(item.getItemId());
}
else {
return false;
}
return true;
}
public void contextFunction1(int id){
Toast.makeText(this, "function 1 invoked!", Toast.LENGTH_SHORT).show();
}
public void contextFunction2(int id){
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Tap_Game_Activity.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
I feel like it may be in this line:
rstBtn = (Button) findViewById(R.id.Reset);
But I still don't understand, any help would be great, thank you.
API tells me, that we can't cast ImageButton to Button. Try to declare rstBtn as an ImageButton and adjust the cast.
rstBtn = (Button) findViewById(R.id.Reset);
You are casting ImageButton to Button when ImageButton does not inherit from Button.
http://developer.android.com/reference/android/widget/ImageButton.html
BTW: Please choose a title that better describes your problem and include every error messages you get in your question.
private ImageButton rstBtn;
....
rstBtn = (ImageButton) findViewById(R.id.Reset);
rstBtn.setOnClickListener(........