我正在尝试使用 android studio 中的 ListView 更改 Activity 的背景颜色,但是当我单击 ListView 中的项目时没有任何反应。有人可以帮助我吗?
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setListAdapter(new ArrayAdapter<String>(this, R.layout.row,R.id.label,items));
view = this.getWindow().getDecorView();
view.setBackgroundResource(R.color.white);
}
public void onListItemClick(ListView parent, View v, char position, long id) {
String s = label.getText().toString();
double l = Double.parseDouble(s);
double o;
switch (position) {
case 0:
view.setBackgroundResource(R.color.red);
break;
case 1:
view.setBackgroundResource(R.color.green);
break;
case 2:
view.setBackgroundResource(R.color.white);
break;
case 3:
view.setBackgroundResource(R.color.orange);
break;
}
}
activity_main.xml
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
最佳答案
如下更新您的activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/background_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background_screen"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical">
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
并在您的 Activity 中转换布局并将背景颜色应用于布局。这将更改屏幕的背景颜色
private LinearLayout mLayout=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setListAdapter(new ArrayAdapter<String>(this, R.layout.row,R.id.label,items));
mLayout = (LinearLayout) findViewById(R.id.background_layout);
view = this.getWindow().getDecorView();
view.setBackgroundResource(R.color.white);
}
public void onListItemClick(ListView parent, View v, char position, long id) {
String s = label.getText().toString();
double l = Double.parseDouble(s);
double o;
switch (position) {
case 0:
mLayout .setBackgroundColor(Color.RED);
break;
case 1:
mLayout .setBackgroundColor(Color.GREEN);
break;
case 2:
mLayout.setBackgroundColor(Color.WHITE);
break;
case 3:
mLayout.setBackgroundColor(Color.parseColor("#FFA500"));
break;
}
}
关于java - 如何更改 ListView 中项目的 Activity 背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47458610/