我想知道 - 有没有办法在Activity之外访问android资源和/或资产文件(或来自任何其他文件夹的文件)(不传递上下文)?
没有上下文无法访问:
getResources().getIdentifier("resource_name", "drawable", getPackageName());
getAssets().open("file_in_assets_folder_name");
Run Code Online (Sandbox Code Playgroud)
如果不在Activity中则抛出异常:
try {
Class class = R.drawable.class;
Field field = class.getField("resource_name");
Integer i = new Integer(field.getInt(null));
} catch (Exception e) {}
Run Code Online (Sandbox Code Playgroud)
也试过下面,但它抱怨文件不存在(这里做错了什么?):
URL url = new URL("file:///android_asset/file_name.ext");
InputSource source = new InputSource(url.openStream());
//exception looks like so 04-10 00:40:43.382: W/System.err(5547): java.io.FileNotFoundException: /android_asset/InfoItems.xml (No such file or directory)
Run Code Online (Sandbox Code Playgroud) 我正在根据http://bartinger.at/listview-with-sectionsseparators/中描述的技术构建一个带有节的ListView .但是我想通过将convertView重用于非节项目来扩展它.但是,每次输入getView()方法时,我发现convertView变量为null.有人可以解释为什么会这样吗?
ViewHolder holder;
final ListViewItem item = items.get(position);
if (item.isSection()) {
Section section = (Section)item;
convertView = inflater.inflate(R.layout.section, null);
TextView title = (TextView) convertView.findViewById(R.id.section_title);
title.setText(section.title);
} else {
if (convertView == null) {
Log.d("Adapter", "convertView was null");
}
Server server = (Server)item;
convertView = inflater.inflate(R.layout.server_row, null);
holder = new ViewHolder();
holder.serverName = (TextView) convertView.findViewById(R.id.server_name);
holder.serverStatusIcon = (ImageView)convertView.findViewById(R.id.server_status_icon);
convertView.setTag(holder);
holder.serverName.setText(server.name);
}
return convertView;
Run Code Online (Sandbox Code Playgroud)
正在创建和显示列表而没有错误,并且包含部分和非部分项目就好了.
我遇到的问题是只显示第一个TextView(eventItemTitle)的文本.正如您所看到的,我现在已经更改为插入文字字符串,但仍然只能看到标题.
我究竟做错了什么?
布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/eventItemTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textStyle="bold"
android:textColor="#FFCC00">
</TextView>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/eventItemDescription"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>
</ScrollView>
Run Code Online (Sandbox Code Playgroud)
活动类:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.event_item);
[...]
TextView text = (TextView) findViewById(R.id.eventItemTitle);
text.setText(event.getTitle() + "\n");
TextView descTV = (TextView) findViewById(R.id.eventItemDescription);
descTV.setText("i'm here");
Run Code Online (Sandbox Code Playgroud)