Refresh/update listview current tab - java

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>

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 can I select one Radio Button in adapter class without Radio Group

RecyclerView Adapter Class
package com.ajitapp.smartwork.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.ajitapp.smartwork.ChooseAddressActivity;
import com.ajitapp.smartwork.Interfaces.AddressClickListener;
import com.ajitapp.smartwork.Interfaces.CartClickListListener;
import com.ajitapp.smartwork.R;
import com.ajitapp.smartwork.models.AddressModal;
import com.ajitapp.smartwork.models.CartModel;
import java.util.List;
public class AddressListAdapter extends RecyclerView.Adapter<AddressListAdapter.MyViewHolder> {
private List<AddressModal> arrayList;
private Context context;
private AddressClickListener cartClickListListener;
public int mSelectedItem = -1;
private RadioButton lastCheckedRB = null;
public AddressListAdapter(Context applicationContext, List<AddressModal> arrayList, ChooseAddressActivity cartClickListListener) {
this.arrayList = arrayList;
this.context = applicationContext;
this.cartClickListListener = cartClickListListener;
}
#NonNull
#Override
public AddressListAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.choose_address_row_item, parent, false);
context = parent.getContext(); //to get the activity context use this line.
final AddressListAdapter.MyViewHolder myViewHolder = new AddressListAdapter.MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull AddressListAdapter.MyViewHolder holder, final int position) {
holder.addr1.setText(arrayList.get(position).getAddr1());
holder.addr2.setText(arrayList.get(position).getAddr2());
holder.city.setText(arrayList.get(position).getCity());
holder.state.setText(arrayList.get(position).getCity());
holder.country.setText(arrayList.get(position).getCountry());
holder.postalCode.setText(arrayList.get(position).getPostalCode());
holder.radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mSelectedItem=position;
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView addr1, addr2, city, state, country, postalCode;
private TextView subtask_description_tv;
private TextView subtask_price_tv;
private Button incrementBtn, decrementBtn;
private TextView display_data;
private TextView total_price_tv;
private RadioButton radioButton;
int total_price;
public MyViewHolder(#NonNull final View itemView) {
super(itemView);
addr1 = itemView.findViewById(R.id.addr1);
addr2 = itemView.findViewById(R.id.addr2);
city = itemView.findViewById(R.id.city);
state = itemView.findViewById(R.id.state);
country = itemView.findViewById(R.id.country);
postalCode = itemView.findViewById(R.id.postalCode);
radioButton = itemView.findViewById(R.id.addressRadioButton);
}
}
}
Item Row
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/toolbar_address_list"
android:padding="5dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
app:navigationIcon="#drawable/ic_arrow_back"
android:background="#color/colorPrimary"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose an address"
android:textStyle="bold"
android:textColor="#color/white"
android:textSize="20sp"
/>
</androidx.appcompat.widget.Toolbar>
<ImageView
android:id="#+id/locationImage"
android:layout_width="match_parent"
android:layout_height="150dp"
android:src="#drawable/address"
android:layout_marginTop="20dp"
android:layout_below="#+id/toolbar_address_list"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_add"
android:id="#+id/add_address"
android:text="Add new address"
android:layout_below="#id/locationImage"
android:layout_marginBottom="10dp"
android:layout_marginTop="20dp"
android:layout_marginLeft="10dp"
android:drawablePadding="5dp"
android:textSize="18sp"
android:textStyle="bold"
/>
<androidx.recyclerview.widget.RecyclerView
android:layout_marginLeft="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_below="#+id/add_address"
android:id="#+id/address_list" />
<Button
android:id="#+id/buy_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:text="Continue"
android:drawableRight="#drawable/ic_arrow_forward"
android:background="#color/colorPrimary"
android:textColor="#color/white"
android:textSize="20sp"
android:layout_marginBottom="10dp"
android:layout_marginTop="30dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:elevation="10dp"
android:layout_alignParentBottom="true"
/>
</RelativeLayout>
I want to click one Radio Button in Recycler View, but I failed to do that. I have tried all the possibilities, but I failed to try from everywhere. I want to click one Radio Button in Recycler View, but I failed to do that. I have tried all the possibilities, but I failed to try from everywhere.
First you need condition like this for your UI in your onBindViewHolder method
if (mSelectedItem == position) {
holder.radioButton.setChecked(true);
} else {
holder.radioButton.setChecked(false);
}
Then change your radio button listener like this
holder.radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mSelectedItem = position;
} else {
mSelectedItem = -1;
}
notifyDataSetChanged();
}
});
try this i hope your problem will solve.

