This problem let my brain burst. I got two Fragments, which contain a WebView each. These two Fragments are then placed in a ViewPagerAdapter, an adapter for my ViewPager. This ViewPager is then setup with a TabLayout. In code:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebViewFragment webViewFragment1 = WebViewFragment.newInstance(1);
WebViewFragment webViewFragment2 = WebViewFragment.newInstance(2);
WebViewFragment[] fragments = new WebViewFragment[]
{
webViewFragment1,
webViewFragment2
};
String[] fragmentTitles = new String[]
{
"WebView1",
"WebView2"
};
ViewPager viewPager = (ViewPager)findViewById(R.id.viewPager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager(), fragments, fragmentTitles);
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout)findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
}
This construction let me view the fragments like in e.g WhatsApp(gesture-controlled).
Nonetheless, I want to control the contents of the WebViews in the WebViewFragments in the MainActivty. But I got no idea, how to access the WebViews externally. The two webviews have IDs:
webView1 //and
webView2
When I try them to access with help of the
findViewById(R.id.webView1)
method, I get null as response.
Now, how I can access these views from the MainActivity?
WebViewFragment
private WebView webView;
public onViewCreated(....) {
webView = view.findViewBy(R.id.webview);
....
}
public WebView getWebView() {
return webView;
}
Activity
WebViewFragment webViewFragment1 = WebViewFragment.newInstance(1);
WebView webView = webViewFragment1.getWebView();
webView.... //WebView Stuff
Please make sure that the 2 Fragments are inflated and not Null.
Related
Hey all I am having the worst time trying to get my code top work.
What I am trying to do is call a function in the MainActivity.java from another fragment FragMovies.java that should then unhide the invisible frameLayout which is called videoFrame.
The MainActivity.java has a TabView, ViewPager and the videoFrame.
In my FragMovies.java I have the following code linked to a button:
Button mainButton = (Button) rootView.findViewById(R.id.button0);
mainButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
MainActivity MA = new MainActivity();
MA.VidStart("thelostegg");
}
});
The onClick event then calls the function VidStart that's on the MainActiviy.java.
The vidStart function looks like this that's inside the MainActivity.java as well as the onCreate function:
public class MainActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
FrameLayout frameLayout;
PagerAdapter pagerAdapter;
private Object videoPlay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getViews();
//adapter setup
pagerAdapter = new com.example.telluridetainment.PagerAdapter(getSupportFragmentManager());
//attaching fragments to adapter
pagerAdapter.addFragment(new FragMovies(),"Movies");
pagerAdapter.addFragment(new FragShows(),"Shows");
viewPager.setOffscreenPageLimit(2);
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager);
//setting icons
tabLayout.getTabAt(0).setIcon(R.drawable.ic_movie_white_24dp);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_movie_white_24dp);
}
public void VidStart(String theMP4) {
videoPlay myfragment = new videoPlay();
FragmentTransaction fragmentManager = getSupportFragmentManager().beginTransaction();
fragmentManager.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
frameLayout = findViewById(R.id.videoFrame);
frameLayout.setVisibility(View.VISIBLE);
fragmentManager.replace(R.id.videoFrame, myfragment).commit();
}
Everything goes fine until it gets the this line:
frameLayout = findViewById(R.id.videoFrame);
and my app crashes...
If I comment out that part of the code then it crashes on the
fragmentManager.replace(R.id.videoFrame, myfragment).commit();
BUT only caling the function from the other fragment. If I put the function call in the MainActivity.java onCreate function then it loads up the video and I can hear my video playing but of course can not see it due to the videoFrame still not visible.
The MainActivity XML:
The fragMovies XML (that's inside the MainActivity viewPager):
The _fragvideoplay XML (Called from the VideoPlay.java):
Basically I am looking to fix the calling of the function from another fragment (class) and have it work like it does being called within it's own class.
I'm sure I'm going about this all wrong. Any help would be great!
I have made image slider using viewPager and picasso. Images are loaded from my own(raw). I've put share button below image.
I want to make specific image be shared using share intent. I mean, if I'm in image of position 3 then only image of position 3 should be shared.
Activity where image slider is shown:
public class RajeshDaiActivity extends AppCompatActivity{
ViewPager viewPager;
private int[] imageUrls = new int[]{
R.drawable.oq,
R.drawable.oqqqq,
R.drawable.opt3
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rajesh_dai);
viewPager = findViewById(R.id.view_pager);
ViewPageAdapter adapter = new ViewPageAdapter(this, imageUrls);
viewPager.setAdapter(adapter);
ImageView ShareButton = findViewById(R.id.share);
ShareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent share = new Intent("android.intent.action.SEND");
//?? how??
}
});
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
}
From the code posted above, it looks like you need to implement an interface and capture the click event of the particular image and implement the logic for redirection in overridden implementation of the particular function in your fragment class. Hope this clarifies your question.
I have an Activity which has 5 fragments in pager. I used
viewPager.setOffscreenPageLimit(fragmentList.size());
to be able to create all fragment in one time
I also have a listener which will pass parameter(object) to all fragment once I have a newIntent.
in one of my fragment I have CheckBox which should be selected according to the parameter from activity.
and other views which I were able to change the value of their texts and background.
just this check box I have set it on But when I see it, I have see it is off, all other events works well.
here is the activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.AppTheme_PopupOverlay);
setContentView(R.layout.activity_configurations);
ViewPager viewPager = findViewById(R.id.container);
TabLayout tabLayout = findViewById(R.id.tabs);
setNdef(getIntent().getExtras());
String type = getNdef().getString("id");
List<Fragment> fragmentList = createFragments(type);
SectionsPagerAdapter pagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), fragmentList);
viewPager.setAdapter(pagerAdapter);
fillTableLayout(tabLayout, type);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
viewPager.setOffscreenPageLimit(fragmentList.size());
readNfcDialog = createReadDialog();
writeNfcDialog = createWriteDialog();
readNfcDialog.show();
setForeground();
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
ClassNfcTag wepTag = new ClassNfcTag(intent);
String type = wepTag.defineClassTag();
OmsRepeaterTag omsRepeaterTag = new OmsRepeaterTag(intent);
byteMap = omsRepeaterTag.readTag();
if (byteMap != null) {
setTagOmsConfiguration(OmsConfiguration.fromByteArray(byteMap));
for (OmsListener listener : onReceiveOmsList) {
listener.gotOms(getInTagOmsConfiguration());
}
}
}
and here is one of the fragments
#Override
public void gotOms(OmsConfiguration configuration) {
setConfiguration(configuration);
if (isAdded()) {
boolean status = getConfiguration().getDeleteRsl();
delete.setChecked(status);
delete.setSelected(status);
}
}
as a solution I have tried to use Switch instead of CheckBox and it worked well.
and I also tried to set the pager to start from exactly the fragment which has the CheckBox and it also work.
viewPager.setCurrentItem(checkBoxFragmentPosition);
I also tried to debug the code and It shows me that the checkBox is checked and when I tried to change it to checked by touching it (programmatically it is checked, in UI I see it unchecked) it change itself from unchecked to unchecked .and then with the next touch changed to checked.
just for the people who will read this question, simply this was an unresolved bug in android.
For my case I used an toggleButton instead checkBox.
first off I apologize if a similar question has already been asked and answered, but I have looked through tons of posts without any luck. Second, I am an absolute beginner (been coding for 6 weeks), so if I'm missing some concepts or if there is a better way to do things, feel free to enlighten me.
Now, here is my question:
On my MainActivity, I have an EventsFragment which has a ListView. There is also a FloatingActionBar on the MainActivity, which when clicked loads another Activity called CreateEventActivity. The CreateEventActivity has an EditText field and a Create Button. What I wanna do is when the User enters some text in the EditText field and clicks the create Button, it should take the string from the EditText field and create an item on the ListView with String as it's name. Also, as soon as the create button is clicked, it should go back to the EventsFragment in the MainActivity.
I used startActivityForResults(), as suggested and it seems that I am able to pass an ArrayList as an intent from CreateEventActivity back to MainActivity, and that is as far as I'm able to get. I think the way I'm sending the list to the EventsFragment is wrong, as the listView is not updating.
MainActivity -
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), MainActivity.this);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
//Iterate over all TabLayouts to set the custom View
for (int i = 0; i < tabLayout.getTabCount(); i++){
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(mSectionsPagerAdapter.getTabView(i));
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadCreateEventActivity();
// Snackbar.make(view, "Here the create a New Event Screen will be displayed", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
}
});
}
private void loadCreateEventActivity(){
Intent intent = new Intent(MainActivity.this, CreateEventActivity.class);
startActivityForResult(intent, 2);
}
public ArrayList<String>list = new ArrayList<>();
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2){
if (resultCode == RESULT_OK) {
list = data.getStringArrayListExtra("LIST_ITEMS");
}
}
}
public ArrayList<String> getList() {
return list;
}
CreatEventsActivity -
public class CreateEventActivity extends AppCompatActivity {
EditText createEventName;
Button createButton;
ArrayList<String> listItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_event);
createEventName = (EditText) findViewById(R.id.createEventName);
createButton = (Button) findViewById(R.id.createButton);
listItems = new ArrayList<String>();
listItems.add("First Item - added on Activity Create");
createButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
listItems.add(createEventName.getText().toString());
Intent intent = new Intent();
intent.putStringArrayListExtra("LIST_ITEMS", listItems);
setResult(RESULT_OK, intent);
createEventName.setText("");
finish();
}
});
}
}
EventsFragment -
public class EventsFragment extends Fragment {
public EventsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_events, container, false);
MainActivity mainActivity = (MainActivity) getActivity();
ArrayList<String>list = mainActivity.getList();
ListView listView = (ListView)view.findViewById(R.id.list_view);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return view;
}
}
Thanks for any help in advance :)
Solution 1 :
You need to have one data set, that is common to both activities.
Every time you click, you add add an item to that data set.
The list view is populated using that very same data set.
Since they are both in different activities, you need to persist that data set.
You can persist it locally, by storing it using a table(database) or as a json string, in [shared preference][1].
Another short cut to persist the data set is to have your data set as a property in your Application class, so you can add and access the dataSet from any activity in the app, as the application class is alive for the entire lifecycle of the app.
I DON'T RECOMMEND THIS. This is easy and it works, but it is not good practice and leads to terrible code quality, but if you just want a quick way to do it, you can do it.
Solution 2 : In your main activity, start the second activity using startActivityForResult(). What this will let you do is let second activity talk back to the first one. So when it talks back, you can know in the first one, how many items were added in the second one and update your first activity's listView accordingly.
I have a tabbed activity as shown below. I need to call a MapsActivity inside first tab("Search") which extends FragmentActivity. Any help in resolving this would help.
public class TabbedActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabbed);
TabHost tab = (TabHost) findViewById(R.id.tabHost);
tab.setup();
TabHost.TabSpec spec1 = tab.newTabSpec("Search");
spec1.setIndicator("Search");
spec1.setContent(R.id.layout1);
tab.addTab(spec1);
TabHost.TabSpec spec2 = tab.newTabSpec("Settings");
spec2.setIndicator("Settings");
spec2.setContent(R.id.layout2);
tab.addTab(spec2);
}
}
Tried this solution, but shows error "MapsActivity is not an enclosing class"
tab.addTab(tab.newTabSpec("Search")
.setIndicator("Search")
.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return new TextView(MapsActivity.this);
}
}));
Activities-in-tabs has been deprecated as a technique for nearly six years.
Do something else, such as:
FragmentTabHost, with fragments for your tabs, such as MapFragment
ViewPager, with fragments for pages (MapFragment, SupportMapFragment) and a tabbed indicator (TabLayout, PagerTabStrip, etc.)