phone volume key does not affect youtube volume (webview) - android-fragments

I set a webview and load youtube.
the problem is that when I play a video in youtube, my phone volume does not affect the volume of the video playing in youtube.
I have tried with setSreanVolume as you could see in the code snippet, to no avail.
Any suggestion and help will be appreciated
public class FragmentYoutube extends Fragment {
private WebView webView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_youtube, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
webView = view.findViewById(R.id.webview_youtube);
webView.setWebChromeClient(new MyChrome());
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://www.youtube.com");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
if (savedInstanceState==null){
webView.post(new Runnable() {
#Override
public void run() {
webView.loadUrl("https://www.youtube.com");
}
});
}
AudioManager audioManager = (AudioManager) getActivity().getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.FLAG_SHOW_UI, AudioManager.FLAG_PLAY_SOUND);
webView.setOnKeyListener(new View.OnKeyListener() {
#RequiresApi(api = Build.VERSION_CODES.P)
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction()== KeyEvent.ACTION_DOWN){
if (keyCode== KeyEvent.KEYCODE_BACK){
if (webView !=null){
if (webView.canGoBack()){
webView.goBack();
} else {
getActivity().onBackPressed();
}
return true;
}
}
}
return true;
}
});
}
}

Related

Retrieve data from Firebase in Recycler view using fragment take too much time

