How to get Position & View information through onclick Binding Adapter implemented with ViewModel? - mvvm

I want to use Data Binding Library & ViewModel
to identify position of clicked item in List.
To know on which view the click happened so that I can trigger different Intent.
Here is my XML file (Currently onclick is on RelativeLayout)
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="orgmembvm"
type="com.support.android.designlibdemo.include.OrgMemb" />
<variable name="orgmembhandlers"
type="com.support.android.designlibdemo.View.MyOrgMembHandlers"/>
</data>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp">
<RelativeLayout
android:id="#+id/org_memb_rec"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:onClick="#{orgmembhandlers::onClickOpenEditRec}"
android:padding="8dp">
//Inner Child element
</RelativeLayout>
BindViewHolder of Adaptor
#Override
public void onBindViewHolder(#NonNull OrgMembViewHolder holder, int
position) {
holder.mBinding.setOrgmembvm(orgMembArrayList.get(position));
holder.mBinding.setOrgmembhandlers(new MyOrgMembHandlers());
holder.mBinding.executePendingBindings();
}
Code in Activity Class for getting viewModel attached to Activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
......
......
userModel = ViewModelProviders.of(this).get(OrgMembViewModel.class);
userModel.getAllLive().observe(this, orgMembList -> {
mAdapter.updateorgmemblist(orgMembList);
});
}
How can this be achieved?

1. Take position variable in layout
<variable
name="position"
type="int"/>
2. set position from adapter
#Override
public void onBindViewHolder(#NonNull OrgMembViewHolder holder, int position) {
holder.mBinding.setPosition(position);
}
3. Put int position in onClickOpenEditRec param
public class MyOrgMembHandler {
public void onClickOpenEditRec(int position) {
}
}
4. Pass position from layout
android:onClick="#{()->orgmembhandlers.onClickOpenEditRec(position)}"
Check this answer to see ways of setting click in data binding.

Related

Displaying Navigation drawer in all activities problem

I'm making a navigation drawer with different activities and i want to display the same navigation drawer in all activities , i take the same code and put it in all activities but when i click on the activities my app crashes all the time i don't know why
Try below code for displaying Navigation drawer on all activity, hope this example help...!
BaseActivity
public class BaseActivity extends AppCompatActivity {
ArrayList<String> menuList;
protected FrameLayout frameLayout;
protected ListView mDrawerList;
protected static int position;
private static boolean isLaunch = true;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
#SuppressLint("ResourceAsColor")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.navigation_drawer_base_layout);
prepareListItems();
frameLayout = findViewById(R.id.content_frame);
mDrawerLayout = findViewById(R.id.drawer_layout);
mDrawerList = findViewById(R.id.left_drawer);
View header = getLayoutInflater().inflate(R.layout.header, null);
mDrawerList.addHeaderView(header);
mDrawerList.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_list_item, menuList));
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
openActivity(position);
}
});
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.menu);
actionBarDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.mipmap.ic_launcher_round, /* nav drawer image to replace 'Up' caret */
R.string.open_drawer, /* "open drawer" description for accessibility */
R.string.close_drawer) /* "close drawer" description for accessibility */ {
#Override
public void onDrawerClosed(View drawerView) {
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
Objects.requireNonNull(getSupportActionBar()).setTitle(getString(R.string.app_name));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
}
#Override
public void onDrawerStateChanged(int newState) {
super.onDrawerStateChanged(newState);
}
};
mDrawerLayout.setDrawerListener(actionBarDrawerToggle);
if (isLaunch) {
isLaunch = false;
openActivity(1);
}
}
private void prepareListItems() {
menuList = new ArrayList<>();
menuList.add(" Activity1 ");
menuList.add(" Activity2 ");
menuList.add(" Activity3 ");
menuList.add(" Activity4 ");
}
/**
* #param position Launching activity when any list item is clicked.
*/
protected void openActivity(int position) {
mDrawerList.setItemChecked(position - 1, true);
mDrawerLayout.closeDrawer(mDrawerList);
BaseActivity.position = position; //Setting currently selected position in this field so that it will be available in our child activities.
switch (position) {
case 0:
break;
case 1:
startActivity(new Intent(this, Activity1.class));
break;
case 2:
startActivity(new Intent(this, Activity2.class));
break;
case 3:
startActivity(new Intent(this, Activity3.class));
break;
case 4:
startActivity(new Intent(this, Activity4.class));
break;
default:
break;
}
// Toast.makeText(this, "Selected Item Position::" + position, Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
}
Activity1
public class Activity1 extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.activity_main, frameLayout);
mDrawerList.setItemChecked(position, true);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
navigation_drawer_base_layout
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#drawable/simple_brushed_metal"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</androidx.drawerlayout.widget.DrawerLayout>
header
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/shade">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:fontFamily="serif"
android:gravity="center"
android:text="#string/app_name"
android:textColor="#color/textColorPrimary"
android:textSize="18sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/developed_by_nd_software_solution"
android:textColor="#color/textColorPrimary"
android:textSize="12sp" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="8dp"
android:background="#color/textColorPrimary" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
drawer_list_item
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/activatedBackgroundIndicator"
android:fontFamily="serif"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textColor="#color/textColorPrimary" />
activity_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:fontFamily="serif"
android:gravity="center"
android:text="#string/app_name"
android:textColor="#color/textColorPrimary"
android:textSize="18sp" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here I have provided code for one activity (Activity1), write code for other activities like Activity2, Activity3 etc.