Creating Flashcards in Android using Fragments

I am trying to make a simple flash card program where the user selects if they want a addition, subtraction, or multiplication problem and then use a separate fragment to show the flash card. When I run the program it doesn't seem to make it to the first fragment as it just keeps loading in the emulator. What am I doing wrong?
Main Activity
package com.example.johnt.hw4;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainAvtivity";
private SectionsStatePageAdapter mSectionStatePagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: Started.");
mSectionStatePagerAdapter = new SectionsStatePageAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById( R.id.list_fragment_port );
// setup the page
setupViewPager(mViewPager);
setViewPager(0);
/*
if (findViewById( R.id.list_fragment_port ) != null ) {
// create the fragment
ListFragment listFragment = new ListFragment();
// replace anything that was there before
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// replace any existing fragment
transaction.add( R.id.list_fragment_port, listFragment );
transaction.commit();
}
*/
}
private void setupViewPager(ViewPager viewPager) {
SectionsStatePageAdapter adapter = new SectionsStatePageAdapter(getSupportFragmentManager());
adapter.addFragment(new ListFragment(), "ListFragment");
adapter.addFragment(new DataFragment(), "DataFragment");
viewPager.setAdapter(adapter);
}
public void setViewPager(int fragmentNumber) {
mViewPager.setCurrentItem(fragmentNumber);
}
public void onListFragmentInteraction(int operatorIndex) {
//create a new data fragment with appropriate information
DataFragment dataFragment = DataFragment.newInstance( operatorIndex );
// replace anything that was there before
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// replace any existing fragment
transaction.replace( R.id.list_fragment_port, dataFragment );
// activate the back button
transaction.addToBackStack(null);
transaction.commit();
}
}
SectionStatePageAdapter
package com.example.johnt.hw4;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class SectionsStatePageAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public SectionsStatePageAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
}
ListFragment
package com.example.johnt.hw4;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class ListFragment extends Fragment {
private static final String TAG = "ListFragment";
//private OnListFragmentInteractionListener mListener;
public final static int OPERATOR_ADDITION = 1;
public final static int OPERATOR_SUBTRACTION = 2;
public final static int OPERATOR_MULTIPLICATION = 3;
private Button addition;
private Button subtraction;
private Button multiplication;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View listfrag = inflater.inflate(R.layout.fragment_list, container, false);
// deal with the buttons
addition = (Button) listfrag.findViewById( R.id.btn_addition );
subtraction = (Button) listfrag.findViewById( R.id.btn_subtraction );
multiplication = (Button) listfrag.findViewById( R.id.btn_multiplication );
addition.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onButtonPressed( OPERATOR_ADDITION );
}
});
subtraction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onButtonPressed( OPERATOR_SUBTRACTION );
}
});
multiplication.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onButtonPressed( OPERATOR_MULTIPLICATION );
}
});
return listfrag;
}
public void onButtonPressed( int operatorIndex ) {
((MainActivity)getActivity()).setViewPager(1);
//mListener.onListFragmentInteraction( operatorIndex );
}
/*
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnListFragmentInteractionListener {
void onListFragmentInteraction( int operatorIndex );
}
*/
}
DataFragment
package com.example.johnt.hw4;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.Random;
public class DataFragment extends Fragment {
private static final String TAG = "DataFragment";
private static final String ARGS_OPERATOR = "operatorIndex";
private int operatorIndex = 1;
public static DataFragment newInstance(int operatorIndex) {
DataFragment fragment = new DataFragment();
Bundle args = new Bundle();
args.putInt(ARGS_OPERATOR, operatorIndex);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflate the layout for this fragment
View datafrag = inflater.inflate(R.layout.fragment_data, container, false);
// get a link to the textview
TextView num1 = (TextView) datafrag.findViewById( R.id.tv_num1 );
TextView num2 = (TextView) datafrag.findViewById( R.id.tv_num2 );
TextView num3 = (TextView) datafrag.findViewById( R.id.tv_num3 );
TextView operator = (TextView) datafrag.findViewById( R.id.tv_operator );
Random r = new Random();
switch ( operatorIndex ) {
case ListFragment.OPERATOR_ADDITION:
int x = r.nextInt(100); // 0 - 99
int y = r.nextInt(100); // 0 - 99
int z = x + y;
num1.setText("" + x);
num2.setText(""+y);
num3.setText(""+z);
operator.setText("+");
break;
case ListFragment.OPERATOR_SUBTRACTION:
int a = r.nextInt(100); // 0 - 99
int b = r.nextInt(100 - a + 1) + a; // a - 99
int c = a - b;
num1.setText(a);
num2.setText(b);
num3.setText(c);
operator.setText("-");
break;
case ListFragment.OPERATOR_MULTIPLICATION:
int v = r.nextInt(100); // 0 - 99
int m = r.nextInt(100); // 0 - 99
int n = v * m;
num1.setText(v);
num2.setText(m);
num3.setText(n);
operator.setText("X");
break;
}
return datafrag;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/list_fragment_port"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</android.support.constraint.ConstraintLayout>
fragment_list.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<Button
android:id="#+id/btn_addition"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Addition"
android:textSize="25sp"
app:layout_constraintBottom_toTopOf="#+id/btn_subtraction"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btn_subtraction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/btn_multiplication"
android:layout_alignParentTop="true"
android:text="Subtraction"
android:textSize="25sp"
app:layout_constraintBottom_toTopOf="#+id/btn_multiplication"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btn_addition" />
<Button
android:id="#+id/btn_multiplication"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Multiplication"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btn_subtraction" />
</android.support.constraint.ConstraintLayout>
fragment_data.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
android:id="#+id/tv_num1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="num1"
android:textSize="25sp"
app:layout_constraintBottom_toTopOf="#+id/tv_operator"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tv_num2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="num2"
android:textSize="25sp"
app:layout_constraintBottom_toTopOf="#+id/tv_equals"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tv_operator" />
<TextView
android:id="#+id/tv_num3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="num3"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tv_equals" />
<TextView
android:id="#+id/tv_operator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="operator"
android:textSize="25sp"
app:layout_constraintBottom_toTopOf="#+id/tv_num2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tv_num1" />
<TextView
android:id="#+id/tv_equals"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="="
android:textSize="25sp"
app:layout_constraintBottom_toTopOf="#+id/tv_num3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tv_num2" />
</android.support.constraint.ConstraintLayout>

App seems like launching more than once in landscape mode after splash screen?

I have a splash screen and after that my main activity starts. This works fine in portrait mode but if in case i tilt my phone in landscape mode, the main activity can be seen launching more than once after splash screen.
I tried using android:launchMode="singleInstance" but in that case i am not able to attach files in feedback alert-box.
Following is my code:
MainActivity.java
package com.example.android.tel;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
TextView toolbar_title_mainActivity, main_textView, disclaimer_txtView;
CardView SearchDept, SearchName, disclaimer, feedback;
ImageView back;
ArrayList<Uri> arrayUri = new ArrayList<Uri>();
ArrayAdapter<Uri> myFileListAdapter;
ListView listViewFiles;
Dialog alertDialog;
final int RQS_LOADIMAGE = 0;
final int RQS_SENDEMAIL = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_main);
} else {
setContentView(R.layout.activity_main);
}
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar_main_activity);
toolbar_title_mainActivity = (TextView) findViewById(R.id.toolbar_title);
main_textView = (TextView) findViewById(R.id.main_textView);
main_textView.setPaintFlags(main_textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
setSupportActionBar(mActionBarToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar_title_mainActivity.setText("Hry. Govt. Telephone Directory");
back = (ImageView) findViewById(R.id.back);
back.setVisibility(View.INVISIBLE);
disclaimer = (CardView) findViewById(R.id.disclaimer);
feedback = (CardView) findViewById(R.id.feedback);
SearchDept = (CardView) findViewById(R.id.cardView1_mainActivity);
SearchName = (CardView) findViewById(R.id.cardView2_mainActivity);
SearchDept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, CardViewActivity.class);
startActivity(i);
}
});
SearchName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent j = new Intent(MainActivity.this, ByNameListActivity.class);
startActivity(j);
}
});
disclaimer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dialog alertDialog = new Dialog(MainActivity.this);
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.setContentView(R.layout.disclaimer);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
alertDialog.show();
}
});
feedback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog = new Dialog(MainActivity.this);
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.setContentView(R.layout.feedback);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
alertDialog.setCanceledOnTouchOutside(true);
ImageView send_btn=(ImageView)alertDialog.findViewById(R.id.send);
ImageView attach_btn=(ImageView)alertDialog.findViewById(R.id.attachment);
final TextView to_email_add=(TextView)alertDialog.findViewById(R.id.email_address);
to_email_add.setText("tel#gmail.com");
final EditText email_subject=(EditText)alertDialog.findViewById(R.id.email_subject);
final EditText email_text=(EditText)alertDialog.findViewById(R.id.email_text);
final EditText mobile_no=(EditText)alertDialog.findViewById(R.id.mobile_text);
email_subject.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
email_text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
myFileListAdapter = new ArrayAdapter<Uri>(
MainActivity.this,
android.R.layout.simple_list_item_1,
arrayUri);
listViewFiles = (ListView)alertDialog.findViewById(R.id.filelist);
listViewFiles.setAdapter(myFileListAdapter);
listViewFiles.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
myFileListAdapter.remove(arrayUri.get(position));
myFileListAdapter.notifyDataSetChanged();
Toast.makeText(view.getContext(), "You unattached one item", Toast.LENGTH_LONG).show();
return false;
}
});
attach_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_LOADIMAGE);
}
});
send_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email_add=to_email_add.getText().toString();
String email_sub=email_subject.getText().toString();
String email_txt=email_text.getText().toString();
String emailAddressList[] = {email_add};
String mobileNo=mobile_no.getText().toString();
String info=email_txt+"\n\nPhone Number :"+mobileNo;
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_EMAIL, emailAddressList);
intent.putExtra(Intent.EXTRA_SUBJECT, email_sub);
intent.putExtra(Intent.EXTRA_TEXT,info);
if(arrayUri.isEmpty()&& isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email without photo attached
intent.setAction(Intent.ACTION_SEND);
intent.setType("plain/text");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}else if(arrayUri.size() == 1 && isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email with ONE photo attached
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, arrayUri.get(0));
intent.setType("image/*");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}else if(arrayUri.size()>1&& isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email with MULTI photo attached
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, arrayUri);
intent.setType("image/*");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}
else {
Toast.makeText(v.getContext(), "Phone number is not valid", Toast.LENGTH_LONG).show();
}
startActivity(Intent.createChooser(intent, "Please provide valid details"));
}
});
alertDialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
switch(requestCode){
case RQS_LOADIMAGE:
Uri imageUri = data.getData();
arrayUri.add(imageUri);
myFileListAdapter.notifyDataSetChanged();
break;
case RQS_SENDEMAIL:
break;
}
}
}
public static boolean isValidPhone(String phone)
{
String expression = "^([0-9\\+]|\\(\\d{1,3}\\))[0-9\\-\\. ]{3,15}$";
CharSequence inputString = phone;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputString);
if (matcher.matches())
{
return true;
}
else{
return false;
}
}
public void hideKeyboard(View view) {
InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation;
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
// or = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}else {
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
// Add code if needed
// listViewFiles.setAdapter(myFileListAdapter);
// myFileListAdapter.notifyDataSetChanged();
setRequestedOrientation(orientation);
}
}
activity_main.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"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:weightSum="14"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
tools:context="com.example.android.tel.MainActivity">
<include
android:id="#+id/tool_bar_main_activity"
layout="#layout/toolbar">
</include>
<TextView
android:id="#+id/main_textView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:layout_marginTop="10dp"
android:text="How would you like to search?"
android:textStyle="bold"
android:textSize="14sp"
android:textColor="#1A237E"
android:gravity="center_horizontal"/>
<RelativeLayout
android:id="#+id/searchby_btns"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="4"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:gravity="center_vertical">
<android.support.v7.widget.CardView
android:id="#+id/cardView1_mainActivity"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
card_view:cardCornerRadius="4dp"
android:layout_marginTop="10dp"
card_view:cardBackgroundColor="#e97c1d">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search By Department.."
android:textColor="#android:color/white"
android:textStyle="bold"
android:textSize="18sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/cardView2_mainActivity"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_below="#id/cardView1_mainActivity"
card_view:cardCornerRadius="4dp"
android:layout_marginTop="20dp"
card_view:cardBackgroundColor="#e97c1d">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search By Name.."
android:textColor="#android:color/white"
android:textStyle="bold"
android:textSize="18sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight="8.5">
<ImageView
android:id="#+id/map_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/hry_map"
android:elevation="4dp"
android:layout_gravity="center"/>
</RelativeLayout>
<RelativeLayout
android:layout_below="#id/map_image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:paddingRight="16dp"
android:paddingLeft="16dp"
android:layout_marginTop="2dp"
android:gravity="center_horizontal"
android:layout_alignParentBottom="true">
<android.support.v7.widget.CardView
android:id="#+id/disclaimer"
android:layout_width="150dp"
android:layout_height="30dp"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp"
android:layout_marginRight="8dp"
card_view:cardBackgroundColor="#424242">
<TextView
android:layout_width="150dp"
android:layout_height="30dp"
android:text="Disclaimer"
android:gravity="center"
android:layout_gravity="center_vertical"
android:textColor="#FFFFFF"
android:textStyle="bold"/>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/feedback"
android:layout_toRightOf="#id/disclaimer"
android:layout_width="150dp"
android:layout_height="30dp"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp"
card_view:cardBackgroundColor="#424242">
<TextView
android:layout_width="150dp"
android:layout_height="30dp"
android:text="Feedback"
android:gravity="center"
android:layout_gravity="center_vertical"
android:textColor="#FFFFFF"
android:textStyle="bold"/>
</android.support.v7.widget.CardView>
</RelativeLayout>
</LinearLayout>
SplashScreenActivity.java
package com.example.android.telephonedirectory;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ProgressBar;
import com.felipecsl.gifimageview.library.GifImageView;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
public class SplashScreenActivity extends AppCompatActivity {
// private GifImageView gifimageview;
private ProgressBar progressBarSplashScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_splash_screen);
} else {
setContentView(R.layout.activity_splash_screen);
}
// gifimageview=(GifImageView)findViewById(R.id.gifSplashscreenImage);
progressBarSplashScreen=(ProgressBar)findViewById(R.id.progressbarSplashscreen);
progressBarSplashScreen.setVisibility(progressBarSplashScreen.VISIBLE);
//set GifImageView Resource
/*try {
InputStream inputStream=getAssets().open("splash_Screen.png");
byte[] bytes= IOUtils.toByteArray(inputStream);
gifimageview.setBytes(bytes);
gifimageview.startAnimation();
}catch (IOException ex){
}*/
//Wait for 4 seconds and start activity main
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
SplashScreenActivity.this.startActivity(new Intent(SplashScreenActivity.this,MainActivity.class));
SplashScreenActivity.this.finish();
}
},2000);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation;
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
// or = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}else {
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
// Add code if needed
// listViewFiles.setAdapter(myFileListAdapter);
// myFileListAdapter.notifyDataSetChanged();
setRequestedOrientation(orientation);
}
}
Dont use android:launchMode="singleInstance"
Launch mode you should use "singleTask" for this .
Because singleInstance creates separate task stack for Activity and do not check activity in current Task Stack.
while "singleTask" check each time if an Activity exist in Task Stack it can not create new one.