I am using two fragments in the main activity, In first fragment[FirstFragment] load data from firebase and show in Recycler view, In the second fragment[uploadUserCarInformation] take data from user and store at the firebase,
I am facing a problem when the application starts then first fragment load very quickly and data show but when replace the first fragment from the second fragment and when replacing back from the second fragment to the first fragment then take 4 to 5 minutes to load data from firebase in recyclerView.
Kindly tell me where I modify the code,
Main Activity
public class MainActivity extends AppCompatActivity {
FrameLayout simpleFrameLayout;
TabLayout tabLayout;
Fragment fragment1 = new FirstFragment();
Fragment fragment2 =new SecondFragment();
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the reference of FrameLayout and TabLayout
tabLayout=findViewById(R.id.simpleTabLayout);
simpleFrameLayout = (FrameLayout) findViewById(R.id.simpleFrameLayout);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment1);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
// perform setOnTabSelectedListener event on TabLayout
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
// get the current selected tab's position and replace the fragment accordingly
switch (tab.getPosition()) {
case 0:
tab.getIcon().setColorFilter(null);
fragmentReplace(fragment1,"fragment1");
break;
case 1:
fragmentReplace(fragment2,"fragment2");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
public void fragmentReplace(Fragment fragment,String fragmentName)
{
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
Log.d("Running Fragment",fragmentName+ " is running");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
}
FirstFragment
public class FirstFragment extends Fragment {
private RecyclerView mRecyclerView;
private ImageAdapter mAdapter;
private DatabaseReference mDatabaseRef;
private List<carInformation> mUpload;
View view;
public FirstFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//retrieveAndSendData();
Log.d("Lifecycle","onCreate called");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("Lifecycle","onCreateView called");
view=inflater.inflate(R.layout.fragment_first,container,false);
mRecyclerView=view.findViewById(R.id.recyler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d("Lifecycle","onViewCreate called");
retrieveAndSendData();
}
public void retrieveAndSendData()
{
mUpload=new ArrayList<>();
mDatabaseRef= FirebaseDatabase.getInstance().getReference();
ValueEventListener valueEventListener=new ValueEventListener() {
#Override
//get firebase data using datasnapshot (read data)
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot : dataSnapshot.getChildren())
{
String key = postSnapshot.getKey();
DatabaseReference databaseReference=mDatabaseRef.child(key);
for (DataSnapshot child: postSnapshot.getChildren())
{
String userBookId = child.getKey();
if(userBookId.equals("city") )
{
break;
}
else
{
// Toast.makeText(getActivity(),userBookId,Toast.LENGTH_LONG).show();
databaseReference.child(userBookId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
carInformation userInformationObj=dataSnapshot.getValue(carInformation.class);
mUpload.add(userInformationObj);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
mAdapter = new ImageAdapter(getActivity(),mUpload);
mRecyclerView.setAdapter(mAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(),databaseError.getMessage(),Toast.LENGTH_SHORT).show();
}
};
mDatabaseRef.addValueEventListener(valueEventListener);
}
uploadUserCarInformation
public class uploadUserCarInformation extends Fragment {
View view;
FirebaseAuth firebaseAuth;
DatabaseReference databaseReference;
StorageReference storageReference;
private StorageTask mUploadTask;
ImageView imageView;
static int PICK_IMAGE=1;
Spinner spin;
// mdatabase.push().getkey() -> generate uniqe id
RadioGroup radioGroupCondition,radioGroupTransmission,radioGroupSupported;
RadioButton radioButtonCondition,radioButtonTranmission,radioButtonSupported;
String radioButtonConditionString,radioButtonSupportedString,radioButtonTransmissionString;
Button addCar,signout;
int selectedIdCondition,selectedIdTransmission,selectedIdSupported;
String ownerName,carName,phoneNuberString,countryString;
TextInputLayout name,carNamePlusModel,phoneNumber,country;
carInformation car_Information=new carInformation();
private ProgressBar progressBar;
private Uri imageUri;
String[] bankNames=new String[374];
InputStream in;
int i=0;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view=inflater.inflate(R.layout.upload_user_car_information,container,false);
firebaseAuth=FirebaseAuth.getInstance();
storageReference=FirebaseStorage.getInstance().getReference("uploads");
name=view.findViewById(R.id.textFieldCarOwner);
carNamePlusModel=view.findViewById(R.id.textFieldCarNameModel);
phoneNumber=view.findViewById(R.id.textFieldPhoneNumber2);
addCar=view.findViewById(R.id.addCar);
signout=view.findViewById(R.id.sign_out);
progressBar=view.findViewById(R.id.progress_bar);
// progressBar.getProgressDrawable().setColorFilter(
// Color.RED, android.graphics.PorterDuff.Mode.SRC_IN);
radioGroupCondition=view.findViewById(R.id.radioGroupCarCondtion);
radioGroupSupported=view.findViewById(R.id.radioGroupCarSupport);
radioGroupTransmission=view.findViewById(R.id.radioGroupCarTransmission);
// progressBar=new ProgressBar(getActivity());
spin = view.findViewById(R.id.Countryspinner2);
imageView=(ImageView) view.findViewById(R.id.selectImage);
//imageView.setImageResource(R.drawable.select_image);
try
{
InputStream fr = this.getResources().openRawResource(R.raw.cities);
BufferedReader br = new BufferedReader(new InputStreamReader(fr));
ArrayList<String> lines=new ArrayList<String>();
String currentLine=br.readLine();
while(currentLine!=null)
{
lines.add(currentLine);
currentLine=br.readLine();
}
Collections.sort(lines);
fr.close(); //closes the stream and release the resources
for(String line : lines)
{
bankNames[i]=line;
// System.out.println(line);
i++;
}
}
catch(IOException e)
{
e.printStackTrace();
}
ArrayAdapter<String> aa=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item,bankNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
AdapterView.OnItemSelectedListener listener = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
spin.setOnItemSelectedListener(listener);
spin.setAdapter(aa);
signout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseAuth.signOut();
Fragment fragment = new SecondFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onFileChooser();
}
});
addCar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mUploadTask !=null && mUploadTask.isInProgress())
{
Toast.makeText(getActivity(),"Uploading Task",Toast.LENGTH_SHORT).show();
}
else
{
carImageAndDetailUploading();
}
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null)
{
imageUri = data.getData();
//A powerful image downloading and caching library and get image from library for Android
Picasso.with(getActivity()).load(imageUri).into(imageView);
}
}
private void carImageAndDetailUploading()
{
FirebaseUser user=firebaseAuth.getCurrentUser();
databaseReference= FirebaseDatabase.getInstance().getReference(user.getUid());
selectedIdCondition=radioGroupCondition.getCheckedRadioButtonId();
radioButtonCondition=view.findViewById(selectedIdCondition);
radioButtonConditionString=radioButtonCondition.getText().toString();
selectedIdSupported=radioGroupSupported.getCheckedRadioButtonId();
radioButtonSupported=view.findViewById(selectedIdSupported);
radioButtonSupportedString=radioButtonSupported.getText().toString();
selectedIdTransmission=radioGroupTransmission.getCheckedRadioButtonId();
radioButtonTranmission=view.findViewById(selectedIdTransmission);
radioButtonTransmissionString=radioButtonTranmission.getText().toString();
ownerName=name.getEditText().getText().toString().trim();
carName=carNamePlusModel.getEditText().getText().toString().trim();
phoneNuberString=phoneNumber.getEditText().getText().toString().trim();
countryString=spin.getSelectedItem().toString();
if(TextUtils.isEmpty(ownerName) || TextUtils.isEmpty(carName) || TextUtils.isEmpty(phoneNuberString) || TextUtils.isEmpty(countryString))
{
Toast.makeText(getActivity(),"Please fill the empty fields ",Toast.LENGTH_LONG).show();
return; //return stooping the function to execute further
}
else if(imageUri == null)
{
Toast.makeText(getActivity(),"No file Selected ",Toast.LENGTH_LONG).show();
return;
}
long phone=Long.parseLong(phoneNuberString);
car_Information.setCarName(carName);
car_Information.setOwnerName(ownerName);
car_Information.setUserPhoneNumber(phone);
car_Information.setCountry(countryString);
car_Information.setCarCondtion(radioButtonConditionString);
car_Information.setCarSupported(radioButtonSupportedString);
car_Information.setCarTransmission(radioButtonTransmissionString);
StorageReference fileReference=storageReference.child(System.currentTimeMillis()+ "." + getFileExtension(imageUri));
mUploadTask = fileReference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//below code user can see 100 % progress bar for 5 sec
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setProgress(0);
}
},5000);
String uniqueKey=databaseReference.push().getKey();
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
car_Information.setImageUrl(downloadUrl.toString());
car_Information.setUnique_key(uniqueKey);
// databaseReference.child("car details"+car_Information.getUnique_key());
// databaseReference.child("car details"+car_Information.getUnique_key()).setValue(car_Information);
databaseReference.child(car_Information.getUnique_key());
databaseReference.child(car_Information.getUnique_key()).setValue(car_Information);
Toast.makeText(getActivity(),"Successfully Upload",Toast.LENGTH_SHORT).show();
clear_editText();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress=(100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
progressBar.setProgress((int) progress);
}
});
}
private void onFileChooser()
{
Intent intent =new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent,PICK_IMAGE);
//startActivityForResult(Intent.createChooser(intent,"Select Picture"),PICK_IMAGE);
}
private String getFileExtension(Uri uri)
{
//this method for get file extension
ContentResolver cR=getActivity().getContentResolver();
MimeTypeMap mime=MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void clear_editText()
{
name.getEditText().setText(" ");
carNamePlusModel.getEditText().setText(" ");
phoneNumber.getEditText().setText(" ");
}
}
enter image description here
enter image description here

