This always confused me. Let's say I have these two scenarios :
First scenario :
my_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout ..>
<CardView id="#+id/myCardView" ../> // or any other view
</RelativeLayout>
In code :
.. onCreate() {
View view = inflater.inflate(R.layout.my_layout, container, false);
myCardView = (CardView) view.findViewById(R.id.myCardView);
}
Second scenario :
my_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<CardView ../>
In code :
.. onCreate() {
myCardView = (CardView) inflater.inflate(R.layout.my_layout, container, false);
}
To inflate and get a CardView object, when should one use first scenario and when the second ?
Note that in first scenario, I never do anything with the RelativeLayout object. It's merely used to get the CardView object.
The reason I ask is I see the first scenario in so many tutorials but it is never explained why the extra encapsulating Layout is actually there.
Is there any scenario where the first example above does make more sense than the second ?
Post Edit: Could you please evaluate my question with RecyclerView.ViewHolder pattern in mind ?
Post Edit 2:
I use the first scenario in ViewHolder pattern.
public class EntryViewHolder extends RecyclerView.ViewHolder {
public CardView cv;
public EntryViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.entries_card_view);
}
}
Still, even in this scenario I never make use of the encapsulating RelativeLayout. I only use it to call findViewById(..) to get the CardView object.
The first scenario would be used whenever you have an XML layout with multiple child views inside of them. A couple TextViews, EditTexts, Spinners, etc, the things you would need to put together a presentable page for the user. The <RelativeLayout and the other layout tags help organize the child views inside of them, in this case "Relative" to each other. I would stick to this practice instead of your second scenario.
I'm not sure I have ever seen anything like your second scenario before. Inflating the layout and then casting the entire layout to a CardView seems odd. The closest thing I can relate it to is when you make an XML for a custom adapter view, where you might be making a list of card objects.
Here is a helpful link on Layouts.
Related
Do I have to rely on ListView/Recycler view each time I need to loop over data to repeat a layout ?
I totally understand it for long lists of data where scroll/performance is involved, but let's say I am sure i'll only have 0...3max items and need to display in very simple single-line-layout for each (1 image, 1 textview + button).. isn't there a simplier pattern than using adapters ?
Seems like overkill (and a pain to deal with for every little part of my screen where I need to loop overs small lists).
What are the other options while using Components architecture (databinding) ?
Manually inflating my layout ? In viewmodel ? fragment? Do I need to create another viewModel specially for this child layout ?
Thanks
I recently have a similar issue recently, but my problem was that of nested lists i.e. I needed to inflate another list inside a recycler view. Here is a minimal example of how I went about it.
Add a LinearLayout to your layout XML file:
<LinearLayout
android:id="#+id/smallList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:list="#{viewModel.yourList}" />
Create a binding adapter where you inflate the items. Like so:
#BindingAdapter("app:list")
fun setList(layout: LinearLayout, yourList: List<ListItemModel>) {
layout.removeAllViews() // Remove previous items if your list does change
for (listItem in yourList) {
ListItemBinding.inflate( // inflate your list item
LayoutInflater.from(layout.context),
layout, // pass your LinearLayout as root
true // attachToRoot is true so that the inflated view is added to the LinearLayout
).apply {
// set your binding variables
this.listItem = listItem
}
}
}
Note: This is a minimal example to solve the issue since actual data and functionality is unknown. You may want to:
Add a click listener variable to your list item XML file and set that similarly.
Create a custom view for the view if it is to be reused and write the binding adapter there.
How I can avoid using findViewById in my app. Layout is very complicated and findViewById traverses its tree to find view which takes time and it is used several times.
First, you must edit your application’s build.gradle file and add the following into the android block:
android {
…
dataBinding.enabled = true
}
The next thing is to change the layout file by making the outer tag instead of whatever ViewGroup you use:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="#+id/hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
</layout>
The layout tag tells Android Studio that this layout should take the extra processing during compilation time to find all the interesting Views and note them for the next step. All layouts without that outer layout tag will not get the extra processing step, so you can sprinkle these into new projects wherever you like without changing anything in the rest of your application.
The next thing you have to do is to tell it to load your layout file differently at runtime. Because this works all the way back to the Eclair release, there is no reliance on new framework changes to load these preprocessed layout files. Therefore, you do have to make a slight change to your loading procedure.
From an Activity, instead of:
setContentView(R.layout.hello_world);
TextView hello = (TextView) findViewById(R.id.hello);
hello.setText("Hello World"); // for example, but you'd use resources, right?
You load it like this:
HelloWorldBinding binding = DataBindingUtil.setContentView(this, R.layout.hello_world);
binding.hello.setText("Hello World"); // you should use resources!
Here you can see that a class, HelloWorldBinding, was generated for the hello_world.xml layout file, and the View with the ID #+id/hello was assigned to a final field hello that you can use. No casting, no findViewById.
It turns out that this mechanism for accessing views is not only much easier than findViewById, but can also be faster! The binding process makes a single pass on all Views in the layout to assign the views to the fields. When you run findViewById, the view hierarchy is walked each time to find it.
One thing you will see is that it transforms your variable names into camel case (just like hello_world.xml becomes the class HelloWorldBinding), so if you gave it the ID #+id/hello_text, then the field name would be helloText.
When you’re inflating your layouts for RecyclerView, ViewPager, or other things that aren’t setting the Activity contents, you’ll want to use the generated type-safe methods on the generated class. There are several versions that match the LayoutInflater, so use the one that is most appropriate for your use. For example:
HelloWorldBinding binding = HelloWorldBinding.inflate(
getLayoutInflater(), container, attachToContainer);
If you aren’t attaching the inflated View to the containing ViewGroup, you’ll have to get access to the inflated View hierarchy. You can do this from the getRoot() method of the binding:
linearLayout.addView(binding.getRoot());
Another choice is Kotlin's Android extensions.
// Using R.layout.activity_main from the main source set
import kotlinx.android.synthetic.main.activity_main.*
class MyActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Instead of findView(R.id.textView) as TextView
textView.setText("Hello, world!")
}
}
https://kotlinlang.org/docs/tutorials/android-plugin.html
you can directly import views from xml:-
add kotlin extentions in app.gradle
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
see the below eg.
You have a few options, the two main ones being:
Android Data Binding:
https://developer.android.com/topic/libraries/data-binding/index.html
OR
Butterknife:
http://jakewharton.github.io/butterknife/
Personally I am a huge fan of Butterknife and use it everywhere where possible, worth noting, this just makes your code nicer to look at. I find that Androids data binding is far more complicated than Butter Knifes (That's more person opinion though...)
To my knowledge you can either use view binding or findViewByID. The clear thing here is that they do the same thing. Data/View binding will just write the findViewByID at compile time.
View Binding just makes your code easier to read. I'm not aware of any changes to android other than soon you will no longer have to cast your findViewByIDs.
You can use viewbinding to replace findviewbyid. It will help you to avoid null pointer exception and type cast exception. You just need to enable view binding in modules gradle file. Then create instance for binding class. then use that instance to reference views in your code.
You will get much clear information from these links.
View binding video tutorial : https://youtu.be/ILUf3Zf0ocI
View binding documentation : https://developer.android.com/topic/libraries/view-binding
How I can avoid using findViewById in my app
You can use getChildAt as alternative for findViewById for founding a view inside a ViewGroup and its derivative (like RelativeLayout, LinearLayout, etc). It is super fast because it's only try to find the view from the views array by its index (link to the source code):
// Child views of this ViewGroup
private View[] mChildren;
// Number of valid children in the mChildren array, the rest should be null or not
// considered as children
private int mChildrenCount;
...
public View getChildAt(int index) {
if (index < 0 || index >= mChildrenCount) {
return null;
}
return mChildren[index];
}
The following is the sample how using getChildAt. Assume you have the following Layout:
<RelativeLayout>
<TextView/>
<Button/>
<EditText/>
</RelativeLayout>
you can get all the views with the following:
// assume we have inflate the layout
TextView textView = (TextView) getChildAt(0);
Button button = (Button) getChildAt(1);
EditText editText = (EditText) getChildAt(2);
But then it is started to become tedious if you have complex layout like the following:
<RelativeLayout>
<TextView/>
<Button/>
<LinearLayout>
<TextView/>
<Button/>
<EditText/>
</LinearLayout>
<LinearLayout>
<TextView/>
<Button/>
<EditText/>
</LinearLayout>
</RelativeLayout>
The major problem of using getChildAt is you can't easily change your layout position without adapting your code for the change.
I have a Layout that I want to populate with items consisting of 2 textviews and one button. I do not know before hand how many items that will populate my Layout.
Since I don't know when writing the layout.xml how many items I want to add, thats means that I have to add the items in the java instead of the xml. But I do not like to build GUI in java because it looks ugly.
Does anyone know if I can create an xml file for my item and then add new items to my layout during execution?
I have written some pseudo code to try to demonstrate what I want to accomplish:
MainLayout.xml
//My empty Layout
<Layout myMainLayout >
</RelativeLayout>
Fragment_post.xml
//one post
<TextView/>
<TextView/>
<Button/>
In the code somewhere
setContentView(R.layout.MainLayout);
MyMainLayout.addFragment(R.layout.Fragment_post);
You can add your fragment_post.xml wherever you want:
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout view=(LinearLayout)inflater.inflate(R.layout.yourfragment, null);
yourLayout.addView(view);
Please don't confuse a Fragment with a piece of the GUI. See here for details: http://developer.android.com/guide/components/fragments.html
Sure you can do this. Just set an initial empty layout to your activity.
onCreate()
{
setContentView(R.layout.initial_layout);
}
Then get and keep a reference to main layout.
LayoutInflater inflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout mainLayout=(RelativeLayout)inflater.inflate(R.layout.initial_layout, null);
Next, add new views to your layout as and when you need them.
LinearLayout view=(LinearLayout)inflater.inflate(R.layout.fragment_post, null);
mainLayout.addView(view);
But note that what you refer to as fragments here are not what android refers to as fragments. Learn about actual android fragments here:
http://developer.android.com/guide/components/fragments.html
I am preparing to do an android demonstration of sorts and one of the first apps that i would like to write would be a screen filled with different widgets(which of course are views) but would like to put them on the screen without any layout built to hold them. is this possible or do you have to use a layout to put more than one view(widget) on the screen at once?
So right now i can do something like:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
TextView view1 = new TextView(this);
view1.setText("I am view one");
setContentView(view1);
}
}
In this case i really havent specified a layout but there doesnt seem to be a way to position multiple widgets on the screen without setting a layout. The purpose of this would be to show why you would want to use layouts. perhaps there is a way to display widgets on the screen without having to call the setContentView method.
You can only add multiple widgets/views to something called a ViewGroup. If you take a look at the documentation you'll see - not surprisingly - that basically all layouts extend this class. Similarly, if you look up the documentation on e.g. a TextView, you'll find that it doesn't extend ViewGroup (it does inherit from View, just like ViewGroup, which means it's on a different branch in the hierarchy tree).
In other words: you will need some sort of a layout in order to display more than a single widget/view at a time. You will also always need an explicit call to setContentView(), unless you use something like a ListActivity or ListFragment that by default creates a layout with a ListView as root.
That being said, your example is actually just a programmatical way of setting the following layout on the activity:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="I am view one" />
You can do it like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout frameLayout = new FrameLayout(this);
TextView view1 = new TextView(this);
view1.setText("I am view one");
frameLayout.addView(view1);
// add more widgets into ViewGroup as you want
// then set the viewgroup as content view
setContentView(frameLayout);
}
I'm trying to make some Android view classes (which are just wrappers around layouts defined in an XML file). Is this correct:
public class MyViewWrapper extends LinearLayout {
private TextView mTextView;
public MyViewWrapper(Context context) {
super(context);
}
public constructUI() {
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.myview, this);
mTextView = (TextView)findViewById(R.id.myview_textview);
}
}
so the idea is just that I can construct my views like that, and they have logic inside for modifying their child views etc. The layout looks like:
<LinearLayout>
<TextView />
</LinearLayout>
It just looks like I'm going to get an extra unnecessary LinearLayout. The wrapper class is itself a LinearLayout, and then it will attach the inner LinearLayout from the xml file.
Is that ok?
Thanks
You can try replacing the <LinearLayout> in your layout file with <merge>. I have not tried that recently, and I think I ran into problems when I last tried it, but in theory it should serve the purpose. <merge> basically means "take all my children and put them directly into whatever container I'm being inflated into".