Android: best way to control view that added dynamically? - android

As the title, i want to know if there is a the best way to control a view that added dynamically. (we have to keep reference to the view that was added)
Some time, for a complex request we have to add view in runtime. The is some ways to do that. In my case:
Some time i use a listview/recyclerview and control view via the list/recycleview adapter.
Other way is use a hashmap.
Do you have any other ideas? and how it work?

I prefer way, when I define View both by Java and XML file. View created like this, gives you ability to call your own Java methods, but you don`t need to create whole layout dynamically in Java. Little example:
MyView.java:
public class MyView extends LinearLayout {
TextView textView;
public MyView(Context context) {
super(context);
init();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public void init() {
inflate(getContext(), R.layout.my_view, this);
setOrientation(VERTICAL);
textView = (TextView) findViewById(R.id.text_view);
}
public MyView setContent(String value) {
textView.setText(value);
return this;
}
}
my_view.xml:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="#+id/text_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</merge>
After that, you can simply add it in you layout through Java:
cont.addView(new MyView(this).setContent("Value"));
or xml:
<com.path.to.your.view.MyView
android:id="#+id/my_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

Related

The inflate method for my binding is not found (using Android, Data Binding.)

I'm using data binding to bind the layouts in my Android app.
I have set up my layout ( my_custom.xml ) and the binding class is generated (MyCustomBinding), but Android Studio does not seem to find the .inflate(...) method of the Binding class right away, marking it as an error ( red text!).
The code seems to be correct though, since it compiles and builds just fine into an APK.
How do I get Android Studio to update correctly ?
Code example:
This is my custom View code:
public class MyCustomView extends FrameLayout {
public MyCustomView(Context context) {
this(context, null, 0);
}
public MyCustomView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
MyCustomBinding binding = MyCustomBinding.inflate(inflater, this, true);
binding.aButton.setText("Whatever");
}
}
layout is defined as:
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android">
<data>
</data>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="#+id/a_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!"
android:padding="10dp"
android:background="#000"
android:textColor="#fff"
android:layout_gravity="center"
/>
</FrameLayout>
</layout>
And here's the issue: (highlighted red)
Something is not completing in Android Studio because you haven't actually implemented data binding.
Once you add a variable to your layout's data element, the inflate method will be found as you expect. That said, you're really not getting the benefit of databinding by setting the value of the text field directly through the binding. You should instead be setting a View Model in your binding, and then let the binding update the views accordingly. For example:
create a View Model:
public class MyViewModel {
public final ObservableField<String> name;
public MyViewModel(String name) {
this.name = new ObservableField<>(name);
}
}
and use it in your layout
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="model" type="com.victoriaschocolates.conceirge.MyViewModel" />
</data>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{model.name}"
android:padding="10dp"
android:background="#000"
android:textColor="#fff"
android:layout_gravity="center"
/>
</FrameLayout>
</layout>
(note the variable declared in the data element, and how it is referenced in the TextView's text attribute)
then bind the two in your custom view:
public class MyCustomView extends FrameLayout {
public MyCustomView(Context context) {
this(context, null, 0);
}
public MyCustomView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
MyCustomBinding binding = MyCustomBinding.inflate(inflater, this, true);
MyViewModel model = new MyViewModel("Whatever");
binding.setModel(model);
}
}
Of course, it would probably be better still to have the data passed in through a setter in the custom view class, or even passed in from the container view (see http://developer.android.com/tools/data-binding/guide.html#includes)
You can try setting a custom class name to your Binding Layout, and referencing it in your custom view to make it clear which layout you using:
<layout>
<data class="MyCustomBinding">
</data>
</layout>
If this does not work, use DataBindingUtil instead of MyCustomBinding, which returns the base DataBinding class and has a inflate() method:
MyCustomBinding binding = DataBindingUtil.inflate(inflater, this, true);
From the docs:
Sometimes the binding cannot be known in advance. In such cases, the binding can be created using the DataBindingUtil class:
ViewDataBinding binding = DataBindingUtil.inflate(LayoutInflater, layoutId,
parent, attachToParent);
ViewDataBinding binding = DataBindingUtil.bindTo(viewRoot, layoutId);
this is updated answer based on latest databinding and androidx, i come here on this question to solve my own problem, after watching above answers i develop by own working code snippet. hope this helps
public class CustomActionBar1 extends RelativeLayout {
public MutableLiveData<String> title = new MutableLiveData<>("Sample text");
CustomActionBar1Binding binding;
public CustomActionBar1(Context context) {
super(context);
init(context, this);
}
public CustomActionBar1(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, this);
}
public CustomActionBar1(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, this);
}
public CustomActionBar1(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, this);
}
private void init(Context context, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
binding = DataBindingUtil.inflate(inflater, R.layout.custom_action_bar_1, viewGroup, true);
}
// helper to change title
public void changeTitle(String title) {
if (title != null)
this.title.setValue(title);
}
public void setTitleVisibility(Boolean visibile){
binding.titleText.setVisibility(visibile ? View.VISIBLE : View.INVISIBLE);
}
}
Xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="customActionBar1"
type="com.actionBar.CustomActionBar1" />
</data>
<RelativeLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:background="#color/yellow"
android:layout_height="#dimen/action_bar_height"
android:id="#+id/main_header_relative">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="#{customActionBar1.title}"
android:layout_centerInParent="true"
android:gravity="center"
android:id="#+id/titleText"
android:visibility="visible"
android:textColor="#color/black" />
</RelativeLayout>
</layout>
You dont need that type of stuffs, DataBinding includes DataBindingUtils class here we go.
public MyCustomView(Context context, AttributeSet attrs, int defStyle){
super(context, attrs, defStyle);
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
MyCustomBinding binding = DataBindingUtil.inflate(inflater, this, true);
binding.aButton.setText("Whatever");
}

BitmapDrawable cannot be cast to RoundRectDrawableWithShadow

I am trying to extend a cardview to set the background image. I know that this can not be done with normal cardview. I have searched net and found plenty of solutions for setting a background color to the card view but none for image.
My code to do so:
public class CCView extends CardView {
public CCView (Context context) {
super(context);
init();
}
public CCView (Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CCView (Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setBackground(getResources().getDrawable(R.drawable.cc_background));
}
}
I get this exception when I populate the code from XML
android.graphics.drawable.BitmapDrawable cannot be cast to android.support.v7.widget.RoundRectDrawableWithShadow
Any solution?
As CardView extends FrameLayout you can layer layouts on top of it. To get around the problem you're having, I'd try adding a blank view "underneath" all the other elements in your view, and then set that view to inherit the state of its parent. Something like this:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:layout_width="match_parent"
card_view:cardBackgroundColor="#DDFFFFFF"
card_view:cardElevation="#dimen/card_elevation">
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:duplicateParentState="true"
android:background="#drawable/card_background"/>
<LinearLayout
....
....
....
/LinearLayout>
</android.support.v7.widget.CardView>

how to put a custom view inside of a custom viewGroup / Layout

custom view inside of a custom viewGroup not visible, how can I get it to show up?
or is there a better way to do this that would work?
no compile or runtime errors but the view does not show up in the viewGroup, it is supposed to fill the area with color like the other views but it is white and the color for the view is not showing up inside of the CustomLayout
xml code, the first 2 views show up with no problems but the 3rd view that is nested inside of the CustomLayout does not show up, just white color area, the view inside not visible
CustomViewOne is a separate class file, CustomViewTwo and CustomViewThree are both nested inside the MainActivity class as static inner classes, and CustomLayout is a separate file
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity" >
<com.example.customviewexample.CustomViewOne
android:layout_width="100dp"
android:layout_height="50dp" />
<view
class="com.example.customviewexample.MainActivity$CustomViewTwo"
android:layout_width="100dp"
android:layout_height="50dp" />
<com.example.customviewexample.CustomLayout
android:layout_width="100dp"
android:layout_height="50dp">
<view
class="com.example.customviewexample.MainActivity$CustomViewThree"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.example.customviewexample.CustomLayout>
</LinearLayout>
here is the code for the CustomViewThree, vary simple like the other custom Views it just fills the area with color, it is nested inside of the MainActivity so you have to use MainActivity$CustomViewThree to access it.
public static class CustomViewThree extends View {
public CustomViewThree(Context context) {
super(context);
}
public CustomViewThree(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomViewThree(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.GREEN);
}
}
and here is the code for the CustomLayout class
public class CustomLayout extends FrameLayout {
public CustomLayout(Context context) {
super(context);
init(context);
}
public CustomLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public CustomLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
public void init(Context context) {
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
}
custom view inside of a custom viewGroup not visible, how can I get it
to show up?
Your parent CustomLayout which wraps the child has a empty onLayout() method which makes the child to not appear. This method is important in a ViewGroup because it's used by the widget to place its children in it. So, you need to provide an implementation for this method to place the children(by calling the layout() method on each of them with the proper positions). As CustomLayout extends FrameLayout you could just call the super method to use FrameLayout's implementation or even better remove the overridden method(is there a reason for implementing it?).

Custom preference not clickable

I added a custom preference to my project (code below). I added it to my preferences xml with a custom widgetLayout:
<w.PlusOnePreference
android:title="Rate App"
android:key="custom"
android:widgetLayout="#layout/plusone_pref"/>
Preference layout xml:
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.plus.PlusOneButton
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:plus="http://schemas.android.com/apk/lib/com.google.android.gms.plus"
android:id="#+id/plus_one_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:focusable="false"
plus:size="standard" />
I see the layout and the button in the layout works fine. The only problem is that the preference isn't clickable. Like it's hidden behind something.
Any ideas on how to make it clickable?
If I add a regular Preference (without a widget layout) it works fine.
Thanks.
public class PlusOnePreference extends Preference {
private PlusClient mPlusClient = null;
public PlusOnePreference(Context context) {
super(context);
}
public PlusOnePreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PlusOnePreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setPlusClient(PlusClient plusClient) {
mPlusClient = plusClient;
}
#Override
protected void onBindView(View view) {
super.onBindView(view);
//mPlusOneButton =
PlusOneButton plusOneButton = (PlusOneButton)view.findViewById(R.id.plus_one_button);
plusOneButton.initialize(mPlusClient, SettingsActivity.URL, SettingsActivity.PLUS_ONE_REQUEST_CODE);
}
}
in layout/plusone_pref.xml set android:focusable="false" for your Button
Putting Pskink's answer together with Ran's comment:
If your custom preference's layout is a ViewGroup (e.g. a *Layout), use android:descendantFocusability="blocksDescendants"
If it's just one View, use android:focusable="false"
Preferences don't have a clickable attribute, though there is an onClick() method. Tryandroid:selectable.

Implement a RadioButtonPreference in Android

How can you implement a RadioButtonPreference in android? Just like the CheckBoxPreference.
Are there any workarounds?
Use a ListPreference. You need to have more than one radio button for it to be meaningful (otherwise, it would just be a checkbox).
If, for some reason, you do not want to use a ListPreference, grab the source code to CheckBoxPreference from the Android open source tree and roll your own Preference implementation. You should then be able to list your custom implementation in preference XML using the namespace (e.g., com.foo.RadioButtonPreference).
You can use a custom class extending from CheckBoxPreference like this:
public class RadioButtonPreference extends CheckBoxPreference {
public RadioButtonPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setWidgetLayoutResource(R.layout.preference_widget_radiobutton);
}
public RadioButtonPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setWidgetLayoutResource(R.layout.preference_widget_radiobutton);
}
public RadioButtonPreference(Context context) {
this(context, null);
}
#Override
public void onClick() {
if (this.isChecked()) {
return;
}
super.onClick();
}
}
Then create a preference_widget_radiobutton.xml layout file:
<?xml version="1.0" encoding="utf-8"?>
<!-- Layout used by CheckBoxPreference for the checkbox style. This is inflated
inside android.R.layout.preference. -->
<RadioButton android:id="#+android:id/checkbox"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:clickable="false"
android:focusable="false"/>

Categories

Resources