I want to make a music player in my fragment page for my android app using android studio. There is no error to the code however when i run the code the fragment page is not appearing the audio player. i follow the code from youtube: https://www.youtube.com/watch?v=rJ3XbXtjNaE&t=385s
this is the code
fragment_med1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:background="#drawable/scene"
tools:context=".Med1Fragment">
<ImageView
android:layout_width="match_parent"
android:layout_height="250dp"
android:src="#drawable/ic_baseline_music_note_24"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="12dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/player_position"
android:text="00:00"
android:textStyle="bold"
android:textColor="#android:color/white"/>
<SeekBar
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="#+id/seek_bar"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/player_duration"
android:text="00:00"
android:textStyle="bold"
android:textColor="#android:color/white"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:orientation="horizontal">
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:id="#+id/bt_rew"
android:src="#drawable/ic_baseline_fast_rewind_24"/>
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:id="#+id/bt_play"
android:src="#drawable/ic_baseline_play_circle_filled_24"/>
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:id="#+id/bt_pause"
android:src="#drawable/ic_baseline_pause_circle_filled_24"/>
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:id="#+id/bt_ff"
android:src="#drawable/ic_baseline_fast_forward_24"/>
</LinearLayout>
</LinearLayout>
Med1Fragment.java
public class Med1Fragment extends Fragment {
TextView playerposition, playerduration;
SeekBar seekBar;
ImageView btnrew, btnplay, btnpause, btnff;
MediaPlayer mediaPlayer;
Handler handler = new Handler();
Runnable runnable;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
playerposition = playerposition.findViewById(R.id.player_position);
playerduration = playerduration.findViewById(R.id.player_duration);
seekBar = seekBar.findViewById(R.id.seek_bar);
btnrew = btnrew.findViewById(R.id.bt_rew);
btnplay = btnplay.findViewById(R.id.bt_play);
btnpause = btnpause.findViewById(R.id.bt_pause);
btnff = btnff.findViewById(R.id.bt_ff);
mediaPlayer = MediaPlayer.create(getActivity(), R.raw.meditation2);
runnable = new Runnable() {
#Override
public void run() {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
handler.postDelayed(this, 500);
}
};
int duration = mediaPlayer.getDuration();
String sDuration = convertFormat(duration);
playerduration.setText(sDuration);
btnplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnplay.setVisibility(View.GONE);
btnpause.setVisibility(View.VISIBLE);
mediaPlayer.start();
seekBar.setMax(mediaPlayer.getDuration());
handler.postDelayed(runnable,0);
}
});
btnpause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnpause.setVisibility(View.GONE);
btnplay.setVisibility(View.VISIBLE);
mediaPlayer.pause();
handler.removeCallbacks(runnable);
}
});
btnff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int currentposition = mediaPlayer.getCurrentPosition();
int duration = mediaPlayer.getDuration();
if(mediaPlayer.isPlaying() && duration != currentposition){
currentposition = currentposition + 5000;
playerposition.setText(convertFormat(currentposition));
mediaPlayer.seekTo(currentposition);
}
}
});
btnrew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int currentposition = mediaPlayer.getCurrentPosition();
if(mediaPlayer.isPlaying() && currentposition > 5000){
currentposition = currentposition - 5000;
playerposition.setText(convertFormat(currentposition));
mediaPlayer.seekTo(currentposition);
}
}
});
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser){
mediaPlayer.seekTo(progress);
}
playerposition.setText(convertFormat(mediaPlayer.getCurrentPosition()));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
btnpause.setVisibility(View.GONE);
btnplay.setVisibility(View.VISIBLE);
mediaPlayer.seekTo(0);
}
});
}
#SuppressLint("DefaultLocale")
private String convertFormat(int duration){
return String.format("%02d:%02d"
, TimeUnit.MILLISECONDS.toMinutes(duration)
, TimeUnit.MILLISECONDS.toSeconds(duration) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration)));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_med1, container, false);
}
}
I am always confused to write the code for fragment because the usual code i get/learn from (eg:youtube) are written for activity instead of fragment.
really appreciate some help. thank you.
Related
I am building a simple video player Ui and I have a : seekbar and two buttons to controle the video view, when I click on any point of seekbar every thing is ok and video view progress will be the same with seekbar and the buttons is working too ! but,when I handle the seekbar thumb and move it ,then leave it, every thing messing up and the seekbar and the buttons will never work again, so I am not getting an Exception error it's just will not work again. why that happening?
Activity
public class Player extends AppCompatActivity {
View controller;
Handler handler;
SeekBar seekBar;
VideoView videoView;
ImageButton play_btn, pause_btn;
ImageButton forward_btn, replay_btn;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
handler = new Handler();
videoView = (VideoView) findViewById(R.id.videoView);
controller = findViewById(R.id.player_controller); // the controller View
hideController(controller);
forward_btn = (ImageButton) findViewById(R.id.playerController_forward_10_Button);
replay_btn = (ImageButton) findViewById(R.id.playerController_replay_10_Button);
forward_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
forward_10_sec();
}
});
replay_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
reply_10_sec();
}
});
play_btn = (ImageButton) findViewById(R.id.playerController_playButton);
pause_btn = (ImageButton) findViewById(R.id.playerController_pauseButton);
play_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play();
}
});
pause_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pause();
}
});
seekBar = findViewById(R.id.playerController_seekBar); // video seekBar
seekBar.setOnSeekBarChangeListener(onSeekBarChangeListener);
videoView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (controller.getVisibility() == View.INVISIBLE)
showController(controller);
else
hideController(controller);
}
});
Intent intent = getIntent();
if (intent != null)
setVideoSource(intent);
}
private void play() {
if(!videoView.isPlaying()) {
videoView.start();
play_btn.setVisibility(View.INVISIBLE);
pause_btn.setVisibility(View.VISIBLE);
}
}
private void pause() {
if(videoView.isPlaying()) {
videoView.pause();
pause_btn.setVisibility(View.INVISIBLE);
play_btn.setVisibility(View.VISIBLE);
}
}
private void forward_10_sec() {
if (videoView.canSeekForward())
videoView.seekTo(videoView.getCurrentPosition() + 1000);
}
private void reply_10_sec() {
if (videoView.canSeekBackward())
videoView.seekTo(videoView.getCurrentPosition() - 1000);
}
// to show the controllers
private void showController(View controller) {
controller.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
hideController(controller);
}
}, 6000);
}
// to hide the controllers
private void hideController(View controller) {
controller.setVisibility(View.INVISIBLE);
}
// to set video source from the main app or file manager
private void setVideoSource(Intent intent) {
... some codes to set path ...
play();
showController(controller);
updateSeekBarProgress();
}
// to move seekBar to real video progress
private void updateSeekBarProgress() {
Player.this.runOnUiThread(updateSeekBar);
}
private Runnable updateSeekBar = new Runnable() {
#Override
public void run() {
seekBar.setMax(videoView.getDuration() / 1000);
seekBar.setProgress(videoView.getCurrentPosition() / 1000);
seekBar.postDelayed(this,500);
}
};
SeekBar.OnSeekBarChangeListener onSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if (b) {
videoView.seekTo(i*1000);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
}
activity_player
<?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"
android:background="#color/black"
tools:context=".Player">
<VideoView
android:id="#+id/videoView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<include
android:id="#+id/player_controller"
layout="#layout/player_controller" />
</androidx.constraintlayout.widget.ConstraintLayout>
player_controller
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/transparent_black">
<ImageButton
android:id="#+id/playerController_playButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null"
android:src="#drawable/play_icon_48"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="#+id/playerController_pauseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null"
android:src="#drawable/pause_icon_48"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="#+id/playerController_replay_10_Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null"
android:src="#drawable/replay_10_icon_48"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#id/playerController_playButton"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="#+id/playerController_forward_10_Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null"
android:src="#drawable/forward_10_icon_48"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#id/playerController_playButton"
app:layout_constraintTop_toTopOf="parent" />
<SeekBar
android:id="#+id/playerController_seekBar"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginStart="5dp"
android:layout_marginEnd="5dp"
android:progressBackgroundTint="#color/white"
android:progressTint="#color/white"
android:secondaryProgressTint="#color/light_purple"
android:thumbTint="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/playerController_playButton" />
</androidx.constraintlayout.widget.ConstraintLayout>
so, in a simple way : I want to set video view progress like seekbar progress with any way that I move the seek bar with.
(now it's just works when click on it and when handle and move it , nothing works again).
thanks...
It's finally has been done with that :
SeekBar.OnSeekBarChangeListener onSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if (b) {
videoView.seekTo(i * 1000);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
handler.removeCallbacks(updateSeekBar);
pause();
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
videoView.seekTo(seekBar.getProgress()*1000);
play();
updateSeekBarProgress();
}
};
I designed dialog and assigned it a file named XML layout with a set of elements and then created a function to show it from within fragment. It appeared on the emulator screen well but it did not appear the same on the device.
What are the appropriate adjustments to be shown on the device well?
// layout xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="260dp"
android:layout_height="260dp"
android:orientation="vertical"
android:background="#f71717">
<LinearLayout
android:id="#+id/l_layout"
android:paddingTop="10dp"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
tools:ignore="ObsoleteLayoutParam">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
tools:ignore="ExtraText">
<RadioGroup
android:id="#+id/radioSex"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:ignore="UselessParent">
<RadioButton
android:id="#+id/second2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:button="#null"
android:layoutDirection="rtl"
android:textAlignment="textStart"
android:layout_gravity="start"
android:textDirection="rtl"
android:drawablePadding="10dp"
android:drawableRight="#android:drawable/btn_radio"
android:text="رفض"
android:textColor="#ffffff"
android:textSize="20dp"
tools:ignore="HardcodedText,RtlHardcoded,SpUsage" />
<RadioButton
android:id="#+id/second"
android:checked="true"
android:layoutDirection="rtl"
android:textDirection="rtl"
android:textAlignment="textStart"
android:layout_gravity="start"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:button="#null"
android:drawablePadding="10dp"
android:drawableRight="#android:drawable/btn_radio"
android:text="قبول"
android:textColor="#ffffff"
android:textSize="20dp"
tools:ignore="HardcodedText,RtlHardcoded,SpUsage" />
</RadioGroup>
/>
</LinearLayout>
<TextView
android:id="#+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#ffffff"
android:text="وقت التسليم"
android:textSize="20dp"
tools:ignore="HardcodedText,SpUsage" />
<Spinner
android:id="#+id/tex"
android:layout_width="172dp"
android:paddingRight="40dp"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_title"
android:drawSelectorOnTop="true"
android:popupBackground="#fff78c"
style="#style/spinner_style"
tools:ignore="HardcodedText,RtlHardcoded,RtlSymmetry,SpUsage"
android:entries="#array/day_"/>
</LinearLayout>
<RelativeLayout
android:id="#+id/rl"
android:layout_width="250dp"
android:layout_height="129dp"
android:layout_below="#+id/l_layout"
android:background="#f71717"
android:layout_marginTop="0dp"
tools:ignore="ObsoleteLayoutParam">
<TextView
android:id="#+id/tv_h"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toStartOf="#+id/spinner_minutes2"
android:paddingLeft="10dp"
android:text="ساعة"
android:textColor="#ffffff"
tools:ignore="HardcodedText,RtlHardcoded,RtlSymmetry" />
<TextView
android:id="#+id/tv_m"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/spinner_minutes2"
android:layout_alignBottom="#+id/spinner_minutes2"
android:layout_alignStart="#+id/button_holder"
android:paddingLeft="10dp"
android:text="دق"
android:textColor="#ffffff"
tools:ignore="HardcodedText,RtlHardcoded,RtlSymmetry" />
<TextView
android:id="#+id/tv_pam"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/spinner_minutes"
android:layout_alignBottom="#+id/spinner_minutes"
android:layout_alignEnd="#+id/spinner_minutes3"
android:layout_marginEnd="12dp"
android:paddingLeft="30dp"
android:text="ص/م"
android:textColor="#ffffff"
tools:ignore="HardcodedText,RtlHardcoded,RtlSymmetry" />
<Spinner
android:id="#+id/spinner_minutes"
android:layout_width="85dip"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
style="#style/spinner_style"
android:popupBackground="#fff78c"
android:layout_alignStart="#+id/spinner_minutes2"
android:entries="#array/hour_" />
<Spinner
android:id="#+id/spinner_minutes2"
android:layout_width="85dip"
android:layout_height="wrap_content"
android:layout_below="#+id/spinner_minutes"
android:layout_marginStart="16dp"
android:popupBackground="#fff78c"
style="#style/spinner_style"
android:layout_toEndOf="#+id/tv_m"
android:entries="#array/hour_" />
<Spinner
android:id="#+id/spinner_minutes3"
android:layout_width="85dip"
android:layout_height="wrap_content"
style="#style/spinner_style"
android:paddingRight="20dp"
android:entries="#array/apm"
android:popupBackground="#fff78c"
tools:ignore="RtlHardcoded,RtlSymmetry"
android:layout_alignBaseline="#+id/spinner_minutes2"
android:layout_alignBottom="#+id/spinner_minutes2"
android:layout_toEndOf="#+id/spinner_minutes" />
<TextView
android:id="#+id/text_timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textAppearance="?android:attr/textAppearanceMedium"
android:visibility="gone" />
<LinearLayout
android:id="#+id/button_holder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/spinner_minutes"
android:layout_centerHorizontal="true"
android:paddingTop="10dp"
android:layout_marginTop="20dip">
<Button
android:id="#+id/button_set"
android:layout_width="100dip"
android:layout_height="wrap_content"
android:layout_marginBottom="5dip"
android:layout_marginLeft="10dip"
android:text="الغاء"
tools:ignore="ButtonStyle,HardcodedText,RtlHardcoded" />
<Button
android:id="#+id/button_cancel"
android:layout_width="100dip"
android:layout_height="wrap_content"
android:layout_marginBottom="5dip"
android:layout_marginRight="10dip"
android:text="إرسال"
tools:ignore="ButtonOrder,ButtonStyle,HardcodedText,RtlHardcoded" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
//calss Fragment:
public class Page_6Fragment extends android.support.v4.app.Fragment implements AdapterView.OnItemSelectedListener {
TextView t1,t2,t3,t4;
Spinner spin ,spin2,spin3,spin4;
Dialog dialog;
RecyclerView recyclerView;
List<Customer> customers;
CustomerAdapter adapter;
View rootView;
String TAG = "MainActivity - ";
Context context;
API api;
Activity a;
public static Page_6Fragment newInstance() {
Page_6Fragment fragment = new Page_6Fragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_customer, container, false);
// View rootView = inflater.inflate(R.xml.pref, container, false);
// Intent intent = new Intent(PreferenceDemoActivity.this,PrefsActivity.class);
// startActivity(intent);
this.context = getActivity();
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
customers = new ArrayList<>();
adapter = new CustomerAdapter(context, customers);
adapter.setLoadMoreListener(new CustomerAdapter.OnLoadMoreListener(){
#Override
public void onLoadMore() {
recyclerView.post(new Runnable() {
#Override
public void run() {
int index = customers.size() - 1;
loadMore(index);
}
});
//Calling loadMore function in Runnable to fix the
// java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling error
}
});
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
//recyclerView.addItemDecoration(new VerticalLineDecorator(2));
recyclerView.setAdapter(adapter);
api = ServiceGenerator.createService(API.class);
load(0);
return rootView;
}
private void load(int index){
Call<List<Customer>> call = api.getCustomer(index);
call.enqueue(new Callback<List<Customer>>(){
#Override
public void onResponse(Call<List<Customer>> call, Response<List<Customer>> response){
// Toast.makeText(getActivity(), "tost "+response.body().get(0).post_writer, Toast.LENGTH_LONG).show();
// Log.i("TRUE_TRUE","Yes"+response.body().get(0).title);
if(response.isSuccessful()){
customers.addAll(response.body());
adapter.notifyDataChanged();
// Toast.makeText(MainActivity.this, "tost "+response.body().get(0).post_writer, Toast.LENGTH_LONG).show();
}else{
Log.e(TAG," Response Error "+String.valueOf(response.code()));
}
}
#Override
public void onFailure(Call<List<Customer>> call, Throwable t) {
Log.e(TAG," Response Error "+t.getMessage());
}
});
}
private void loadMore(int index){
//add loading progress view
customers.add(new Customer("load"));
adapter.notifyItemInserted(customers.size()-1);
Call<List<Customer>>call = api.getCustomer(index);
call.enqueue(new Callback<List<Customer>>(){
#Override
public void onResponse(Call<List<Customer>> call, Response<List<Customer>>response) {
if(response.isSuccessful()){
// remove loading view .......
customers.remove(customers.size()-1);
List<Customer>result=response.body();
if(result.size()>0){
// add loaded data
customers.addAll(result);
}else{//result size 0 means there is no more data available at server
adapter.setMoreDataAvailable(false);
//telling adapter to stop calling load more as no more server data available
Toast.makeText(context,"No More Data Available",Toast.LENGTH_LONG).show();
}
adapter.notifyDataChanged();
}else{
Log.e(TAG," Load More Response Error "+String.valueOf(response.code()));
}
}
#Override
public void onFailure(Call<List<Customer>>call,Throwable t) {
Log.e(TAG," Load More Response Error "+t.getMessage());
}
});
}
public void showDialog(Context context){
dialog = new Dialog(context);
dialog.setCancelable(true);
dialog.setContentView(R.layout.layout);
dialog.show();
String[] bankNames = {
"BO","SB","HD","PN","Bj"
};
t1= (TextView)dialog.findViewById(R.id.tv_h);
t2= (TextView)dialog.findViewById(R.id.tv_m);
t3= (TextView)dialog.findViewById(R.id.tv_title);
t4= (TextView)dialog.findViewById(R.id.tv_pam);
spin =(Spinner)dialog.findViewById(R.id.spinner_minutes);
spin2 =(Spinner)dialog.findViewById(R.id.spinner_minutes2);
spin3 =(Spinner)dialog.findViewById(R.id.spinner_minutes3);
spin4 =(Spinner)dialog.findViewById(R.id.tex);
spin.setOnItemSelectedListener(this);
spin2.setOnItemSelectedListener(this);
spin3.setOnItemSelectedListener(this);
spin4.setOnItemSelectedListener(this);
RadioButton radioButton2 = (RadioButton)dialog.findViewById(R.id.second2);
RadioButton radioButton = (RadioButton)dialog.findViewById(R.id.second);
RadioGroup radioGroup = (RadioGroup)dialog.findViewById(R.id.radioSex);
ArrayAdapter<String> a = new ArrayAdapter<String>(context,R.layout.spinner_item,bankNames);
//ArrayAdapter b = new ArrayAdapter(this,android.R.layout.simple_spinner_item,bankNames2);
a.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(a);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton = (RadioButton)dialog.findViewById(checkedId);
if (checkedId == R.id.second2) {
RadioYes();
} else if (checkedId == R.id.second) {
RadioNo();
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE);
((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE);
((TextView) parent.getChildAt(0)).setTextSize(16);
// Toast.makeText(getApplicationContext(),"" +spin2.getSelectedItem(), Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void RadioNo(){
spin.setVisibility(View.VISIBLE);
spin2.setVisibility(View.VISIBLE);
spin3.setVisibility(View.VISIBLE);
spin4.setVisibility(View.VISIBLE);
t1.setVisibility(View.VISIBLE);
t2.setVisibility(View.VISIBLE);
t3.setVisibility(View.VISIBLE);
t4.setVisibility(View.VISIBLE);
}
public void RadioYes(){
spin.setVisibility(View.GONE);
spin2.setVisibility(View.GONE);
spin3.setVisibility(View.GONE);
spin4.setVisibility(View.GONE);
t1.setVisibility(View.GONE);
t2.setVisibility(View.GONE);
t3.setVisibility(View.GONE);
t4.setVisibility(View.GONE);
}
}
// class to call function show dailoge
public class CustomerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public final int TYPE_MOVIE = 0;
public final int TYPE_LOAD = 1;
static Context context;
List<Customer> customers;
OnLoadMoreListener loadMoreListener;
boolean isLoading = false, isMoreDataAvailable = true;
public CustomerAdapter(Context context, List<Customer> customers) {
this.context = context;
this.customers = customers;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
if(viewType==TYPE_MOVIE){
return new CustomerHolder(inflater.inflate(R.layout.row_movie,parent,false));
}else{
return new LoadHolder(inflater.inflate(R.layout.row_load,parent,false));
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if(position>=getItemCount()-1 && isMoreDataAvailable && !isLoading && loadMoreListener!=null){
isLoading = true;
loadMoreListener.onLoadMore();
}
if(getItemViewType(position)==TYPE_MOVIE){
((CustomerHolder)holder).bindData(customers.get(position));
if(((CustomerHolder)holder).buttonViewOption != null)((CustomerHolder)holder).buttonViewOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Page_6Fragment.newInstance().showDialog(context);
}
});
}
}
#Override
public int getItemViewType(int position) {
if(customers.get(position).type.equals("movie")){
return TYPE_MOVIE;
}else{
return TYPE_LOAD;
}
}
#Override
public int getItemCount(){
return customers.size();
}
/* VIEW HOLDERS */
static class CustomerHolder extends RecyclerView.ViewHolder{
TextView tvTitle;
TextView tvRating;
Button buttonViewOption;
public CustomerHolder(View itemView) {
super(itemView);
tvTitle=(TextView)itemView.findViewById(R.id.title);
tvRating=(TextView)itemView.findViewById(R.id.rating);
buttonViewOption = (Button) itemView.findViewById(R.id.textViewOptions);
}
void bindData(Customer cust){
tvTitle.setText(cust.name);
tvRating.setText(cust.title);
}
}
static class LoadHolder extends RecyclerView.ViewHolder{
public LoadHolder(View itemView) {
super(itemView);
}
}
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
/* notifyDataSetChanged is final method so we can't override it
call adapter.notifyDataChanged(); after update the list
*/
public void notifyDataChanged(){
notifyDataSetChanged();
isLoading = false;
}
public interface OnLoadMoreListener{
void onLoadMore();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
}
I have a problem ,I create recyclerview and its work fine at the first search data from api , it display fine but when I try to search with new data ( second time ) it is not display anything i try to test and debug every every thing work fine and new data enter to adapter and get the result fine and set adapter to recyclerview but it is not showing any thing
I try several method like use only one adapter and change it's list of Date and use notifyDataSetChange but not work still only show at the first time
Below activity is use to search get date ( use in searching data )
fromDate to toDate
DeliveryReportActivity.java
public class DeliveryReportActivity extends AppCompatActivity
implements DateDialogFromFragment.SelectDateFromInterface,
DateDialogToFragment.SelectDateToInterface {
Button btn_from;
Button btn_to;
EditText et_fromDate;
EditText et_toDate;
Button search_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delivery_report);
btn_from=(Button)findViewById(R.id.btn_fromDate);
btn_to=(Button)findViewById(R.id.btn_toDate);
et_fromDate = (EditText) findViewById(R.id.from_date);
et_toDate = (EditText) findViewById(R.id.to_date);
search_btn=(Button)findViewById(R.id.search_delivery_report_btn);
et_fromDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(new
Date()));
et_toDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(new
Date()));
btn_from.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DateDialogFromFragment dateDialogFragment = new
DateDialogFromFragment();
android.app.FragmentTransaction ft =
getFragmentManager().beginTransaction();
dateDialogFragment.show(ft, "DatePicker");
}
});
btn_to.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DateDialogToFragment dateDialogFragment = new
DateDialogToFragment();
android.app.FragmentTransaction ft =
getFragmentManager().beginTransaction();
dateDialogFragment.show(ft, "DatePicker");
}
});
search_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle bundle=new Bundle();
bundle.putString("from",et_fromDate.getText().toString()+ "
00:00:00");
bundle.putString("to",et_toDate.getText().toString()+" 23:59:59");
Intent intent =new
Intent(DeliveryReportActivity.this,DeliveryReportListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
#Override
public void onGetSelectFromDate(String fromDate) {
et_fromDate.setText(fromDate);
}
#Override
public void onGetSelectToDate(String toDate) {
et_toDate.setText(toDate);
}
}
and it's view activity_delivery_report.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:orientation="vertical"
tools:context="com.exatech.groupsmsandroid.activity.
deliveryReport.DeliveryReportActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/btn_fromDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/From"
android:textSize="18dp" />
<EditText
android:id="#+id/from_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="2017-12-26" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:orientation="horizontal">
<Button
android:id="#+id/btn_toDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/to" />
<EditText
android:id="#+id/to_date"
android:text="2017-12-26"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_centerInParent="true"
android:gravity="center"
android:layout_marginTop="20dp"
android:id="#+id/search_delivery_report_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:text="#android:string/search_go" />
</RelativeLayout>
</LinearLayout>
after I press the search button it's start new activity that show my recylerview the new activity is
DeliveryReportListActivity .java
public class DeliveryReportListActivity extends AppCompatActivity implements
DeliveryReportService.DeliveryReportServiceInterface {
private static final String TAG = "GSMS";
private Bundle bundle;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delivery_report_list);
recyclerView = (RecyclerView) findViewById(R.id.delivery_report_rv);
}
#Override
protected void onResume() {
super.onResume();
bundle = getIntent().getExtras();
String from = bundle.getString("from");
String to = bundle.getString("to");
DeliveryReportService.getInstance(this).
getDeliveryReportFromDateToDate(from, to);// Call api get deliver
}
#Override
public void onGetDeliveryReport(Response<List<DeliveryReportResource>>
listResponse) {// response
Log.i(TAG, "onGetDeliveryReport: listResponse.body():" +
listResponse.body());
DeliveryReportAdapter deliveryReportAdapter = new
DeliveryReportAdapter(DeliveryReportListActivity.this, listResponse.body());
recyclerView.setAdapter(deliveryReportAdapter);
deliveryReportAdapter.notifyDataSetChanged();
Toast.makeText(DeliveryReportListActivity.this, "Delivery Report Success
", Toast.LENGTH_SHORT).show();
}
#Override
public void onDeliveryConnectionFailed() {
Toast.makeText(DeliveryReportListActivity.this, "Connect Error ",
Toast.LENGTH_SHORT).show();
}
}
and it's view activity_delivery_report_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.exatech.groupsmsandroid.activity.deliveryReport.
DeliveryReportListActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:text="#string/text"
android:layout_weight="3"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_weight="4"
android:text="#string/phone_no"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_weight="4"
android:text="#string/status"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/delivery_report_rv"
android:layout_width="match_parent"
app:layoutManager="LinearLayoutManager"
android:layout_height="match_parent"
tools:listitem="#layout/delivery_report_list_content"/>
</LinearLayout>
Below is Myadapter Class
**DeliveryReportAdapter.java**
public class DeliveryReportAdapter extends
RecyclerView.Adapter<DeliveryReportAdapter.ViewHolder> {
List<DeliveryReportResource> listDeliveryReport;
Context context;
public DeliveryReportAdapter(Context context, List<DeliveryReportResource>
listDeliveryReport) {
this.listDeliveryReport = listDeliveryReport;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view =
LayoutInflater.from(parent.getContext()).
inflate(R.layout.delivery_report_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.item = listDeliveryReport.get(position);
holder.text.setText(holder.item.getText());
CustomAdapterFroDeliveryReport adapterFroDeliveryReport = new
CustomAdapterFroDeliveryReport(context, R.layout.two_text_contect,
listDeliveryReport.get(position).getSmsSubscribedRecipientsResourceList());
holder.phoneNoAndStatus.setAdapter(adapterFroDeliveryReport);
holder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "click message no=" +
holder.item.getText(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return listDeliveryReport.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
View view;
TextView text;
ListView phoneNoAndStatus;
DeliveryReportResource item;
public ViewHolder(View itemView) {
super(itemView);
view = itemView;
text = (TextView) itemView.findViewById(R.id.message_tv);
phoneNoAndStatus = (ListView)
itemView.findViewById(R.id.phoneNo_and_status_lv);
}
}
}
Try to create an adapter once and then update items
Add next code to your adapter class
ArrayList<DeliveryReportResource> listDeliveryReport = new ArrayList<DeliveryReportResource>();
public DeliveryReportAdapter(Context context) {
this.context = context;
}
public void updateItems(List<DeliveryReportResource> list) {
listDeliveryReport.clear();
listDeliveryReport.addAll(list);
notifyDataSetChanged();
}
Then create adapter once in onCreate() and place it as global variable
And now you should call adapter.updateItems(...) every time you want to change data
Hello its been 2 days i am searching for a solution for this and still have no idea how to do, i want make a swipe left and right also rearrange recycle view,When user swipe left it will automatically list in completed list and if swipe on left it will delete list item in recycle view also user can rearrange the list element my long press.
Here is main activity:
public class MainActivity extends AppCompatActivity {
private RecyclerView shoppingItems;
private Toolbar toolbar;
private Realm realm;
private CoordinatorLayout coordinatorLayout;
private List<ShoppingItem> dataSet;
private RecyclerView.Adapter shoppingItemsAdapter = new RecyclerView.Adapter() {
private final int ACTIVE_VIEW=1;
private final int INACTIVE_VIEW=2;
private final int SUBHEADER_VIEW=3;
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == ACTIVE_VIEW) {
View v = getLayoutInflater().inflate(R.layout.active_item, parent, false);
return new ActiveItemViewHolder(v,
(CheckBox)v.findViewById(R.id.item_status),
(TextView)v.findViewById(R.id.item_name),
(TextView)v.findViewById(R.id.item_quantity),
(ImageView)v.findViewById(R.id.item_action)
);
} else if(viewType == INACTIVE_VIEW) {
View v = getLayoutInflater().inflate(R.layout.inactive_item, parent, false);
return new InactiveItemViewHolder(v,
(CheckBox)v.findViewById(R.id.item_status),
(TextView)v.findViewById(R.id.item_name),
(ImageView)v.findViewById(R.id.item_action)
);
} else {
View v = getLayoutInflater().inflate(R.layout.subheader, parent, false);
return new SubheaderViewHolder(v);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final ShoppingItem currentItem = dataSet.get(position);
if(currentItem.getTimestamp()==-1) return;
if(currentItem.isCompleted()) {
InactiveItemViewHolder h = (InactiveItemViewHolder)holder;
h.itemName.setText(currentItem.getName());
h.itemName.setPaintFlags(h.itemName.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
h.itemAction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Task is restored", Snackbar.LENGTH_LONG);
snackbar.show();
realm.beginTransaction();
currentItem.setCompleted(false);
currentItem.setTimestamp(System.currentTimeMillis());
realm.commitTransaction();
initializeDataSet();
shoppingItemsAdapter.notifyDataSetChanged();
}
});
}else{
ActiveItemViewHolder h = (ActiveItemViewHolder)holder;
h.itemName.setText(currentItem.getName());
h.itemQuantity.setText(currentItem.getQuantity());
h.itemStatus.setChecked(false);
h.itemStatus.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
if (checked) {
realm.beginTransaction();
currentItem.setCompleted(true);
currentItem.setTimestamp(System.currentTimeMillis());
realm.commitTransaction();
initializeDataSet();
shoppingItemsAdapter.notifyDataSetChanged();
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Task is Completed", Snackbar.LENGTH_LONG)
.setAction("UNDO", new View.OnClickListener() {
#Override
public void onClick(View view) {
realm.beginTransaction();
currentItem.setCompleted(false);
currentItem.setTimestamp(System.currentTimeMillis());
realm.commitTransaction();
initializeDataSet();
shoppingItemsAdapter.notifyDataSetChanged();
Snackbar snackbar1 = Snackbar.make(coordinatorLayout, "Task is restored!", Snackbar.LENGTH_SHORT);
snackbar1.show();
}
});
snackbar.show();
}
}
});
h.itemAction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, ItemActivity.class);
i.putExtra("TITLE", "Edit item");
i.putExtra("ITEM_NAME", currentItem.getName());
i.putExtra("ITEM_QUANTITY", currentItem.getQuantity());
i.putExtra("ITEM_ID", currentItem.getId());
startActivityForResult(i, 1);
}
});
}
}
#Override
public int getItemCount() {
return dataSet.size();
}
#Override
public int getItemViewType(int position) {
ShoppingItem currentItem = dataSet.get(position);
if(currentItem.getTimestamp()==-1) return SUBHEADER_VIEW;
if(currentItem.isCompleted()) return INACTIVE_VIEW;
return ACTIVE_VIEW;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
RealmConfiguration configuration =
new RealmConfiguration.Builder(this).build();
Realm.setDefaultConfiguration(configuration);
realm = Realm.getDefaultInstance();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, ItemActivity.class);
i.putExtra("TITLE", "Add Task");
startActivityForResult(i, 1);
}
});
shoppingItems = (RecyclerView)findViewById(R.id.shopping_items);
shoppingItems.setLayoutManager(new LinearLayoutManager(this));
initializeDataSet();
shoppingItems.setAdapter(shoppingItemsAdapter);
}
private void initializeDataSet() {
dataSet = new ArrayList<>();
RealmResults<ShoppingItem> activeItemResults
= realm.where(ShoppingItem.class).equalTo("completed", false)
.findAllSorted("timestamp", Sort.DESCENDING);
RealmResults<ShoppingItem> inactiveItemResults
= realm.where(ShoppingItem.class).equalTo("completed", true)
.findAllSorted("timestamp", Sort.DESCENDING);
ShoppingItem subheader = new ShoppingItem();
subheader.setTimestamp(-1);
for(ShoppingItem item:activeItemResults) dataSet.add(item);
dataSet.add(subheader);
for(ShoppingItem item:inactiveItemResults) dataSet.add(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK) {
initializeDataSet();
shoppingItemsAdapter.notifyDataSetChanged();
}
}
activity main.xml
android.support.design.widget.CoordinatorLayout 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/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.github.hathibelagal.shoppinglist.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#drawable/ic_add_24dp"
android:tint="#android:color/white" />
</android.support.design.widget.CoordinatorLayout>
active_item.xml:
RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="72dp">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/item_status"
android:layout_centerVertical="true"
android:layout_alignParentStart="true" />
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="72dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/item_name"
android:textColor="#android:color/black" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/item_quantity" />
</LinearLayout>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/item_action"
android:layout_centerVertical="true"
android:layout_alignParentEnd="true"
android:src="#drawable/ic_create_24dp"
android:alpha="0.26" />
</RelativeLayout>
Please help me! Thanks for advance!
Try this out :
https://medium.com/#ipaulpro/drag-and-swipe-with-recyclerview-b9456d2b1aaf#.lrbbupqkq
Stack Overflow post for the same :
RecyclerView Swipe with a view below it
Drag and drop items in RecyclerView with GridLayoutManager
I'm trying to replace a ListView with a RecyclerView. The click listeners I had set up for it look like this (this is from the Activity):
//Road Trip selection
roadTripList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
RoadTrip trip = trips.get(i);
Intent intent= new Intent(RoadTripListActivity.this, RoadTripActivity.class);
intent.putExtra("startLocation", trip.getStart());
intent.putExtra("endLocation", trip.getEnd());
intent.putExtra("routeType", trip.getType());
setResult(RoadTripActivity.ROADTRIP_LIST_INTENT_RESULT, intent);
finish();
overridePendingTransition(R.anim.in_right, R.anim.out_left);
}
});
//Road Trip deletion
roadTripList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int i, long l) {
new AlertDialog.Builder(RoadTripListActivity.this)
.setTitle("Delete this Road Trip?")
.setMessage("Are you sure you want to delete this road trip from your saved trips?")
.setCancelable(true)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
trips.remove(i);
tripStrings.remove(i);
tinyDB.putListString("roadtrips", tripStrings);
//roadTripList.setAdapter(adapter);
adapter.updateAdapter(trips);
}
}).setNegativeButton("Cancel", null)
.create().show();
return true;
}
});
Adapter looks like this:
public class RoadTripListAdapter extends RecyclerView.Adapter<RoadTripListAdapter.ViewHolder> {
protected ArrayList<RoadTrip> trips;
protected Context context;
public RoadTripListAdapter(Context context, ArrayList<RoadTrip> trips) {
this.context = context;
this.trips = trips;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private final TextView startTextView;
private final TextView endTextView;
private final ImageView imageView;
private final LinearLayout itemLayout;
public ViewHolder(View v) {
super(v);
startTextView = (TextView) v.findViewById(R.id.roadtrip_list_start);
endTextView = (TextView) v.findViewById(R.id.roadtrip_list_end);
imageView = (ImageView) v.findViewById(R.id.roadtrip_list_icon);
itemLayout = (LinearLayout) v.findViewById(R.id.roadtrip_list_item_layout);
}
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
//Get the corresponding step
final RoadTrip trip = trips.get(position);
holder.startTextView.setText(trip.getStart());
holder.endTextView.setText(trip.getEnd());
if (trip.getType().equals(SearchType.walking.name())) {
holder.imageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_directions_walk_24dp));
} else {
holder.imageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_directions_car_24dp));
}
}
#Override
public int getItemCount() {
return trips.size();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.road_trip_list_item, parent, false);
return new ViewHolder(v);
}
public void updateAdapter(ArrayList<RoadTrip> trips) {
this.trips = trips;
this.notifyDataSetChanged();
}
}
And the list item xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/roadtrip_list_item_layout"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/roadtrip_list_icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="center_vertical"
android:layout_margin="5dp"
android:src="#drawable/ic_directions_car_24dp"/>
<LinearLayout
android:layout_width="wrap_content"
android:orientation="vertical"
android:layout_height="wrap_content">
<TextView
android:id="#+id/roadtrip_list_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textColor="#color/black"
android:text="Start: "/>
<TextView
android:id="#+id/roadtrip_list_end"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textColor="#color/black"
android:text="End: "/>
</LinearLayout>
</LinearLayout>
How can I set up the equivalent for a RecyclerView? Everything I can find on the subject says to set it up inside the adapter, but that won't work in this case... Is there a way to set it up in the Activity?
In onBindViewHolder, add OnClickListener and OnLongClickListener like this :
itemLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RoadTrip trip = trips.get(position);
Intent intent= new Intent(RoadTripListActivity.this, RoadTripActivity.class);
intent.putExtra("startLocation", trip.getStart());
intent.putExtra("endLocation", trip.getEnd());
intent.putExtra("routeType", trip.getType());
setResult(RoadTripActivity.ROADTRIP_LIST_INTENT_RESULT, intent);
finish();
overridePendingTransition(R.anim.in_right, R.anim.out_left);
}
});
//Road Trip deletion
itemLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
new AlertDialog.Builder(RoadTripListActivity.this)
.setTitle("Delete this Road Trip?")
.setMessage("Are you sure you want to delete this road trip from your saved trips?")
.setCancelable(true)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
trips.remove(position);
tripStrings.remove(position);
tinyDB.putListString("roadtrips", tripStrings);
notifyItemRemoved(position);
notifyItemRangeChanged(position, trips.size());
}
}).setNegativeButton("Cancel", null)
.create().show();
return true;
}
});
I figured it out:
((Activity) context).setResult(RoadTripActivity.ROADTRIP_LIST_INTENT_RESULT, intent);
((Activity) context).finish();
((Activity) context).overridePendingTransition(R.anim.in_right, R.anim.out_left);
I had been using getApplicationContext to pass as the context for the adapter, so I changed it to
adapter = new RoadTripListAdapter(this, trips);
in the activity.
out_marginLeft="50dp"
android:layout_marginTop="50dp"
android:layout_marginRight="50dp"
android:gravity="center"
android:orientation="vertical">
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/txtProgress"
android:layout_centerHorizontal="true"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:progress="50"
android:progressTint="#android:color/black" />
<TextView
android:id="#+id/txtProgress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Progress"
android:textColor="#android:color/black" />
</LinearLayout>
Java