TextView and Button in a row of listview xamarin c#

I have a listview in which I have a textview, an image and a button in a row in Xamarin using c#. by clicking on button I need to open a new layout:
this is axml for listview: called "Friends"
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minWidth="25px"
android:minHeight="25px">
<ListView
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="378.2dp"
android:id="#+id/listView1" />
</LinearLayout>
this is axml for each row in listview: called "Row1"
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minWidth="25px"
android:minHeight="25px">
<LinearLayout
android:orientation="horizontal"
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="81.1dp"
android:id="#+id/linearLayout1">
<ImageView
android:src="#drawable/Icon"
android:layout_width="91.7dp"
android:layout_height="match_parent"
android:id="#+id/imageView5" />
<TextView
android:text="Text"
android:layout_width="184.9dp"
android:layout_height="35.6dp"
android:id="#+id/textView1"
android:gravity="center"
android:textSize="20dp" />
<Button
android:text="Chat"
android:layout_width="62.3dp"
android:layout_height="37.8dp"
android:id="#+id/chat1"
android:layout_marginTop="32dp" />
</LinearLayout>
</LinearLayout>
and this is the activity for listview: called "FriendsActivity"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace EJIK_Network
{
[Activity (Label = "FriendsActivity")]
public class FriendsActivity : Activity
{
ListView listview;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Friends);
listview = FindViewById<ListView> (Resource.Id.listView1);
View rootInAnotherLayout = this.LayoutInflater.Inflate (Resource.Layout.Row1,null);
Button chat = rootInAnotherLayout.FindViewById<Button> (Resource.Id.chat1);
chat.Click += (sender, e) => {
var CA = new Intent(this, typeof(ChatingActivity));
StartActivity (CA);
};
}
}
}
The cod run but when I clicked on chat button it didn't open the new layout wich I defined in "ChatingActivity"??????
You have to create a Custom Adapter and inside the GetView method:
public override View GetView(int position, View convertView, ViewGroup parent) {
var view = (convertView ??
this._context.LayoutInflater.Inflate(
Resource.Layout.Row1,
parent,
false)) as LinearLayout;
Button chat = view.FindViewById<Button> (Resource.Id.chat1);
chat.Click += (sender, e) => {
var CA = new Intent(this, typeof(ChatingActivity));
StartActivity (CA);
};
}
So clicking on the chat button of each list item, the ChatingActivity will start.

