Android:控制动态添加的视图的最佳方式?
Android: best way to control view that added dynamically?
正如标题,我想知道是否有最好的方法来控制动态添加的视图。 (我们必须保留对添加的视图的引用)
有时,对于复杂的请求,我们必须在运行时添加视图。有一些方法可以做到这一点。就我而言:
有时我通过 list/recycleview adapter
使用 listview/recyclerview
和 control view
。
其他方法是使用 hashmap
.
你还有其他想法吗?它是如何工作的?
我更喜欢通过 Java 和 XML 文件定义视图的方式。这样创建的视图使您能够调用自己的 Java 方法,但您不需要在 Java 中动态创建整个布局。小例子:
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>
之后,您可以通过 Java:
将其简单地添加到您的布局中
cont.addView(new MyView(this).setContent("Value"));
或xml:
<com.path.to.your.view.MyView
android:id="@+id/my_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
正如标题,我想知道是否有最好的方法来控制动态添加的视图。 (我们必须保留对添加的视图的引用)
有时,对于复杂的请求,我们必须在运行时添加视图。有一些方法可以做到这一点。就我而言:
有时我通过
list/recycleview adapter
使用listview/recyclerview
和control view
。其他方法是使用
hashmap
.
你还有其他想法吗?它是如何工作的?
我更喜欢通过 Java 和 XML 文件定义视图的方式。这样创建的视图使您能够调用自己的 Java 方法,但您不需要在 Java 中动态创建整个布局。小例子:
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>
之后,您可以通过 Java:
将其简单地添加到您的布局中cont.addView(new MyView(this).setContent("Value"));
或xml:
<com.path.to.your.view.MyView
android:id="@+id/my_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>