Adding a remove button in my item list

I am fairly new to Java and Android development. I am currently creating a shopping app and was looking at adding a "Remove" button to my Shopping Cart list.
Here is my current code for my list activity for my shopping cart, I am not really sure where to begin and some guidance would be greatly appreciated.
Thanks
package .shopper;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
public class CartListActivity extends ListActivity {
public class ProductListAdapter extends BaseAdapter {
private final Context context;
private List<Product> itemList;
public List<Product> getItemList() {
return itemList;
}
public void setItemList(List<Product> itemList) {
this.itemList = itemList;
}
public Context getContext() {
return context;
}
public ProductListAdapter(Context c) {
context = c;
}
#Override
public int getCount() {
if(itemList == null) return 0;
else return itemList.size();
}
#Override
public Object getItem(int position) {
if (itemList == null) return null;
else return itemList.get(position);
}
#Override
public long getItemId(int position) {
if (itemList == null) return 0;
else return itemList.get(position).hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View cell = convertView;
if (cell == null) {
// get layout from mobile xml
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
cell = inflater.inflate(R.layout.adapter_product_list, parent, false);
}
Product p = itemList.get(position);
//set value into textview according to position
TextView textView = (TextView) cell.findViewById(R.id.product_title);
textView.setText(p.getProductName());
// add £ symbol
textView = (TextView) cell.findViewById(R.id.product_info);
textView.setText("Price: " + "£"+ p.getPrice());
//set value into imageview according to position
ImageView imgView = (ImageView) cell.findViewById(R.id.product_image);
// clear the image
imgView.setImageDrawable(null);
//and load from the network
p.loadImage(imgView, 54, 54);
return cell;
}
}
public static final Integer[] productIcons = {
0, // index 0 is empty
R.drawable.books,
R.drawable.films,
R.drawable.music,
R.drawable.games,
};
private int categoryId;
private ProductListAdapter adapter;
private ListViewLoader loader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get the category from the intent
Intent intent = getIntent();
categoryId = intent.getIntExtra(MainActivity.SELECTED_CATEGORY, 0);
adapter = new ProductListAdapter(this);
setListAdapter(adapter);
// Show the Up button in the action bar.
setupActionBar();
loader = new ListViewLoader(adapter, categoryId);
loader.execute(String.format(MainActivity.WEBSERVER_GETLIST, categoryId));
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.product_list, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.show_cart:
//create the intent for the cart activity
Intent intent = new Intent(getApplicationContext(), CartActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
//create an intent
Intent intent = new Intent(this, ProductActivity.class);
Product p = (Product)adapter.getItem(position);
//specify the extra parameters we want to pass
intent.putExtra(MainActivity.SELECTED_CATEGORY, p.getCategoryId());
intent.putExtra(MainActivity.SELECTED_PRODUCTID, p.getProductId());
intent.putExtra(MainActivity.SELECTED_PRODUCTNAME, p.getProductName());
intent.putExtra(MainActivity.SELECTED_PRODUCTPRICE, p.getPrice());
intent.putExtra(MainActivity.SELECTED_SUITABLEFORKIDS, p.getSuitableForKids());
startActivity(intent);
}
}
EDIT:
XML for adapter_product_list
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<ImageView
android:id="#+id/product_image"
android:layout_width="54dp"
android:layout_height="54dp"
android:padding="5dp"
android:layout_alignParentLeft="true" />
<TextView
android:id="#+id/product_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/product_image"
android:layout_alignTop="#+id/product_image"
android:textColor="#446688"
android:textSize="20sp" />
<TextView
android:id="#+id/product_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/product_image"
android:layout_below="#+id/product_title"
android:textColor="#777777"
android:textSize="16sp"
android:textStyle="italic" />
</RelativeLayout>
Change your xml like following
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp" >
<ImageView
android:id="#+id/product_image"
android:layout_width="54dp"
android:layout_height="54dp"
android:layout_alignParentLeft="true"
android:padding="5dp"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/product_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/product_image"
android:layout_toRightOf="#+id/product_image"
android:text="adjkajdjk"
android:textColor="#446688"
android:textSize="20sp" />
<TextView
android:id="#+id/product_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/product_title"
android:layout_toRightOf="#+id/product_image"
android:text="adjkajdjk"
android:textColor="#777777"
android:textSize="16sp"
android:textStyle="italic" />
<Button
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Delete" />
</RelativeLayout>
And in your adapter inside getView() function add this
Button deleteBtn = (Button) findViewById(R.id.delete_btn);
deleteBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
itemList.remove(position);
notifyDataSetChanged();
}
});
1) hope p.loadImage(imgView, 54, 54); is running in a asyncTask
2) if you want to click on a button in a row of a ListView than you shoudl add the button to your row layout and implent onClickListenr of that button in your getView method of adapter.in onClick method yous hould have:
if(position<itemList.size()){
//TO REMOVE TEM FROM ARRAY LIST
itemList.remove(position);
//TO Update the ListView
notifyDataSetChanged();
}
you can implement a multy line delete,by adding a checkbox in your listRow and adding the positon of the item to be deleted to an arrayList of Integers and after click-ing the delete button you should delete all the items from the imteList and after that call notifyDataSetChanged()
EDIT
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<ImageView
android:id="#+id/product_image"
android:layout_width="54dp"
android:layout_height="54dp"
android:padding="5dp"
android:layout_alignParentLeft="true" />
<TextView
android:id="#+id/product_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/product_image"
android:layout_alignTop="#+id/product_image"
android:textColor="#446688"
android:textSize="20sp" />
<TextView
android:id="#+id/product_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/product_image"
android:layout_below="#+id/product_title"
android:textColor="#777777"
android:textSize="16sp"
android:textStyle="italic" />
<Button
android:id="#+id/deleteBtn"
android:layout_width="wrap_content
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/product_info"
</RelativeLayout>
you should add this button to your layout, and in getView method of adapter add
Button delete=v.findViewById(R.id.deleteBtn);
delete.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//THE PART I WROTE ABOVE
}
})

Categories

Resources