I am trying to setup a onclicklistner on a dialog button. If the listener is set using
bnxt.setOnClickListener(new x());
the app works as expected but if the below given 2nd implementation is used, the app crashes. Any hint or help is highly appreciated.
bnxt.setOnClickListener(new OnClickListener() { ...
Supplied code:
class x implements OnClickListener {
x() {
}
public void onClick(View v) {
if (listener != null) {
final Dialog dialog = new Dialog(getActivity());
FancyButton m_no = (FancyButton) dialog.findViewById(R.id.b_no);
m_no.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
}
public View onCView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_x, container, false);
final FancyButton bnxt = (FancyButton) view.findViewById(R.id.btn_popup);
//bnxt.setOnClickListener(new x());
bnxt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (listener != null) {
final Dialog dialog = new Dialog(getActivity());
FancyButton m_no = (FancyButton) dialog.findViewById(R.id.b_no);
m_no.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
});
return view;
}
There is no problem with using a nested onClicklistener. Below is the sample code. Kept layout as simple just to test.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test, container, false);
view.findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.dialog_view);
dialog.findViewById(R.id.dialog_btn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Dialog btn clicked", Toast.LENGTH_LONG).show();
}
});
dialog.show();
}
});
return view;
}
fragment_test.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=".TestActivityFragment">
<Button
android:id="#+id/btn1"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="btn1"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/btn2"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:text="btn2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#id/btn1" />
</android.support.constraint.ConstraintLayout>
dialog_view.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">
<Button
android:id="#+id/dialog_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Dialog BTn" />
</android.support.constraint.ConstraintLayout>
Related
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.
This question already has answers here:
findViewById in Fragment
(37 answers)
Closed 6 years ago.
I'm making an android app and I have a button that won't react when I press it. The button is supposed to bring up an alertdialog box. I'm very confused as I have an OnClickListener and the dialog box is instantiated.
Here is the code from the Java file:
public class tab1Expenses extends Fragment {
Button btnEx;
public class button extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab1expense);
btnEx = (Button)findViewById(R.id.btnEx);
btnEx.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
View view = LayoutInflater.from(button.this).inflate(R.layout.add_ex, null);
AlertDialog.Builder add = new AlertDialog.Builder(button.this);
add.setView(view);
add.setCancelable(true)
.setTitle("Enter Expense:")
.setMessage("Expense Name:")
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
Dialog dialog = add.create();
dialog.show();
}
});
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1expense, container, false);
return rootView;
}
}
And here is my XML file that is related to the java file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ojemz.expensetracker.tab1Expenses$button"
android:background="#android:color/darker_gray">
<Button
android:text="Add Expense"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnEx"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:width="800dp"
android:textAppearance="#style/TextAppearance.AppCompat.Widget.Switch"
android:background="#android:color/black"
android:textColor="#android:color/holo_green_light" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="17dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<!-- TextView and other stuff -->
</LinearLayout>
</ScrollView>
You're doing it wrong!
The button class extending Activity has no reason to exist here.
If you simply want to get some onClick callbacks just do the following:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1expense, container, false);
btnEx = (Button)rootView.findViewById(R.id.btnEx);
btnEx.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
View view = LayoutInflater.from(button.this).inflate(R.layout.add_ex, null);
AlertDialog.Builder add = new AlertDialog.Builder(tab1Expenses.this.getActivity());
add.setView(view);
add.setCancelable(true)
.setTitle("Enter Expense:")
.setMessage("Expense Name:")
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
Dialog dialog = add.create();
dialog.show();
}
});
return rootView;
}
Don't forget to remove your "button" inner class.
Side note
You should rename your tab1Expenses Fragment class to Tab1Expenses in order to distinguish between instances and classes.
Please refer to Java naming conversions.
i have some problems with my layout, this is the capture of my layout inflater
the layout is to big and the button are in wrong place, i don't use a title but there is a black title background in there
i just want to make it smaller like piano tiles layout
can anyone help me to fix this?
this is my layout.xml data that will show inflater layout in menu.java
<?xml version='1.0' encoding='utf-8'?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:background="#drawable/backgroundblankwhite"
android:gravity="center|center_horizontal|center_vertical"
android:orientation="vertical"
android:padding="10sp" >
<TextView
android:id="#+id/exitimage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/textinflateexit"
android:singleLine="true" >
<requestFocus />
</TextView>
<LinearLayout
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center" >
<Button
android:id="#+id/buttonexityes"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:background="#drawable/buttonquityes" />
<Button
android:id="#+id/buttonexitno"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:background="#drawable/buttonquitno" />
</LinearLayout>
</LinearLayout>
and this is my menu.java that have a button to display my inflate layout
public class menu extends Activity {
private Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.menu);
Button exit = (Button) findViewById(R.id.exit);
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
final Dialog openDialog = new Dialog(context);
openDialog.setContentView(R.layout.inflatequitapp);
TextView dialogTextContent = (TextView)openDialog.findViewById(R.id.exitimage);
Button dialogExitButton = (Button)openDialog.findViewById(R.id.buttonexityes);
dialogExitButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// if this button is clicked, close
// current activity
menu.this.finish();
}
});
Button dialogCloseButton = (Button)openDialog.findViewById(R.id.buttonexitno);
dialogCloseButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
openDialog.dismiss();
}
});
openDialog.show();
}
});
}
#Override
public void onBackPressed() {
// do nothing.
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
I have change a bit variable to check at my end..please do change variables,class to match at your end...
MainActivity.java
///---////
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
Button exit = (Button) findViewById(R.id.but);
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
final Dialog openDialog = new Dialog(MainActivity.this);
openDialog.setContentView(R.layout.main);
openDialog.setTitle("Confirm Exit");
TextView dialogTextContent = (TextView)openDialog.findViewById(R.id.exitimage);
Button dialogExitButton = (Button)openDialog.findViewById(R.id.buttonexityes);
dialogExitButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
finish();
}
});
Button dialogCloseButton = (Button)openDialog.findViewById(R.id.buttonexitno);
dialogCloseButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
openDialog.dismiss();
}
});
openDialog.show();
}
});
}
Dialog xml file..
<?xml version='1.0' encoding='utf-8'?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:background="#ffffff"
android:gravity="center|center_horizontal|center_vertical"
android:orientation="vertical"
android:padding="10sp" >
<TextView
android:id="#+id/exitimage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ffffff"
android:singleLine="true"
android:text="Are You Sure!!" >
<requestFocus />
</TextView>
<LinearLayout
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center" >
<Button
android:id="#+id/buttonexityes"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:background="#ffffff"
android:text="Yes" />
<Button
android:id="#+id/buttonexitno"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:background="#ffffff"
android:text="No" />
</LinearLayout>
</LinearLayout>
output:
you have to used below code for dialog
private void forgotPasswordDialog() {
LayoutInflater layoutInflater = LayoutInflater.from(this);
final View dialogView = layoutInflater.inflate(R.layout.dialog_forgot_password, null);
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.PauseDialog);
final AlertDialog dialog = builder.create();
dialog.setView(dialogView);
dialog.show();
final EditText edtUserNameDialog = (EditText) dialogView.findViewById(R.id.edtUserNameDialog);
edtUserNameDialog.setText(edtUserName.getText());
final Button btnSubmit = (Button) dialogView.findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!FieldsValidator.validateUsername(edtUserNameDialog)) {
//forgotPasswordDialog();
} else if (!checkDMSID()) {
KeyboardUtils.hideKeyboard(edtUserNameDialog);
dialog.dismiss();
} else {
KeyboardUtils.hideKeyboard(edtUserNameDialog);
forgotPassword(edtUserNameDialog.getText().toString());
dialog.dismiss();
}
}
});
final Button btnCancel = (Button) dialogView.findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
KeyboardUtils.hideKeyboard(edtUserNameDialog);
dialog.dismiss();
}
});
}
I have two fragments. In the first one, I have a button and I would like to change to another fragment by clicking button.
Here is my code:
FirstFragment
public class FirstFragement extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View ios = inflater.inflate(R.layout.activity_annuncio, container, false);
Button bottAnn = (Button) ios.findViewById(R.id.bNuovoAnnuncio);
bottAnn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
return ios;
}
}
the Firstxml code:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<Button
android:id="#+id/bNuovoAnnuncio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nuovo Annuncio"
android:background="#drawable/button"
android:textColor="#ffffff"
android:layout_marginTop="5dp"/>
<ListView
android:id="#+id/listView1"
android:layout_width="294dp"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
</ScrollView>
SECOND FRAGMENT
public class SecondFragement extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View ios = inflater.inflate(R.layout.activity_annuncio, container, false);
return ios;
}
}
the Secondxml code:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<ListView
android:id="#+id/listView1"
android:layout_width="294dp"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
</ScrollView>
How I can solve it?
You have to replace your new fragment in existing container.
Try this, in first fragment :
Button bottAnn = (Button) ios.findViewById(R.id.bNuovoAnnuncio);
bottAnn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SecondFragement frag = new SecondFragement();
getActivity().getFragmentManager().beginTransaction().replace(//Your container, frag).commit();
}
});
TextView textView_paydetails;
FragmentManager fragmentManager_payment;
Button button_placeorder;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_paymentdetails,
container, false);
textView_paydetails = (TextView) view.findViewById(R.id.txtsdid);
button_placeorder = (Button) view.findViewById(R.id.btnponid);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
fragmentManager_payment = getFragmentManager();
textView_paydetails.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/* // TODO Auto-generated method stub
PaymentShipping payment_shipping = new PaymentShipping();
FragmentTransaction fragmentTransaction = fragmentManager_payment
.beginTransaction();
// Locate Position
fragmentTransaction.replace(R.id.fsp, payment_shipping, "A");
fragmentTransaction.commit();*/
}
});
button_placeorder.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SecondFragement payment_shippingmethod = new SecondFragement();
FragmentTransaction fragmentTransaction = fragmentManager_payment
.beginTransaction();
// Locate Position
fragmentTransaction.replace(R.id.fsp, payment_shippingmethod,
"A");
//fragmentTransaction.addToBackStack("A");
fragmentTransaction.commit();
}
});
}
I'm trying to use setRetainInstance() but it seems not working for me! =(.
I simplified the problem to the easiest version:
I have a fragment with a TextView and a Button.
The initial text of the TextView is "I'm waiting" when the button is pressed the text changes to "Hello!"
That is my code:
The fragment:
public class SayHelloFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.say_hello_layout, container);
final TextView text = (TextView) view.findViewById(R.id.textView1);
view.findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text.setText("Hello!");
}
});
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}
}
The Activity:
public class MainActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
The activity's layout:
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/say_hello_fragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.example.retaintext.SayHelloFragment" />
The Fragment's layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I'm Waiting"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
But when I play it, press the button and change the device's orientation the text becomes reset.
What am I missing? How can I solve it? Thanks!
You are missing that onCreateView runs after the rotation again and inflates the default view with the default text again.
You need to restore the state of your views manually, e.g.:
public class SayHelloFragment extends Fragment {
private String mText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.say_hello_layout, container);
final TextView text = (TextView) view.findViewById(R.id.textView1);
if (mText != null)
text.setText(mText);
view.findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mText = "Hello!";
text.setText(mText);
}
});
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}
}