【发布时间】:2018-06-11 11:39:19
【问题描述】:
我有一个父视图和一个子视图。子视图以编程方式膨胀。子视图有一个带有一些背景的TextView。 TextView 上有一个 onclick 事件。我想要的是当用户单击第一个 TextView 时,它的背景颜色应该改变,当用户选择第二个时,第一个 textview 的背景应该回到它的默认背景,而第二个应该改变。
我更改了背景颜色,但在恢复背景时遇到了困难。这是我的代码:
我的父视图:
<com.google.android.flexbox.FlexboxLayout
android:id="@+id/viewCategoriesLinearlayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:flexWrap="wrap"
app:alignItems="stretch"
app:alignContent="stretch"
android:layout_marginTop="@dimen/_10sdp"
android:layout_marginLeft="@dimen/_5sdp"
android:layout_marginStart="@dimen/_5sdp" />
我的孩子视图:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<TextView
android:id="@+id/categoryChip"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:background="@drawable/category_tag_background"
android:text="TAG"
android:layout_marginTop="@dimen/_25sdp"
android:paddingLeft="@dimen/_5sdp"
android:paddingTop="@dimen/_5sdp"
android:paddingBottom="@dimen/_5sdp"
android:paddingRight="@dimen/_5sdp"
android:layout_marginLeft="@dimen/_5sdp"
android:layout_marginRight="@dimen/_5sdp"
android:textColor="@color/textcolorLogin"
android:textSize="@dimen/_11ssp" />
<TextView
android:id="@+id/categorychipid"
android:layout_width="0dp"
android:layout_height="0dp"
android:visibility="gone"/>
</LinearLayout>
这就是我膨胀和改变背景颜色的方式:
FlexboxLayout categoryInformationHeader = view.findViewById(R.id.viewCategoriesLinearlayout);
final View editChildView = getActivity().getLayoutInflater().inflate(R.layout.tag_layout, null);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(10,2,10,2);
editChildView.setLayoutParams(layoutParams);
editParentLL.addView(editChildView);
final TextView editTvChip = editChildView.findViewById(R.id.chip12345);
final String shelfShareCategoryTitle = crsEditShelfShare.getString(crsEditShelfShare.getColumnIndex("title"));
editTvChip.setText(shelfShareCategoryTitle);
editTvChip.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
editTvChip.setBackgroundResource(R.color.colorPrimary);
}
});
【问题讨论】:
-
你能展示你如何以编程方式添加子视图吗?因为这就是我们要在
onClickListener的editTvChip上再次调用的内容。 -
@TentenPonce, editParentLL.addView(editChildView);这就是我夸大子视图的地方。
-
这是一个循环吗?
-
@TentenPonce,这不是循环。子视图在单击按钮时被放大
-
我一次添加一个子视图。假装通过单击按钮调用这段代码,而不是我认为你会明白的。
标签: android layout-inflater android-inflate