I have spinner and webviewer in the same activity. I need the webviewer change when I select item from the spinner. I find the code but i try it and the webviwer not showing anything please help me to find the error in this code.
String:
<string-array name="Ragol">
<item value ="https://www.google.com.eg">link1</item>
<item value ="https://www.facebook.com">link2</item>
<item value ="https://www.riwaya.ml">link3</item>
<item value ="https://cooltext.com/">link4</item>
</string-array>
The Activity code:
<Spinner
android:id="#+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:dropDownSelector="#android:color/darker_gray"
android:dropDownWidth="#android:dimen/thumbnail_width"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="0dp" />
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/darker_gray"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="61dp">
</WebView>
The Java Code
public class WebScreen extends Activity implements OnItemSelectedListener {
String starturl = "http://www.google.com.eg", selected;
Spinner s1;
WebView webView;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_screen);
String sp1 = getIntent().getStringExtra("keyName");
if (sp1.contentEquals("Ragol")) {
s1 = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence>
adapter = ArrayAdapter.createFromResource(this,
R.array.Ragol, R.layout.my_spinner);
adapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(this);
s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
selected = parent.getItemAtPosition(pos).toString();
webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.loadUrl(selected);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
webView.loadUrl(starturl);
}
});
}
}
Related
I want to send data from the dialogfragment to activity by one command inside the button .
//code in dialogfragment
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(context);
ISharedPreferencesEditor editor = prefs.Edit();
editor.PutString("my_data", "some_data");
editor.Apply();
second = new SecondActivity();
String myData = prefs.GetString("my_data", "");
second.txtView.Text = myData; // textview in secondactivity
Dismiss();
According to your description, your need to create Dialogfragment firstly in your project, and load layout in your DialogmentFragment.
public class DialogFragment1: DialogFragment
{
private TextView tv1;
private TextView tv2;
private Button btn1;
public static DialogFragment1 NewInstance(Bundle bundle)
{
DialogFragment1 fragment = new DialogFragment1();
fragment.Arguments = bundle;
return fragment;
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Use this to return your custom view for this Fragment
View view = inflater.Inflate(Resource.Layout.Signuplayout, container, false);
tv1 = view.FindViewById<TextView>(Resource.Id.textView1);
tv2= view.FindViewById<TextView>(Resource.Id.textView2);
btn1 = view.FindViewById<Button>(Resource.Id.button1);
btn1.Click += Btn1_Click;
return view;
}
private void Btn1_Click(object sender, EventArgs e)
{
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(Context);
ISharedPreferencesEditor editor = prefs.Edit();
editor.PutString("my_data", tv1.Text);
editor.Apply();
DialogFragment1 _exportFragment = (DialogFragment1)FragmentManager.FindFragmentByTag("Dialog Fragment");
if (_exportFragment != null)
{
_exportFragment.Dismiss();
}
}
}
The signuplayout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView1"
android:hint="first name"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView2"
android:hint="Pasword"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sign up"
android:id="#+id/button1"/>
</LinearLayout>
Mainactivity.cs:
private Button btn1;
private Button btn2;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
btn1 = FindViewById<Button>(Resource.Id.button1);
btn2 = FindViewById<Button>(Resource.Id.button2);
btn1.Click += Btn1_Click;
btn2.Click += Btn2_Click;
}
private void Btn2_Click(object sender, System.EventArgs e)
{
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(Application.Context);
string myData = prefs.GetString("my_data", "");
}
private void Btn1_Click(object sender, System.EventArgs e)
{
FragmentTransaction transcation = FragmentManager.BeginTransaction();
DialogFragment1 signup = new DialogFragment1();
signup.Show(transcation, "Dialog Fragment");
}
<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">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/button1" android:text="Sign up"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="get data"
android:id="#+id/button2"/>
</LinearLayout>
Clicking first Button in MainLayout to display DialogFragment, then clicking Button in DialogFragment to pass data to activity, finally, clicking the second Button in MainLayout to get data.
This is one sample that you can take a look:
https://github.com/CherryBu/dialogapp
Update:
Adding one public method in Mainactivity.cs to display data:
public void getdata()
{
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(Application.Context);
string myData = prefs.GetString("my_data", "");
Toast.MakeText(Application.Context,myData,ToastLength.Long).Show();
}
Then instantiate one Mainactivity, call getdata method in DialogFragment.cs:
static MainActivity mactivity;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Use this to return your custom view for this Fragment
View view = inflater.Inflate(Resource.Layout.Signuplayout, container, false);
tv1 = view.FindViewById<TextView>(Resource.Id.textView1);
tv2= view.FindViewById<TextView>(Resource.Id.textView2);
btn1 = view.FindViewById<Button>(Resource.Id.button1);
btn1.Click += Btn1_Click;
mactivity = new MainActivity();
return view;
}
private void Btn1_Click(object sender, EventArgs e)
{
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(Context);
ISharedPreferencesEditor editor = prefs.Edit();
editor.PutString("my_data", tv1.Text);
editor.Apply();
DialogFragment1 _exportFragment = (DialogFragment1)FragmentManager.FindFragmentByTag("Dialog Fragment");
if (_exportFragment != null)
{
_exportFragment.Dismiss();
}
mactivity.getdata();
}
i am using xamarin android app template with drawerlayout.i am using webview in app_bar_main.axml. when the activity is launched .it overlaps the appbar and does not show toolbar.my app_bar_main.axml is as follows: i want to show webview but below appbar.the webview is below toolbar but contents of toolbar are hidden.i want contents of toolbar so that i can navigate through toolbar in appbar .app_bar_main.axml .
<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/appBarLayout"
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:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<ProgressBar
android:id="#+id/progressBar"
android:layout_below="#id/toolbar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v4.widget.NestedScrollView
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:layout_gravity="fill_vertical"
android:layout_below="#id/progressBar"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<WebView
android:id="#+id/StoreView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v4.widget.NestedScrollView>
<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"
app:srcCompat="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
the MainActivity.cs code is here.
the app_bar_main.axml is in activity_main.axml as produced by drawerlayout template.
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
Android.Support.V7.Widget.Toolbar toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
FloatingActionButton fab = FindViewById<FloatingActionButton>(Resource.Id.fab);
fab.Click += FabOnClick;
DrawerLayout drawer = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, Resource.String.navigation_drawer_open, Resource.String.navigation_drawer_close);
drawer.AddDrawerListener(toggle);
toggle.SyncState();
NavigationView navigationView = FindViewById<NavigationView>(Resource.Id.nav_view);
navigationView.SetNavigationItemSelectedListener(this);
// start store activity
if (IsOnline() == true)
{
message = "items";
var intent = new Intent(this, typeof(StoreActivity));
intent.PutExtra("Data", "message");
StartActivity(intent);
}
}
```
Here is a simple demo which achieve your function.The main code is as follows:
The activity_main.axml
<?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"
android:orientation="vertical"
android:layout_width="match_parent"
android:fitsSystemWindows="true"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="#33B86C"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:layout_scrollFlags="scroll|enterAlways" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:layout_width="match_parent">
<FrameLayout
android:background="#android:color/holo_purple"
android:id="#+id/content_frame"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_height="match_parent"
android:layout_width="200dp"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/menu" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
MainActivity.cs
public class MainActivity : AppCompatActivity
{
DrawerLayout drawer;
NavigationView navigationView;
private string mDrawerTitle;
private string[] mContentTitles;
Toolbar toolbar;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
mDrawerTitle = this.Title;
mContentTitles= this.Resources.GetStringArray(Resource.Array.contents_array);
toolbar = FindViewById<Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
SupportActionBar.SetDisplayHomeAsUpEnabled(true);
SupportActionBar.SetDisplayShowTitleEnabled(false);
SupportActionBar.SetHomeButtonEnabled(true);
SupportActionBar.SetHomeAsUpIndicator(Resource.Drawable.ic_menu);
// Get our button from the layout resource,
// and attach an event to it
drawer = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);
navigationView = FindViewById<NavigationView>(Resource.Id.nav_view);
if (navigationView != null)
setupDrawerContent(navigationView);
ActionBarDrawerToggle toggle = new MyActionBarDrawerToggle(this, drawer, toolbar, Resource.String.drawer_open, Resource.String.drawer_close);
drawer.AddDrawerListener(toggle);
toggle.SyncState();
if (savedInstanceState == null) //first launch
{
toolbar.Title = mContentTitles[0];
var fragment = WebviewFragment.NewInstance(0);
var fragmentManager = this.FragmentManager;
var ft = fragmentManager.BeginTransaction();
ft.Replace(Resource.Id.content_frame, fragment);
ft.Commit();
}
}
void setupDrawerContent(NavigationView navigationView)
{
navigationView.NavigationItemSelected += (sender, e) => {
int ItemId = e.MenuItem.ItemId;
e.MenuItem.SetChecked(true);
int index = 0;
if (ItemId == Resource.Id.nav_home) {
index = 0;
} else if (ItemId == Resource.Id.nav_messages) {
index = 1;
}
else if (ItemId == Resource.Id.nav_about)
{
index = 2;
}
// update the main content by replacing fragments
var fragment = WebviewFragment.NewInstance(index);
var fragmentManager = this.FragmentManager;
var ft = fragmentManager.BeginTransaction();
ft.Replace(Resource.Id.content_frame, fragment);
ft.Commit();
// update selected item title, then close the drawer
mDrawerTitle = mContentTitles[index];
drawer.CloseDrawers();
};
}
internal class WebviewFragment : Fragment
{
public const string ARG_NUMBER = "planet_number";
public WebviewFragment()
{
// Empty constructor required for fragment subclasses
}
public static Fragment NewInstance(int position)
{
Fragment fragment = new WebviewFragment();
Bundle args = new Bundle();
args.PutInt(WebviewFragment.ARG_NUMBER, position);
fragment.Arguments = args;
return fragment;
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.Inflate(Resource.Layout.fragment_content2, container, false);
var i = this.Arguments.GetInt(ARG_NUMBER);
var url = this.Resources.GetStringArray(Resource.Array.weburls_array)[i];
var title = this.Resources.GetStringArray(Resource.Array.contents_array)[i];
var web_view = rootView.FindViewById<WebView>(Resource.Id.webview);
web_view.Settings.JavaScriptEnabled = true;
web_view.SetWebViewClient(new HelloWebViewClient());
web_view.LoadUrl(url);
this.Activity.Title = title;
return rootView;
}
}
internal class MyActionBarDrawerToggle : ActionBarDrawerToggle
{
MainActivity owner;
public MyActionBarDrawerToggle(MainActivity activity, DrawerLayout layout, Toolbar toolbar, int openRes, int closeRes)
: base(activity, layout, toolbar, openRes, closeRes)
{
owner = activity;
}
public override void OnDrawerClosed(View drawerView)
{
owner.toolbar.Title = owner.Title;
owner.InvalidateOptionsMenu();
}
public override void OnDrawerOpened(View drawerView)
{
owner.toolbar.Title = owner.mDrawerTitle;
owner.InvalidateOptionsMenu();
}
}
}
strings.xml
<resources>
<string name="app_name">DrawLayoutApp</string>
<string name="action_settings">Settings</string>
<string name="drawer_open">Open navigation drawer</string>
<string name="drawer_close">Close navigation drawer</string>
<string-array name="contents_array">
<item>Home</item>
<item>Messages</item>
<item>About</item>
</string-array>
<string-array name="weburls_array">
<item>https://www.google.com/</item>
<item>https://msdn.itellyou.cn/</item>
<item>https://www.baidu.com/</item>
</string-array>
</resources>
menu.xml
<?xml version="1.0" encoding="utf-8" ?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_home"
android:title="Home" />
<item
android:id="#+id/nav_messages"
android:title="Messages" />
<item
android:id="#+id/nav_about"
android:title="About" />
</group>
</menu>
The effect is as follows:
In my test app I disable expansion of AppBarLayout when it is collapsed (by scrolling RecycleView). I do that by adding addOnOffsetChangedListener to AppBarLayout.
However, when I click EditText it expands again but, I do not want it to expand.
How to disable the expansion of AppBarLayout when I click EditText?
I have put the whole code, so that everyone can copy/paste the code, create new project and test this fast.
Here is how the .gif looks
Here is XML code:
<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="400dp"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleTextAppearance="#android:color/transparent"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="#drawable/beachcroatia"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycleView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="?attr/actionBarSize"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<LinearLayout
android:id="#+id/messages_linear_layout"
android:layout_width="match_parent"
android:layout_height="58dp"
android:layout_gravity="bottom"
android:background="#E1F5FE"
android:orientation="horizontal"
tools:layout_editor_absoluteY="453dp">
<EditText
android:id="#+id/editText_messageBox"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:layout_gravity="center"
android:layout_weight="0.85"
android:hint="Enter a message"/>
<ImageView
android:id="#+id/messages_sendArrow"
android:layout_width="0dp"
android:layout_height="30dp"
android:layout_gravity="center"
android:layout_weight="0.15"
android:src="#drawable/ic_send_message_" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
Here is full MainActivity code:
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerChat;
private AdapterChat mAdapterChat;
CollapsingToolbarLayout collapsingToolbarLayout;
AppBarLayout appBarLayout;
ImageView sendMessageImageViewButton;
EditText editTextMessage;
private List<Message> messagesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar);
appBarLayout = findViewById(R.id.app_bar_layout);
sendMessageImageViewButton = findViewById(R.id.messages_sendArrow);
editTextMessage = findViewById(R.id.editText_messageBox);
messagesList = new ArrayList<>();
messagesList.addAll(getMessagesList());
mRecyclerChat = findViewById(R.id.recycleView);
LinearLayoutManager manager = new LinearLayoutManager(this);
mRecyclerChat.setLayoutManager(manager);
mAdapterChat = new AdapterChat(this, messagesList);
mRecyclerChat.setAdapter(mAdapterChat);
//move to the last item in recycleview
mRecyclerChat.getLayoutManager().scrollToPosition(mAdapterChat.getMessagesObekt().size() - 1);
editTextMessage.requestFocus();
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (Math.abs(verticalOffset) == appBarLayout.getTotalScrollRange()) {
// Collapsed
Toast.makeText(MainActivity.this, "Collapsed", Toast.LENGTH_SHORT).show();
// disable expanding
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) collapsingToolbarLayout.getLayoutParams();
params.setScrollFlags(0);
} else if (verticalOffset == 0) {
Toast.makeText(MainActivity.this, "Extend", Toast.LENGTH_SHORT).show();
// Expanded
} else {
// Somewhere in between
}
}
});
//sending new message and updating recycleview
sendMessageImageViewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Message Send", Toast.LENGTH_SHORT).show();
mAdapterChat.updateLastMessage(new Message(editTextMessage.getText().toString()));
editTextMessage.getText().clear();
mRecyclerChat.getLayoutManager().scrollToPosition(mAdapterChat.getMessagesObekt().size() - 1);
}
});
}
//ading some items to a list
private List<Message> getMessagesList() {
List<Message> mMessages = new ArrayList<>();
for (int i = 0; i < 200; i++) {
mMessages.add(new Message("message " + i));
}
return mMessages;
}
}
Here is my message class where i add dummy data to show in RecycleView
public class Message {
private String message;
public Message(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Here is RecycleView Adapter code:
package com.example.petar.collapsingtolbartestiramo;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class AdapterChat extends RecyclerView.Adapter<AdapterChat.ChatHolder> {
private LayoutInflater mInflater;
private List<Message> messagesObekt;
public AdapterChat(Context context, List<Message> listOfMassages) {
mInflater = LayoutInflater.from(context);
messagesObekt = new ArrayList<>();
messagesObekt.addAll(listOfMassages);
notifyDataSetChanged();
}
public void updateChat(List<Message> porukeObjekt){
this.messagesObekt.addAll(porukeObjekt);
notifyDataSetChanged();
}
public void updateLastMessage(Message porukeObjekt) {
this.messagesObekt.add(porukeObjekt);
//notifyDataSetChanged();
notifyItemInserted(messagesObekt.size());
}
public List<Message> getMessagesObekt() {
return messagesObekt;
}
#Override
public ChatHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.list_message, parent, false);
ChatHolder holder = new ChatHolder(view, messagesObekt);
return holder;
}
#Override
public void onBindViewHolder(ChatHolder holder, int position) {
holder.textViewMessage.setText(messagesObekt.get(position).getMessage());
}
#Override
public int getItemCount() {
return messagesObekt.size();
}
public static class ChatHolder extends RecyclerView.ViewHolder {
TextView textViewMessage;
public ChatHolder(View itemView, List<Message> messagesObekt) {
super(itemView);
textViewMessage = itemView.findViewById(R.id.rv_message);
}
}
}
Here is RecycleView item XML code (list_message.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="vertical">
<TextView
android:id="#+id/rv_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Poruka Ovdje"
android:textSize="14sp"/>
</LinearLayout>
:
EDIT
I tried adding focus listener to EditText but, that did not helped. This is how i try:
editTextMessage.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
appBarLayout.setExpanded(false);
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) collapsingToolbarLayout.getLayoutParams();
params.setScrollFlags(0);
}
}
});
I do not know is the best solution, but it works nice. If someone has better solution, feel free to write it.
There is indeed a better, cleaner and simpler solution.
The culprit that leads to this "issue" is actually a feature that was added by Google inside AppBarLayout.ScrollingViewBehavior. That's the one you set via app:layout_behavior="#string/appbar_scrolling_view_behavior". Inside that class, onRequestChildRectangleOnScreen calls setExpanded(false, !immediate) whenever the keyboard is shown. You simply override this method and return false to disable this default behavior. Add this class to your project:
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import com.google.android.material.appbar.AppBarLayout;
public class FixedScrollingViewBehavior extends AppBarLayout.ScrollingViewBehavior {
public FixedScrollingViewBehavior() {
super();
}
public FixedScrollingViewBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onRequestChildRectangleOnScreen(#NonNull CoordinatorLayout parent,
#NonNull View child, #NonNull Rect rectangle, boolean immediate) {
return false;
}
}
Then just use this new class by changing app:layout_behavior="#string/appbar_scrolling_view_behavior" to app:layout_behavior="your.source.package.FixedScrollingViewBehavior".
I have find the answer. I do not know is the best solution, but it works nice. If someone has better solution, feel free to write it.
So, what i done is i put the whole AppBarLayout params to 0 when i click EditText or when EditText get focus.
So, when EditText is clicked, AppBarLayout is still there but, now his height is 0 and it is not visible.
This do the trick:
//Collaps AppBarLayout
public void collapsAppBarLayout(){
CoordinatorLayout.LayoutParams params =(CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
params.height = 0; // setting new param height to 0
//setting params to appbarLayout (now AppBarLayout is 0)
appBarLayout.setLayoutParams(params);
appBarLayout.setExpanded(false);
}
Also, if you want to have expand option, you need to save height of previous params and then just add that height again.
So, this is a code how i done it:
Fist, when i scroll RecycleView i disable expand of appBarLayout using addOnOffsetChangedListener. However i also save params height for future use.
int sizeParams; //save params height
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (Math.abs(verticalOffset) == appBarLayout.getTotalScrollRange()) {
// Collapsed
Toast.makeText(MainActivity.this, "Collapsed", Toast.LENGTH_SHORT).show();
// disable expanding and scroll
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) collapsingToolbarLayout.getLayoutParams();
params.setScrollFlags(0);
//saving height for future use
sizeParams = params.height;
} else if (verticalOffset == 0) {
Toast.makeText(MainActivity.this, "Extend", Toast.LENGTH_SHORT).show();
// Expanded
} else {
// Somewhere in between
}
}
});
Now i make this 2 method which i call when i need expand/collaps.
//Collaps AppBarLayout
public void collapsAppBarLayout(){
CoordinatorLayout.LayoutParams params =(CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
sizeParams = params.height;//save params height for future use
params.height = 0; // setting new param height to 0
//setting params to appbarLayout (now AppBarLayout is 0
appBarLayout.setLayoutParams(params);
appBarLayout.setExpanded(false);
}
//Expand AppBarLayout
public void expandAppBarLayout(){
CoordinatorLayout.LayoutParams params =(CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
params.height = 3*sizeParams; // HEIGHT
appBarLayout.setLayoutParams(params); //add height to appbarlayout
//enable scroll and expand
AppBarLayout.LayoutParams params1 = (AppBarLayout.LayoutParams) collapsingToolbarLayout.getLayoutParams();
params1.setScrollFlags(1);
appBarLayout.setExpanded(true);//expand
}
I have to display the following table:
So I want to know what is the best widget to use for the table. I want the table to be dynamic I mean if I choose some other group from the dropdown the number of items in the table to increase or to decrease and the total price to change depending on what I have in column price. What widget is the best widget to achieve that?
RecyclerView is the best UI control to achieve it. Because RecyclerView is Adapter pattern, so you can use the adapter to achieve dynamic what you have said.
I want the table to be dynamic I mean if I choose some other group from the dropdown the number of items in the table to increase or to decrease and the total price to change depending on what I have in column price
I have made a demo for you, you can test it and do some changes for your project:
Three .axml files:
Main.axml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<Button
android:id="#+id/bt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="group1"/>
<Button
android:id="#+id/bt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="group2"/>
<Button
android:id="#+id/bt3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="group3"
/>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/rv"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
item_layout, every item'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="wrap_content">
<TextView
android:id="#+id/item_tv"
android:layout_width="match_parent"
android:textSize="30dp"
android:layout_height="wrap_content" />
</LinearLayout>
item_layout, total price'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="wrap_content">
<TextView
android:id="#+id/foot_tv"
android:gravity="end"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity:
using Android.App;
using Android.Widget;
using Android.OS;
using System;
using System.Collections.Generic;
using Android.Support.V7.Widget;
using Android.Views;
using Android.Content;
namespace RecycleTest
{
[Activity(Label = "RecycleTest", MainLauncher = true)]
public class MainActivity : Activity
{
RecyclerView mRecyclerView;
MyAdapter adapter;
Button bt1, bt2, bt3;
List<double> list1, list2, list3;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
initView();
initData();
mRecyclerView = FindViewById<RecyclerView>(Resource.Id.rv);
mRecyclerView.SetLayoutManager(new LinearLayoutManager(this));
adapter = new MyAdapter(this, list1);
mRecyclerView.SetAdapter(adapter);
}
private void initData()
{
list1 = new List<double>();
list2 = new List<double>();
list3 = new List<double>();
list1.Add(1.1);
list1.Add(1.2);
list1.Add(1.3);
list2.Add(2.1);
list2.Add(2.2);
list2.Add(2.3);
list2.Add(2.4);
list3.Add(3.1);
list3.Add(3.2);
list3.Add(3.3);
list3.Add(3.4);
list3.Add(3.5);
}
public void initView() {
bt1 = FindViewById<Button>(Resource.Id.bt1);
bt2 = FindViewById<Button>(Resource.Id.bt2);
bt3 = FindViewById<Button>(Resource.Id.bt3);
bt1.Click += Bt1_Click;
bt2.Click += Bt2_Click;
bt3.Click += Bt3_Click;
}
private void Bt3_Click(object sender, System.EventArgs e)
{
adapter.change(list3);
}
private void Bt2_Click(object sender, System.EventArgs e)
{
adapter.change(list2);
}
private void Bt1_Click(object sender, System.EventArgs e)
{
adapter.change(list1);
}
}
class MyViewHolder : RecyclerView.ViewHolder
{
public TextView mtv;
public MyViewHolder(View itemView): base(itemView)
{
mtv = itemView.FindViewById<TextView>(Resource.Id.item_tv);
}
}
class MyFootViewHolder : RecyclerView.ViewHolder
{
public TextView mtv;
public MyFootViewHolder(View itemView):base(itemView)
{
mtv = itemView.FindViewById<TextView>(Resource.Id.foot_tv);
}
}
class MyAdapter :RecyclerView.Adapter{
Context mContext;
List<double> mList=new List<double>();
public override int ItemCount => mList.Count + 1;
public MyAdapter(Context context, List<Double> list)
{
this.mContext = context;
this.mList.AddRange(list);
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
if (GetItemViewType(position) == 0)
{
((MyViewHolder)holder).mtv.Text=(mList[position].ToString());
}
else
{
double price = 0;
for (int i = 0; i < mList.Count; i++)
{
price += mList[i];
}
((MyFootViewHolder)holder).mtv.Text=price + "";
}
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
RecyclerView.ViewHolder holder;
if (viewType == 0)
{
holder = new MyViewHolder(LayoutInflater.From(mContext).Inflate(Resource.Layout.item_layout, parent, false));
}
else
{
holder = new MyFootViewHolder(LayoutInflater.From(mContext).Inflate(Resource.Layout.foot_layout, parent, false));
}
return holder;
}
public override int GetItemViewType(int position)
{
int type;
if (position != mList.Count)
{
type = 0;
}
else
{
type = 1;
}
return type;
}
public void change(List<Double> list1)
{
mList.Clear();
mList.AddRange(list1);
NotifyDataSetChanged();
}
}
}
I have two fragments in my main Activity.
Each fragment should play different youtube video.
But In my code,both the fragments are playing same video although I passes different url to the two instances of YouTubePlayerSupportFragment class.
MainActivity-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VideoFragment f1=VideoFragment.newInstance("kXYiU_JCYtU");
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container1, f1).commit();
VideoFragment f2 = new VideoFragment();
f2=VideoFragment.newInstance("k4V3Mo61fJM");
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container2, f2).commit();
}
activity_main.xml-
<RelativeLayout
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"
tools:context=".MainActivity"
>
<FrameLayout
android:id="#+id/fragment_container1"
android:layout_width="fill_parent"
android:layout_height="150dp"
>
</FrameLayout>
<FrameLayout
android:id="#+id/fragment_container2"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/fragment_container1"
>
</FrameLayout>
</RelativeLayout>
VideoFragment class-
public VideoFragment() { }
public static VideoFragment newInstance(String url) {
VideoFragment f = new VideoFragment();
Bundle b = new Bundle();
b.putString("url", url);
f.setArguments(b);
f.init();
return f;
}
private void init() {
initialize("AIzaSyDM2vaVDpwGGFEcQCcD_hA38ZQo2Tqa06o", new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.cueVideo(getArguments().getString("url"));
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
});
}
I would be grateful if anyone could help me.
Its impossible. Youtube player based on singletone patern, so every time you will get same player