我自己正在学习 DialogFragments。除了从按钮传递 Intent 之外,我从未尝试过任何其他方法,因此我没有找到正确的方向。
我想学习所有可能的方法。
这与使用ListFragment创建列表有什么不同吗?
主要 Activity 上有 2 个按钮。单击第二个按钮时,它应该打开一个包含项目列表的 DialogFragment,单击列表项应该在浏览器中打开一个 URL。
主要 Activity
btnDepartment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Intent intent = new Intent(MainActivity.this, DepartmentActivity.class);
//startActivity(intent);
}
});
这里是Department类,它是一个纯Java类
public class Department {
private String deptName, deptUrl;
public static final Department[] myDepartment = {
new Department("CS", "http://cs.com"),
new Department("Biology", "http://bio.com"),
new Department("Chemistry", "http://www.chemistry.com"),
new Department("Nursing", "http://nursing.com")
};
private Department(String deptName, String deptUrl){
this.deptName = deptName;
this.deptUrl = deptUrl;
}
public String getDeptName() {
return deptName;
}
public String getDeptUrl() {
return deptUrl;
}
@Override
public String toString() {
return deptName;
}
}
部门 fragment
public class DepartmentFragment extends DialogFragment {
public DepartmentFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_department, container, false);
}
}
最佳答案
Is [creating a DialogFragment] different than creating list with ListFragment
简单地说:是的。
为什么?因为ListFragment
让您可以访问 getListView()
和setAdapter()
和类的实例方法。
为了对不从 ListFragment
扩展的任何其他 Fragment 类执行此操作,您必须使用 ListView
声明一些 XML 布局并做这样的事情
我假设fragment_department.xml
包含 ListView
@+id/list
的元素并且您不关心部门信息如何显示。
public class DepartmentFragment extends DialogFragment {
public DepartmentFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_department, container, false);
ListView lstView = (ListView) rootView.findViewById(R.id.list);
ArrayAdapter<Department> adapter = new ArrayAdapter<Department>(getActivity(), android.R.layout.simple_list_item_1, Department.myDepartment);
lstView.setAdapter(adapter);
// TODO: adapter.setOnItemClickListener
// ... handle click
// ... load webpage
return rootView;
}
}
关于android - 如何使用 Dialogfragment 和 ArrayAdapter 创建列表对话框来填充 Java 类中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39841396/