Adding a webview programmatically - java

I have had no trouble adding a web view to my layout on click with a button, but when it comes to adding a web view on create of my main activity it just does nothing. I need the program to create certain web views based on data stored when I run it. It just really gets me that the same exact code runs perfectly when I put it inside an onClick button, but in the main method it does absolutely nothing. No error, no anything.
tickerLinearLayout = (LinearLayout) findViewById(R.id.TickerLinearLayout);
currency = new WebView(this);
currency.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, btcUp.getMeasuredHeight()));
tickerLinearLayout.addView(currency);
currency.getSettings().setJavaScriptEnabled(true);
disableScroll(currency);
currency.loadUrl("file:///android_asset/btc.html");

To create a Webview programatically in an Activity, you will first have to add your Webview into a RelativeLayout. I am choosing a RelativeLayout because my use case needs the Webview to be positioned on different locations on the Parent View time to time.
public class CustomRelativeLayout extends RelativeLayout {
private WebView mWebView;
public CustomRelativeLayout(Context context) {
super(context);
mWebView = new WebView(context);
mWebView.setId(View.NO_ID);
mWebView.setScrollContainer(false);
mWebView.loadData("<html><body>TEST</body></html>", "text/html", "utf-8");
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
context.getResources().getDisplayMetrics().widthPixels, context.getResources().getDisplayMetrics().heightPixels);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
mWebView.setLayoutParams(params);
addView(mWebView);
}
public WebView getTheWebView() {
return mWebView;
}
}
You can modify the CustomRelativeLayout class to accept URL.
In your MainActivity class, you will have to add a new instance of CustomRelativeLayout and add it to the contentView as shown below:
setContentView(new CustomRelativeLayout(this));
To make adjustments to the size of the webview play around with the width and height of the LayoutParams added to the Webview.
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
<width>, <height>);

Related

How to change ImageView in fragment from pop up window class?

I want to change the ImageView in my fragment's xml when I click on an Image from a pop up window class.
Pop Up class
public class MoodPopUp extends Activity {
ImageView a,b,c,d,e,f,g,h,i;
ImageView main;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mood_picker_popup);
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int width = displayMetrics.widthPixels;
int height = displayMetrics.heightPixels;
//Pop Up Window Size
getWindow().setLayout((int) (width*.8),(int)(height*.6));
//Set emoji images on mood imageview
//Main Mood Image View
main = (ImageView) findViewById(R.id.MainMoodimageview);
//Pop Up Picker on Click
a = (ImageView) findViewById(R.id.Aemoji);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
main.setImageResource(R.drawable.smiling);
}
});
}
This is the imageview from another fragment I want to change upon click.
<ImageView
android:id="#+id/MainMoodimageview"
android:layout_width="187dp"
android:layout_height="163dp"
android:layout_marginTop="19dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/divider3"
android:src="#drawable/ic_baseline_emoji_emotions_24" />
Welcome to Stack Overflow, #Enzo.
There are a few ways to accomplish what you want.
A traditional way to accomplish this is to use an interface in a dialog fragment.
Some ideas are in this question and set of answers
Callback to a Fragment from a DialogFragment
Another solution would be to use a shared ViewModel. Your picker can set the Drawable and you can use it in your other activity.
https://developer.android.com/topic/libraries/architecture/viewmodel
https://developer.android.com/codelabs/kotlin-android-training-view-model#0
The important part if you go the ViewModel route is to make sure that your two activities or fragments, etc, share the same scope.
Another easy way to accomplish this is to use a Singleton or a Kotlin object. This works well if you only every want one instance that all will read and write to.
https://kotlinlang.org/docs/object-declarations.html#object-declarations

parentActivityName forces onCreate

In my Android manifest, I am specifying a parentActivityName in order to utilise the back button displayed in the activity.
I find this however re-calls onCreate of the previous activity, in which I do several network calls and set up a recycler view widget.
This causes the screen to refresh entirely, I'd like to avoid this and deal with the recyclerview and what new content to display and delete to ensure the user flow is not jolted.
I currently set my application up in onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_container_list);
final SwipeRefreshLayout swiperefreshContainerListRecyclerView = (SwipeRefreshLayout) this.findViewById(R.id.swiperefresh_container_list_recyclerview);
swiperefreshContainerListRecyclerView.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
refreshContainerList();
}
}
);
// Get a handle on our RecyclerView for interactin and setup
containerListRecyclerView = (RecyclerView) findViewById(R.id.container_list_recyclerview);
// Grab a new LayoutManager
containerListLayoutManager = new LinearLayoutManager(this);
// Grab a new adapter
List<ContainerModel> containers = new ArrayList<>();
containerListRecyclerAdapter = new ContainerListRecyclerViewAdapter(containers, this);
// Better performance as the size of our RecyclerView does not change
containerListRecyclerView.setHasFixedSize(true);
// Attach our LayoutManager to our RecyclerView
containerListRecyclerView.setLayoutManager(containerListLayoutManager);
// Wire up adapter for RecyclerView
containerListRecyclerView.setAdapter(containerListRecyclerAdapter);
cAdvisorService = new CAdvisorService();
cAdvisorService.fetchDataFromService(context, containerListRecyclerAdapter);
System.out.println("Running onCreate!");
}
I already have logic within my cAdvisorService to deal with removing and adding items into the RecyclerView.
How do I deal with the fact that onCreate is called each time, forcing new instances of my RecyclerView and cAdvisorService?
There way to achieve this by declaring your parent activity in your Android manifest as
android:launchMode="singleTop"
, see more at: How can I return to a parent activity correctly?

How does setContentView work in android?

