Here is the tutorial
https://www.youtube.com/watch?time_continue=289&v=OGfZpfn-dGI
In my android studio it doesn't recognize the button iv'e name them
android:id="#+id/top_button"
android:text="top button"
android:text="button 2"
android: android:id="#+id/button_2"
top_button.setOnClicklistner {
println(top button was clicked)
Button_2.setOnClicklistner {
println(Button)
We're missing a lot of context here that would probably help us help you.
A few things first though:
- The android:id property in your XML layout is how you name the View in question. This is most often how you will reference the View in code.
- The android:text property is the user visible text on views like TextView.
- In order for top_button to refer to your desired View in your XML layout file, it needs to be bound in code. There's a couple of normal ways of doing it findViewById() and data-binding.
I'm going to assume, for now, that the last step is what you are missing (it seems the most likely culprit at this point)... Here's a few ways to bind it:
Method 1: when using an Activity class
If you're binding top_button to your View from an Activity class, this should work:
private lateinit var top_button // replace View here with your widget's type
fun onCreate(...) {
super.onCreate(...)
setContentView(R.layout.<i>your_layout_file_name_here</i>)
top_button = findViewById(R.id.top_button)
...
}
Method 2: when using a Fragment class
If you're binding top_button to your View from a Fragment class, it's more like this:
private lateinit var top_button: View // replace View here with your widget's type
fun onCreateView(...): View {
val rootView = layoutInflater.inflate(R.layout.<i>your_layout_file_name_here</i>)
top_button = rootView.findViewById(R.id.top_button)
...
return rootView
}
Method 3: when using data-binding
I prefer this method myself, but you should Google how to setup data-binding in Android as you'll need changes in your build.gradle and all.
First, change your XML layout to be:
<layout>
<!-- your existing layout XML here -->
</layout>
Then in your Activity/Fragment, let's say your XML layout file is named activity_my_cool_screen.xml, you can do:
val binding = ActivityMyCoolScreenBinding.inflate(getLayoutInflater())
binding.topButton.setOnClickListener(...)
Notice here that the ActivityMyCoolScreenBinding class is auto-generated for you. If it turns red at first, then first verify you've accurately setup data-binding in your project, then if that's good to go, make sure to import the ActivityMyCoolScreenBinding class. If you change your XML layout's filename, then the ActivityMyCoolScreenBinding class name will change to match automatically. But, I'd recommend if you do change the name, that you use Android Studio's refactoring/renaming tools as it'll search your codebase and update it everywhere. Otherwise, you have to do it by hand (doable, but potentially tedious and error prone).
Good luck!
Related
I want to retrieve the id of a Layout inside of one of my layout xmls, and it's possible to use both
R.id.* and the binding for this - details below.
Which is the preferred way?
Given the following structure:
app
|-- java.org.romco.appname
| |-- MainActivity.kt
|-- res.layout
| |-- main_activity.xml
| |-- main_content.xml
Let's say my main_activity.xml is a CoordinatorLayout and includes the main_content.xml with a defined id of "main_content", such as:
android:id="#+id/main_content"
layout="#layout/content_main" />
My content_main.xml then contains a FrameLayout with a defined if of "task_details_container", such as:
<FrameLayout
android:id="#+id/task_details_container" />
Following the official guides, the binding in MainActivity.kt would be created as:
class MainActivity : AppCompatActivity() {
private lateinit var mainActivityBinding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mainActivityBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(mainActivityBinding.root)
}
If I now want to refer to the FrameView inside of my content_main.xml, how do I go about it?
Should i use what I'd normally use, so R.id.task_details_container, or is it preferred to use the binding to retrieve the ID now that I have it available? If I try to log it in onCreate, the output is the same:
val id1 = R.id.task_details_container
val id2 = mainActivityBinding.mainContent.taskDetailsContainer.id
Log.d("MainActivity", "R id = $id1, binding id = $id2")
Log output:
D/MainActivity: R id = 2131231072, binding id = 2131231072
From what I've found so far:
here's a video where they introduce view binding, but they only mention it as a way to avoid using findViewById: https://www.youtube.com/watch?v=td3Kd7fOROw&t=1756s
This article walks us through using view binding, in both activities and fragments, but again, seemingly only as a way to avoid findViewById. https://medium.com/androiddevelopers/use-view-binding-to-replace-findviewbyid-c83942471fc
The official doc covers pretty much the same as the article: https://developer.android.com/topic/libraries/view-binding
But none of these talk about whether using the bound id is better than using R.id..
My guess is that using R.id. is preferred, since not all elements have to be view-bound and therefore, for the sake of consistency, I can use R.id.* everywhere, where as I possibly can't use binding where the property is not accessible. But as I said, it's just a guess and I'd like to hear a wiser opinion on this.
You should always use View Binding. It is more efficient than findViewById. Every time you call findViewById(), the Android system traverses the entire view hierarchy at runtime to find the view. Whereas View Binding traverses the view hierarchy only once. For a large view hierarchy, using findViewById can noticeably slow down the app for the user.
If you are using view ids for anything other than calling findViewById(), is safe to use R.id.view_id instead binding.view.id. Both have the same performance characteristics
New to android development, I'm trying to apply View Binding as they are the recommended view referencing method by Google as of now. I have two layouts content_main.xml and content_note_list.xml. I got the first 'content_main_xml' (MainActivity) to work with View Binding. However I'm having trouble implementing view binding for second 'content_note_list.xml'.
Below is the code that keeps crashing the app within the simulator
here's the image of the code block
It works when I don't use the view binding ie.
setContentView(R.layout.activity_note_list)
but as soon as I try to use the view bindings, it opens up the app and crashes momentarily
setContentView(binding.root)
I don't know what I'm doing wrong, I have followed the description provided by the official android dev site, multiple videos.
Any help would be necessary.
EDIT:
content_note_list.xml activity_note_list.xml
Apologize for attaching image files, the code becomes all messed up when I try to append it.
It seems to be the name. Remembering from android documentation. If your layout is result_profile.xml
<LinearLayout ... >
<TextView android:id="#+id/name" />
<ImageView android:cropToPadding="true" />
<Button android:id="#+id/button"
android:background="#drawable/rounded_button" />
</LinearLayout>
ViewBinding will generate ResultProfileBinding.
If view binding is enabled for a module, a binding class is generated for each XML layout file that the module contains. Each binding class contains references to the root view and all views that have an ID. The name of the binding class is generated by converting the name of the XML file to Pascal case and adding the word "Binding" to the end.
So, with that in mind. if your layout is activity_note_list it will generate ActivityNoteListBinding class or something like that. In your code, you are setting ContentNoteListBinding class. Try to replace ContentNoteListBinding with ActivityNoteListBinding. Also, if it does not solve the problem. Try to add the code from console log. it has more details about the error.
Update
If you want to handle View or ViewGroup which are include in your activity/fragment over <include> tag, you can access these views almost directly. You need to add an Id in this tag <include>. And then you will have access to these components: For example:
This is a activity_note_list.xml
........
<include
id="+#id/ly_content_list_note"
layout="#layout/content_list_note"/>
........
And content_note_list.xml
<listView
id="+id/listNotes"
.......
/>
Now in your Activity class, you can access in this way:
binding.lyContentListNote.listNotes
As you can see, first access directly to the id of the container, which is ly_content_list_note and then all the view components inside that, in this case listNotes.
adding to #rguzman answer, to avoid running into issues like this where the type of the binding is accidentally set wrong, you can use DataBindingUtil library.
For Activity
val binding = DataBindingUtil.setContentView(this, R.layout.your_file)
For Fragments
binding = DataBindingUtil.inflate(inflater, R.layout.your_file, container, false)
//other logic
return binding.root
link to official docs for more info
I want to achieve this :
Create a ViewDataBinding by inflating a layout.
Set a tag to its root view.
Insert its root view into my layout.
Later on, call findViewWithTag() to retrieve its root view.
Getting the ViewDataBinding linked to its view.
But I can't figure out how to achieve the latest step.
This is how my code looks like :
MyViewDataBinding binding = DataBindingUtils.inflate(inflater, R.layout.my_layout, myContainer, false);
View bindingRootView = binding.getRoot();
bindingRootView.setTag("aTag");
myContainer.addView(bindingRootView);
//In another part of the code ...
MyViewDataBinding binding = myContainer.findViewByTag("aTag").getViewDataBinding();
But is their something like "getViewDataBinding"?
Thank's for help.
You can find appropriate method in DataBindingUtil class. It is called findBinding(View view). It may be needed to cast returned value to your wanted class type.
I'm not sure though whether it's the best architecture. I would be interested if you would give us more context.
The problem is proposed because I want to edit the position, color, and other display properties in the "what you see is what you get" mode; therefore, add some specific behavior in its onDraw(Canvas) function. So, i want to rewrite the view class, currently use own-defined class in res/layout/main.xml is unsupported.
Anyone knows some solution?
Create your own class that extends View and override onDraw method. Than use it in xml with the fully qualified name of the class. Something like this
....
<your.package.MyView android:id="#+id/my_id" ..../>
....
Then in your code get a reference to it like this
MyView mv = (MyView)findViewById(R.id.my_id);
Here is good example of the above.
I currently have an activity with some buttons.
In my xml, buttons are defined like this:
<ImageButton (...) android:onClick="GoToPageX"/>
and I have in my activity:
public void GotoPageX() {
startActivity(new Intent(this, PageX.class));
finish();
}
The problem is that I have hundreds of buttons and do not want to write
<ImageButton (...) android:onClick="GoToPage1"/>
<ImageButton (...) android:onClick="GoToPage2"/>
<ImageButton (...) android:onClick="GoToPage3"/>
...
<ImageButton (...) android:onClick="GoToPage100"/>
and all the scripts.
I am now using
public void GotoPage( int i) {
startActivity(new Intent(getBaseContext(), activities.get(i)));
finish();
}
and would like to give the parameter i from the xml, is that possible?
Thank a lot for any help.
It is not directly possible. However, maybe you could use android:tag to get your parameter.
<ImageButton (...) android:onClick="goToPage" android:tag="25"/>
public void goToPage(View v) {
String pageNumber = v.getTag().toString();
/* ... */
}
You could also do this by enabling data binding and using a lambda expression for the onClick value. This way is especially useful if you plan to use multiple inputs of different types. Here's an example of a simple MainActivity.xml in which this strategy is used.
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="main" type="com.example.android.myapp.MainActivity" />
</data>
<LinearLayout android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton (...) android:onClick='#{() -> main.GotoPage(1,"one")}'/>
<ImageButton (...) android:onClick='#{() -> main.GotoPage(2,"two")}'/>
<ImageButton (...) android:onClick='#{() -> main.GotoPage(3,"three")}'/>
...
<ImageButton (...) android:onClick='#{() -> main.GotoPage(100,"one hundred")}'/>
</LinearLayout>
</layout>
and in MainActivity.java
public void GotoPage(int i, String otherVariable) {
/** code using i and otherVariable **/
}
UPDATE: For those who don't know how to set up data binding, I will explain it here so you don't have to google around for it. First, enable dataBinding in the build.gradle file:
android {
...
dataBinding {
enabled = true
}
...
}
Also, make sure jcenter() is in your repositories.
Then, go to the XML of the layout where onClick will be used and wrap its layout in a layout tag with a data section like this:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="main" type="com.example.android.yourapp.MainActivity" />
</data>
<YourLayout>
...
</YourLayout>
</layout>
For the variable tag's type parameter, you need to put the class that will contain the function which onClick points to. In this example, I will use the main activity class, which is named MainActivity in my test project.
After you have your layout wrapped in a layout tag like in the example above, clean the project in Android Studio. You may also need to invalidate cache/restart or close and reopen Android Studio.
Next, if the the layout with onClick you are trying to set up data binding for is the same layout set by setContentView in your main activity class, open the file that contains your main activity class. If the layout with onClick you are trying to set up data binding for is inflated programmatically in a different file, open the file in which the layout is inflated instead.
Add these imports to that file:
import com.example.android.yourapp.databinding.YourLayoutBinding;
import android.databinding.DataBindingUtil;
That first class you are importing is generated when you clean the project (and possibly have to invalidate cache/restart) and is automatically named after the XML file you added the layout wrapper to. If the layout file is named your_layout.xml, the import class will be named YourLayoutBinding. The exact import path will depend on your app name and structure, but it will always be within a databinding parent class.
The next step depends on whether the layout you are adding data binding to is set with setContentView or is inflated with inflate. Both versions of the following step make use of the method setMain. The setMain method is automatically generated and named using the value of the name parameter in the layout wrapper we added. Since we put name="main", the method is called setMain.
If the layout you are adding data binding to is the same layout set by setContentView find the line in your main activity class that looks like setContentView(R.layout.your_layout); and change it to use DataBindingUtil.setContentView instead of setContentView, adding this as its first argument. Use binding.setMain to point the layout's main variable to the current activity.
YourLayoutBinding binding = DataBindingUtil.setContentView(this, R.layout.your_layout);
binding.setMain(this);
If the layout you are adding data binding to is not set by setContentView but rather inflated go to where it is inflated in your code. It should look something like this:
return inflater.inflate(R.layout.your_layout, container, false);
Modify it to use DataBindingUtil.inflate, adding the previous inflater as its first argument. Use binding.setMain to point the layout's main variable to the main activity, and use binding.getRoot() to get the view. It should end up like this:
YourLayoutBinding binding = DataBindingUtil.inflate(inflater, R.layout.your_layout, container, false);
binding.setMain((MainActivity) getActivity());
return binding.getRoot();
Now the data binding is ready to use. Add a function for onClick to point to within your main activity class.
public void exampleFunction(int number, String text) {
System.out.println("Number: " + number + ", Text: " + text);
}
You can call it from the layout you added data binding to using a lambda expression. This example function doesn't require a View, so it can be used like this:
<Button android:id="#+id/buttonID"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="26sp"
android:text="Test"
android:onClick='#{() -> main.exampleFunction(123, "test")}'/>
Make sure to use single quotes around the value for onClick if you plan on using a String input.
If you do need to pass the button's view to your function, simply add a View parameter to your function's required arguments and use a lambda expression like this instead:
<Button android:id="#+id/buttonID"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="26sp"
android:text="Test"
android:onClick='#{(view) -> main.exampleFunction(view, 123, "test")}'/>
If you will create some layout element in xml you can use there
<ImageButton
android:id="#+id/some_id_value" />
where some_id_value is kind of unique string which will be translate into id which is kept in R.java (better for you- don't change anything there) than in code you can get that id by using
R.id.some_id_value
read a little bit there that's really basics.
You can set Tags for a view. Tags are basically a way for views to have memories.
xml:
<ImageButton
...Other Parameters...
android:id="#+id/Button2"
android:tag="2"
android:onClick="GoToPageX"/>
<ImageButton
...Other Parameters...
android:id="#+id/Button3"
android:tag="3"
android:onClick="GoToPageX"/>
The line android:tag="2" set a tag value of 2(string data type) to Button2
Java file:
General Case:
Inside GoToPageX(View v) function,
use v.getTag() to get the tag value of corresponding view(From which ever view the method was called).
Your case:
Add the method as follows
public void GoToPageX(View v){
int i = Integer.parseInt(v.getTag()); //parseInt converts string to integer
startActivity(new Intent(getBaseContext(), activities.get(i)));
finish();
}