【发布时间】:2018-03-01 11:54:50
【问题描述】:
我构建了一个 ListView,当我尝试运行该应用程序时,它一直说它不会加载。它需要关闭。所以我无法在 Android Studio 虚拟设备上运行它。
import android.content.res.Resources;
public class MainActivity4 extends AppCompatActivity {
ListView myListView;
String [] items;
String [] prices;
String [] descriptions;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
Resources res = getResources();
myListView = (ListView) findViewById(R.id.myListView);
items = res.getStringArray(R.array.items);
prices = res.getStringArray(R.array.prices);
descriptions = res.getStringArray(R.array.descriptions);
ItemAdapter itemAdapter = new ItemAdapter(this, items, prices,descriptions);
myListView.setAdapter(itemAdapter);
}
}
我还创建了一个 ItemAdapter 类,它继承自 BaseAdapter 以扩展布局。
物品适配器代码
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class ItemAdapter extends BaseAdapter {
LayoutInflater mInflater;
//String array of the items
String [] items;
//reference to the other arrays
String [] prices;
String [] descriptions;
//constructor for this class
public ItemAdapter(Context c, String[] items, String[] prices, String [] descriptions){
items =items;
prices=prices;
decriptions=descriptions
mInflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
//how many items are in this list
public int getCount() {
return items.length;
}
@Override
//Get an item from the list
public Object getItem(int i) {
return items[i];
}
@Override
//Get only the index of the item
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = mInflater.inflate(R.layout.my_list,null);
TextView nameTextView = (TextView) v.findViewById(R.id.nameTextView);
TextView descriptionTextView = (TextView) v.findViewById(R.id.descriptionTextView);
TextView priceTextView = (TextView) v.findViewById(R.id.priceTextView);
String name = items[i];
String desc = descriptions[i];
String cost = prices[i];
//now we put the information on the textview
nameTextView.setText(name);
descriptionTextView.setText(desc);
priceTextView.setText(cost);
return v;
//within that layout file there's going to be 3 TextViews to put in 3 strings
}
}
我也对Resources下的String文件做了一些改动
<resources>
<string name="app_name">Lists</string>
<string-array name="items">
<item>Olives</item>
<item>Tomato</item>
<item>Apple</item>
</string-array>
<string-array name="Prices">
<item>$0.99</item>
<item>$0.49</item>
<item>$.89</item>
</string-array>
<string-array name="descriptions">
<item>Fresh Olives from Saranda</item>
<item>Fresh tomatoes from Lushnja</item>
<item>Fresh apples from Korça </item>
</string-array>
当我运行应用程序时,模拟器一直说程序已停止。
怎么了?
【问题讨论】:
-
可以添加崩溃的堆栈跟踪吗?
-
请注意,列表视图是老派。尝试回收站视图。 ;)
标签: android android-layout listview android-studio layout-inflater