Delete sharedpreferences on click button fragment

I wanted delete or reset value 0 once user click on reset button ,
here is code which i am using , but seem not be work ..
What wrong I am doing , i am not able to figure out , ..I also tried all way , using google to figure it out , but still stuck.
sharedPreferences = getActivity().getPreferences(1);
sharedPreferences.edit().remove("ccs11").commit();
sharedPreferences.edit().remove("spinner_paneer").commit();
Below is my fragment , on which i am trying to implement .
public PlanFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_gain, container, false);
sharedPreferences = getActivity().getPreferences(1);
String cp1s11=sharedPreferences.getString("cp111", "0");
String cf1s11=sharedPreferences.getString("cf111", "0");
String ccs11=sharedPreferences.getString("cc111", "0");
//Button
btnfinish=(Button)rootView.findViewById(R.id.finish_gain);
btnfinish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sharedPreferences = getActivity().getPreferences(1);
edt = sharedPreferences.edit();
edt.putString("ccs11", pro11.getText().toString());
edt.apply();
Intent intent = new Intent(getActivity(), MainActivity.class);
getActivity().startActivity(intent);
}
});
btnreset=(Button)rootView.findViewById(R.id.reset);
btnreset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sharedPreferences = getActivity().getPreferences(1);
sharedPreferences.edit().remove("ccs11").commit();
sharedPreferences.edit().remove("spinner_paneer").commit();
}
});
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}

