我正在开发一个 Android 应用程序并遇到一个问题:我的主要 Activity 包含一个 ListView 和一个按钮,我需要在 ListView 为空时禁用该按钮。
我试过了 this但是 ListView 没有 addTextChangedListener
。
最佳答案
您需要使用适配器 .registerDataSetObserver()
方法,每次 ListView
的数据更改时都会触发该方法。
这是一个简单的例子,说明你需要实现什么
它看起来像什么
布局
<?xml version="1.0" encoding="utf-8"?>
<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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="@+id/btn_disable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:enabled="false"
android:text="Disabled" />
<Button
android:id="@+id/btn_add_data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add" />
<Button
android:id="@+id/btn_remove_data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remove" />
</LinearLayout>
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
行为
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btnDisabled = findViewById(R.id.btn_disable);
Button btnRemoveData = findViewById(R.id.btn_remove_data);
Button btnAddData = findViewById(R.id.btn_add_data);
final ListView mList = findViewById(R.id.listview);
final List<String> data = new ArrayList<>();
final ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, data);
mList.setAdapter(adapter);
btnAddData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
data.add("Data");
adapter.notifyDataSetChanged();
}
});
adapter.registerDataSetObserver(new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
if (mList.getAdapter().isEmpty())
btnDisabled.setEnabled(false);
else
btnDisabled.setEnabled(true);
}
});
btnRemoveData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!data.isEmpty())
data.remove(data.size() - 1);
adapter.notifyDataSetChanged();
}
});
}
}
关于android - 如何在 listView 为空时禁用按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58151486/