【发布时间】:2019-09-12 22:43:06
【问题描述】:
我是一名新的 Android 开发学生,我正在尝试创建一个动态布局,女巫在同一行内包含一个 TextView 和一个按钮。
但我有一个小问题。 我通过
在我的 Drawables 资源中设置了我的 Button button.setBackgroundResource(R.drawable.ic_comment_black_48px);
现在,我无法更改它背后的背景颜色。
我在我的主 LinearLayout 中创建了一个 newLinearlayout,并创建了一个新的 textView 和一个新的 Button。 我已将它们放在 LinearLayout 的子元素中,并将其放在主元素中。 这是可行的,但不是我按钮背后的背景颜色。
有没有办法做到这一点?
我的xml布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/grey"
android:id="@+id/historyLayout">
</LinearLayout>
我的完整活动
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
mLinearLayout = findViewById(R.id.historyLayout);
mMoodSaved = new ArrayList(7); // Define the max size of my ArrayList
loadData();
for (int i = 1; i <= 7; i++) {
final TextView textView = new TextView(this);
mLinearLyt = new LinearLayout(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mLinearLyt.setOrientation(LinearLayout.HORIZONTAL);
textView.setHeight(300);
textView.setWidth(400);
textView.setBackgroundColor(Color.RED);
textView.setTextColor(Color.BLACK);
textView.setTextSize(12);
textView.setText(String.valueOf(i));
mLinearLyt.setBackgroundColor(Color.YELLOW);
mLinearLyt.addView(textView);
mLinearLyt.setLayoutParams(params);
ImageButton button = new ImageButton(this);
LinearLayout.LayoutParams param2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
param2.setMargins(20,50,0,0);
param2.height = 100;
param2.width = 100;
button.setLayoutParams(param2);
button.setBackgroundResource(R.drawable.ic_comment_black_48px);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
soundConfirm();
Toast.makeText(getApplicationContext(), textView.getText(), Toast.LENGTH_LONG).show(); //Display Toast Message
}
});
mLinearLyt.addView(button);
mLinearLayout.addView(mLinearLyt);
}
}
【问题讨论】:
-
分享你的xml代码
-
@SultanMahmud 好的共享。它只是一个基本的线性布局,可以动态地做所有事情。
-
分享完整的活动代码。理想情况下,setBackgroundResource 应该设置背景。
-
@TheAnkush 好的共享。我想创建动态 7 行。之后它们将包含来自对象的一些数据。
标签: android button dynamic android-linearlayout