Android Code for Refresh Button that destroys and recreates Text MediaPlayer (Hangs)!

viewPager4 Fragment Activities
If I click on the Texts that play short sounds, one after another then after sometimes the mediaplayer hangs and doesn't play any sound. But if I'm able to destroy activity and recreate the same activity with refresh button in Action Bar, I'd be able to click sounds again.
So what to write in the code for R.id.item2?
Or there is any other way that continuous clicking on short sounds by these texts is possible without any hang kind of problem?
Following is the reference code:
public class module1 extends FragmentActivity {
static Context con;
static int length = 0;
ViewPager mViewPager;
SectionsPagerAdapter mSectionsPagerAdapter;
static MediaPlayer mediaplayer, mediaplayert, m;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
con = this;
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mains, menu);
// Just .main into .mains [created new for different behavior of Action Bar]
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.item1) {
Intent in = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.google.com"));
startActivity(in);
}
if (item.getItemId() == R.id.item2) {
//what should i write here? to destroy and recreate the same fragment activity again.
//Problem: After clicking fast on one after another text links, mediaplayert hangs and doesnt play
//Solution: exit app destroy and reopen, then mediaplayer works fine...
//SO, what to write here? kindly help!
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
Fragment ff = new DummySectionFragment1();
switch (arg0) {
case 0:
ff = new DummySectionFragment1();
break;
}
Bundle args = new Bundle();
args.putInt(DummySectionFragment1.ARG_SECTION_NUMBER, arg0 + 1);
ff.setArguments(args);
return ff;
}
#Override
public int getCount() {
return 1;
}
#Override
public CharSequence getPageTitle(int arg0) {
Locale l = Locale.getDefault();
switch (arg0) {
case 0:
return getString(R.string.title_section27).toUpperCase(l);
}
return null;
}
}
public static class DummySectionFragment1 extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.m01set01, container, false);
// Genius Shot by Stupid vIC//
TextView Text = (TextView) rootView.findViewById(R.id.textView2);
Text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mediaplayert = MediaPlayer.create(MainActivity.con,
R.raw.sound1);
mediaplayert.start();
}
});
TextView Text1 = (TextView) rootView.findViewById(R.id.textView4);
Text1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mediaplayert = MediaPlayer.create(MainActivity.con,
R.raw.sound2);
mediaplayert.start();
}
});
TextView Text2 = (TextView) rootView.findViewById(R.id.textView6);
Text2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mediaplayert = MediaPlayer.create(MainActivity.con,
R.raw.sound3);
mediaplayert.start();
}
});
return rootView;
}
}
#Override
protected void onDestroy() {
if (mediaplayert != null) {
mediaplayert.stop();
mediaplayert= null;
}
super.onDestroy();
}
}

Can't change the fragment's TextView on realtime