android preferencefragment listview arrayadapter getview not called

After researching / reviewing code the past couple days, a solution eludes me. The ArrayAdapter.getView() function is not being called.
ArrayAdapter.getCount() is returning 3.
This listview is similar to the WiFi preference fragment ..
https://android.googlesource.com/platform/packages/apps/Settings.git/+/6829c48c36fceebb46989f8ee25c369fa5f7adeb/src/com/android/settings/wifi/WifiSettings.java
The code samples at GitHub (using title search terms) show that this should be working.
Queries through stackoverflow for "getView not called" have suggested that
the List was not being passed in,
the count was not being returned,
the ArrayAdapter was not attached to the ListView properly using setListAdapter vs setAdapter
the ArrayAdapter and ListView scope need to be class vs method level
the ListView may not be visible, thus android knows it would not be able to draw it on the screen so getView() method is never called to render the objects.
Provided below are the PreferenceFragment and ArrayAdapter Classes, and XML files.
Your Thoughts?
PreferenceFragment Class
public class Settings_WebServers extends PreferenceFragment
{
protected MyAdapter adapter = null;
protected ListView lv = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate (savedInstanceState);
addPreferencesFromResource(R.xml.settings_webservers);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView (inflater, container, savedInstanceState);
View v = inflater.inflate (R.layout.webservers, container, false);
List<String> strings = new ArrayList<String> ();
strings.add ("WebServer 1");
strings.add ("WebServer 2");
strings.add ("WebServer 3");
adapter = new MyAdapter (container.getContext(), R.layout.webservers_list, strings);
lv = (ListView) v.findViewById (android.R.id.list);
lv.setAdapter (adapter);
return v;
}
#Override
public void onStart()
{
super.onStart();;
Log.d ("onStart ", "Entered Function" );
Log.d ("ListView ", String.valueOf(lv.isShown()?"shown":"hidden"));
}
// ArrayAdapter embedded class
ArrayAdapter Class
private class MyAdapter extends ArrayAdapter<String>
{
Context context;
List<String> strings = new ArrayList<String>();
int layoutResourceId;
public MyAdapter(Context context, int layoutResourceId, List<String> objects)
{
super(context, layoutResourceId, objects);
this.layoutResourceId = layoutResourceId;
this.strings = objects;
this.context = context;
}
#Override
public int getCount ()
{ return (strings.size()); }
#Override
public View getView (int position, View convertView, ViewGroup parent)
{
Log.d ("getView position", String.valueOf (position) );
TextView lblServerName = null;
String current = strings.get (position);
LayoutInflater inflater =
(LayoutInflater) context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate
(R.layout.webservers_list, parent, false);
lblServerName = (TextView) convertView.findViewById (R.id.txtServerName);
if (lblServerName != null)
lblServerName.setText (String.valueOf(current));
return convertView;
}
}
}
Preference Header Segment
<header
android:fragment="ENetArch.Todo.Settings_WebServers"
android:icon="#drawable/icon_server"
android:title="WebServers"
android:summary="A list of servers to synchronize with"/>
xml.settings.webservers.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
</PreferenceScreen>
layout.webservers.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
layout.webservers_list.xml
<?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="?android:attr/listPreferredItemHeight"
android:padding="6dip">
<TextView
android:id="#+id/txtServerName"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="match_parent"
android:text="ENetArch"
/>
</LinearLayout>
Log Trace
04-25 15:33:02.840: D/onCreateView(2941): Entered Function
04-25 15:33:02.930: D/MyAdapter(2941): construct entered
04-25 15:33:02.930: D/MyAdapter(2941): construct exited
04-25 15:33:02.950: D/getCount(2941): 3
04-25 15:33:02.950: D/getCount(2941): 3
04-25 15:33:02.950: D/onCreateView(2941): Exiting Function
04-25 15:33:03.070: D/onStart(2941): Entered Function
04-25 15:33:03.070: D/ListView(2941): hidden