I am trying to display a button on my android app but everytime i run the app it crashes. i realise this is because i use setContentView multiple times? I dont understand how it works, and dont understand how i can fix this problem so my button will display. my code is below.
public class MainActivity extends Activity {
Draw draw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
draw = new Draw(this);
draw.setBackgroundColor(Color.BLUE);
setContentView(draw);
LinearLayout l = new LinearLayout(this);
l.setOrientation(LinearLayout.VERTICAL);
setContentView(l);
l.addView(new Draw(this));
//setContentView(R.layout.activity_main);
setUpBlockBtn();
}
private void setUpBlockBtn(){
setContentView(R.layout.activity_main);
Button addBlockButton = (Button)findViewById(R.id.btnBlock);
addBlockButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("DemoButtonApp", "you clicked the button");
//finish();
}
});
}
You try to access Button from android xml layout but you do not set this layout in Activity.
Put you button activity_main.xml and use this button in your activity.
Thanks
You can create one more layout and add Draw and Linear layout to that layout.
Something like this.
LinearLayout l1=new LinearLayout(this);
l1.setOrientation(LinearLayout.VERTICAL);
l1.addView(draw);
l1.addView(l2) // your linearLayout.
setContentView(l1)
Remember you can't use setContentView more than one time.
There should be top layout which includes subview and other layouts and then you can add that layout to your activity.

Android MjpegDemo Modification

I am trying to understand Android MjpegDemo code that I found. This code streams IP camera video to android app. In the original app Mjpeg view takes up an entire screen and doesn't use an activity.xml in the layout dir (which is what I am used to seeing). This is partial code for the MjpegSample.java which loads as main activity. I think I understand that setContentView(mv) and WindowManager.LayoutParams.FLAG_FULLSCREEN is the reason everything fills the screen. Is there a way to work with this type of an Activity and still add other objects, like buttons or backgrounds?
public class MjpegSample extends Activity {
private MjpegView mv;
public void onCreate(Bundle myBundle) {
super.onCreate(myBundle);
String URL = "http://someURL/mjpg/video.mjpg";
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
mv = new MjpegView(this);
setContentView(mv);
mv.setSource(MjpegInputStream.read(URL));
mv.setDisplayMode(MjpegView.SIZE_BEST_FIT);
}
}
Here is a detailed example on how to achieve this. Here, we use a LinearLayout object as the main view content, then we add our View objects to this (I also included an example LinearLayout that is nested inside the main one, to show how you can embed View containers within other View containers):
public class MjpegSample extends Activity {
private MjpegView mv;
private LinearLayout ll1;
private LinearLayout nestedL;
private Button btn1;
private TextView txt1;
public void onCreate(Bundle myBundle) {
super.onCreate(myBundle);
//allow legacy-style network queries on UI thread (in case you compile for Android 3.0+, which do not allow
//network transactions in main UI thread by default)
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
final String URL = "http://someURL/mjpg/video.mjpg";
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
//Create new button programmatically
btn1 = new Button(this);
btn1.setText("Test button 1");
//set so that content is wrapped in its parent container (which will be the nestedL object below)
btn1.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
//Create new TextView programmatically
txt1 = new TextView(this);
txt1.setText("Test text 1");
//set so that content is wrapped in its parent container (which will be the nestedL object below)
txt1.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
//Create new MjpegView programmatically
mv = new MjpegView(this);
//set so that content is wrapped in its parent container (which will be the ll1 object below)
mv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
nestedL = new LinearLayout(this);
nestedL.setOrientation(LinearLayout.HORIZONTAL);
//set so that content is wrapped in its parent container (which will be the ll1 object below)
nestedL.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
//we add btn1 and txt1 in nestedL LinearLayout (they will be ordered horizontally, according to nestedL orientation
//as configured above, and all those widgets will not be stretched either)
nestedL.addView(btn1);
nestedL.addView(txt1);
//create the main LinearLayout widget which will be set as the view content using setContentView(...)
ll1 = new LinearLayout(this);
ll1.setOrientation(LinearLayout.VERTICAL);
//we add the other LinearLayout (horizontal one) on top
ll1.addView(nestedL);
//then we add the video player thing
ll1.addView(mv);
//ll1 is set as the main view for your activity
setContentView(ll1);
mv.setDisplayMode(MjpegView.SIZE_BEST_FIT);
mv.setSource(MjpegInputStream.read(URL));
}
}

How to dynamically add images from server to a linear layout

Hi i am trying to load images from server and add them dynamically into a linearlayout which is inside a scroll view
protected void onPostExecute(ArrayList<RssItem> result) {
Log.i("Async-Example", "onPostExecute Called");
horview = (HorizontalScrollView) aview.findViewById(R.id.homesection);
LinearLayout ll = (LinearLayout) aview.findViewById(R.id.sectionid);
for(int i = 0; i < rssItems.size(); i++){
try{
image = new ImageView(getActivity());
image.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
//text.setText(data.get(position).getTitle());
aview.setTag(rssItems.get(i).getLink());
image.setFocusable(true);
imageLoader.DisplayImage(rssItems.get(i).getLink(), image);
ll.addView(image);
}catch(Exception e) {
}
}
The problem I am facing is: if I am declaring ImageView inside my LinearLayout in xml, then only the last image from the server is added. But if i don't declare the ImageView inside linear layout and instead instantiate and add to it, none of the images from the server replace my actual default icon
You should not add the ImageView with XML inside the LinearLayout, as this will only result in a single view being inflated. Initiating ImageViews on the go as you do should work, but to me it sounds like you are trying to load a list of images fetched from a website, in which case you would normally use a ListView with a custom adapter. There are a lot of tutorials online for this:
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
I think the problem in your code is related to the imageLoader. If you are having problems it, you can always try another one like http://square.github.io/picasso/ and call
Picasso.with(getActivity()).load(rssItems.get(i).getLink()).into(image);

Categories