So I got 2 fragments and an activity. Those 2 fragments are communicating each other via an interface.
Problem is, I can't change the TextView in the second fragment from Activity wih some text from fragment1.
There is the same problem( How to change fragment's textView's text from activity ) but there is no real solution so i thought i should open this.
Fragment 1:
public class test_layout extends Fragment {
DearListener activityCommander;
TextView custom_question_bar, list_number;
String selectedCustomQuestion;
boolean buttonClicked;
Button yiyecekButton;
Context c;
public interface DearListener {
public void getMyText(String theQuestion);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
activityCommander = (DearListener) activity;
Log.i("MYLOG", "onAttach");
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString());
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.new_test_layout, container, false);
//custom_question_bar= (TextView) v.findViewById(R.id.custom_question_bar);
//list_number= (TextView) v.findViewById(R.id.list_number);
yiyecekButton = (Button) v.findViewById(R.id.yiyecekButton);
Log.i("MYLOG", "Button referenced");
yiyecekButton.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v){
Log.i("MYLOG", "onCLickListener Called");
onClickYiyecek(v);
}
}
);
return v;
}
public void onClickYiyecek(View v){
Log.i("MYLOG", "OnClickYiyecek");
activityCommander.getMyText("En sevdiğim yiyecek ne?");
}
public void onClickQuestionReady(View v){
if( custom_question_bar == null)
{
Toast.makeText(c, "Boşluğu doldurmadınız", Toast.LENGTH_SHORT).show();
}
activityCommander.getMyText(custom_question_bar.getText().toString());
}
}
And the Activity:
public class NewTest extends Activity implements test_layout.DearListener {
FragmentManager manager;
test_layout test_layout_frag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_holder);
manager=getFragmentManager();
test_layout_frag = new test_layout();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.the_frame_layout, test_layout_frag);
transaction.commit();
}
#Override
public void getMyText(String theQuestion) {
manager=getFragmentManager();
answer_layout answer_layout_frag = new answer_layout();
answer_layout answer_layout_obj = (answer_layout)getFragmentManager().findFragmentById(R.id.fragment2);
answer_layout_obj.changeText(theQuestion);
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.the_frame_layout, answer_layout_frag);
transaction.commit();
Log.i("MYLOG", "Transaction Called");
//transaction.addToBackStack(null);
}
}
And the second fragment:
public class answer_layout extends Fragment {
TextView yourSelectedQuestion;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.new_answer_layout, container, false);
yourSelectedQuestion= (TextView) v.findViewById(R.id.yourSelectedQuestion);
return v;
}
public void changeText(String a) {
Log.i("MYLOG", "changeText");
Log.i("MYLOG", a);
yourSelectedQuestion.setText(a);
}
}
No exception is given but the TextView in second fragment isn't changing.
Since i didn't write the xml here, I can if its needed. Using FrameLayout and it contains 2 fragments inside it.
In myFragment class write a static method:
public static myFragment newInstance(String txt) {
myFragment myfragment = new myFragment();
Bundle args = new Bundle();
args.putString("TEXT", txt);
myfragment.setArguments(args);
return myfragment;
}
after that in OnCreate method of myFragment class inflate the textView tv and
tv.setText(getArguments().getString("TEXT"));
In main FragmentActivity class do:
myFragment fragment = myFragment.newInstance(textToBeSent);
before replace,
fragmentTransaction.replace(R.id.fr_dynamic, fragment);
fragmentTransaction.commit();

View inside a Fragment isn't destroyable?

i have a problem with the android Fragment class. I already implemented a FragmentStatePagerAdapter etc. Now my problem is the following: I added my own View-class to each "LSDataFragment":
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
mConnection = ((WorkActivity) this.getActivity()).getConnection(args
.getInt(ARG_OBJECT));
rootView = inflater.inflate(R.layout.view_pager, container, false);
mView = new LSDataView(this.getActivity().getApplicationContext(),(WorkActivity) this.getActivity());
update();
return rootView;
}
public void update(){
final RelativeLayout mainLayout = (RelativeLayout) rootView.findViewById(R.id.pagerMainLayout);
final RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
mainLayout.addView(mView, params);
mainLayout.invalidate();
//doesn't work outside the uiThread?!
((WorkActivity) this.getActivity()).runOnUiThread(new Runnable() {
#Override
public void run() {
mainLayout.setBackgroundColor(Color.BLUE);
mainLayout.addView(mView, params);
mainLayout.invalidate();
}
});
}
But when i remove the Fragment from my FragmentStatePagerAdapter, the LSDataView mView is remaining on the screen, and not destroyed (wtf):
for(Connection c : WorkActivity.this.mConnections){
if(c.getHandler() == handler)
WorkActivity.this.mConnections.remove(c);
}
WorkActivity.this.runOnUiThread(new Runnable(){
#Override
public void run() {
mCollectionPagerAdapter.notifyDataSetChanged();
}
});

Resources