Use two components from different layouts

I have 2 layouts,in first layout I have EditText,Button and in second layout I have TextView. What I want is when i write something in EditText to copy that in second layout when you press button,but i get crash every time. Is there any way to use components from two layouts or i am missing something. If this is imposible another way would be good. Thx
main activity
public void onCreate(Bundle ivansad) {
super.onCreate(ivansad);
setContentView(R.layout.activity_main);
Button Start = (Button) findViewById(R.id.bStart);
Start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
setContentView(R.layout.numbers);
Intent Changeto2 = new Intent (MainAct.this, Numgen.class);
startActivity(Changeto2);
}
});
}
second activity
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.numbers);
Button Next = (Button)findViewById(R.id.bNext);
final EditText text = (EditText)findViewById(R.id.broj1);
final TextView edit = (TextView)findViewById(R.id.lb1);
Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
edit.setText(text.getText());
}
});
}
First layout
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="Deprecated"
android:background="#drawable/grey_bg" >
<Button
android:id="#+id/bNext"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_x="-1dp"
android:layout_y="405dp"
android:background="#000000"
android:text="Dalje"
android:textColor="#ffffff"
tools:ignore="HardcodedText" />
<EditText
android:textColor="#ffffff"
android:id="#+id/broj1"
android:layout_width="154dp"
android:layout_height="50dp"
android:layout_x="164dp"
android:layout_y="6dp"
android:background="#drawable/text_bg"
android:ems="10"
android:gravity="center"
android:hint="1-49"
android:inputType="number"
tools:ignore="HardcodedText" >
</AbsoluteLayout>
Second Layout
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/grey_bg"
android:orientation="vertical">
<TextView
android:id="#+id/lb1"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_x="80dp"
android:layout_y="107dp"
android:gravity="center"
android:text=" "
android:textSize="18sp"
tools:ignore="HardcodedText" />
</AbsoluteLayout>
What you want to do is have two separate activities, one to edit the text, and one to display it.
The first one you want to set the layout to layout_main, and set a callback for the button. Inside the callback you want:
final EditText text = (EditText)findViewById(R.id.broj1);
Intent intent = new Intent(MainAct.this, NumGen.class);
Bundle bundle = new Bundle();
bundle.putString("mString",text.getText().toString());
intent.putExtras(bundle);
startActivity(intent);
Then inside your second activity (NumGen?) you can get that string you saved by doing this:
Bundle data = getIntent().getExtras();
String mString="";
if(data.containsKey("mString")){ mString=data.getString("mString"); }
One of the main issues it looks like you might be having is the ids defined in your XML files aren't the same as the ids in your code. After that, read up on how Activities work and pass information.

Display two webview in one screen

i'm trying to make a webview app which can display two website in one screen. but when i run my app it display one website and open on new browser. how can i display two website and it doesn't work on new browser?
this is my WebViewActivity class:
package com.mkyong.android;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class WebViewActivity extends Activity {
private WebView webView1, webView2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView1 = (WebView) findViewById(R.id.webView1);
webView1.getSettings().setJavaScriptEnabled(true);
webView1.loadUrl("http://www.google.com");
webView2 = (WebView) findViewById(R.id.webView2);
webView2.getSettings().setJavaScriptEnabled(true);
webView2.loadUrl("http://www.google.com");
}
}
this is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<WebView
android:id="#+id/webview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.39" />
<WebView
android:id="#+id/webview2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.53" />
</LinearLayout>
I suggest you use framelayout and try to set webviewClient to your webview
this function shouldOverrideUrlLoading (in the declaration of the webviewClient)
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
Log.i("Page", url);
view.setWebViewClient(new MyWebViewClient());
view.setWebChromeClient(new MyWebChromeClient());
view.loadUrl(url);
return true;
}
will override url loaded by the webview and force it to be loaded in the webview not in the new browser