构建我的第一个 Android 应用程序。我已经成功地从公共(public)类(class)中调用图像和文本 block 。所以,
在 DetailFragment 中,我有这个:
public class DetailFragment extends ListFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/** Inflating the layout country_details_fragment_layout to the view object v */
View v = inflater.inflate(R.layout.detail_fragment, null);
/** Getting the textview object of the layout to set the details */
TextView tv = (TextView) v.findViewById(R.id.country_details);
ImageView img = (ImageView) v.findViewById(R.id.disco);
// ListView lines = (ListView) v.findViewById(R.id.country_list);
String[] myList = new String[] {"Hello","World","Foo","Bar", "New"};
/** Getting the bundle object passed from MainActivity ( in Landscape mode ) or from
* CountryDetailsActivity ( in Portrait Mode )
* */
Bundle b = getArguments();
/** Getting the clicked item's position and setting corresponding details in the textview of the detailed fragment */
tv.setText("Details of " + Country.name[b.getInt("position")]);
img.setImageResource(DiscoImage.flags[b.getInt("position")]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, ??);
setListAdapter(adapter);
return v;
}
Country.java 正常返回此信息:
public class Country {
/** Array of countries used to display in CountryListFragment */
static String name[] = new String[] {
"BEYONCÉ","4","I Am... Sasha Fierce", "B'DAY", "Dangerously In Love"
};
}
Discoimage.java 返回此罚款:
public class DiscoImage {
static int[] flags = new int[]{
R.drawable.ic_beycd,
R.drawable.ic_4c,
R.drawable.ic_cdiam,
R.drawable.bdaycd,
R.drawable.dilcd,
};
}
此时,当您单击前一个 View 中的列表项时,下一个 View 中的图像会发生变化,Textview 也会发生变化。
我想知道如何使用 ListView 执行此操作?使用字符串创建一个 java 文件,但数据将如何布局以及如何通过
调用它 ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, NameofJavaClass.flags[b.getInt("position")]);
setListAdapter(adapter);
最佳答案
您应该使用自定义的 ArrayAdapter。
为此,您必须做两件事。
1) 创建要在 View 上的每个项目中显示的布局,并将其保存为布局文件夹中的 xml 文件。
2) 创建ArrayAdapter的子类(可以是内部的),它实现以下两个方法: 1; <SUBCLASSNAME>(Context context, int resource, item[] itemList) { super(context, resource, itemList); }
2; public View getView(int position, View convertView, ViewGroup parent)
它必须返回一个 View 。
可以在 https://www.youtube.com/watch?v=WRANgDgM2Zg 找到这方面的精彩视频示例。 。另外,如果您没有像他那样使用内部类,请创建一个类范围的 LayoutInflator (例如 private LayoutInflater inflater;
)对象并在构造函数中将其分配(#2 的第一部分),如下所示 inflater = LayoutInflater.from(context);
我希望这会有所帮助。
关于java - 更改以前的 ListView 中的 ListView 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30363005/