我有一个答案:访问每个布局 的按钮,了解如何显示特定布局的所有按钮,但我不明白这里的代码是我如何让它运行项目的其余部分完全一样上面的链接是我改变的:
package com.example.adapterlist;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity {
Map<String, Integer> layoutIds = new HashMap<String, Integer>();
ArrayList<String> arrayForArrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listView = (ListView) findViewById(R.id.mylist);
java.lang.reflect.Field[] ID_Fields = R.layout.class.getFields();
String []values=new String[ID_Fields.length];
int[] resArray = new int[ID_Fields.length];
for(int i = 0; i < ID_Fields.length; i++){
try {
resArray[i] = ID_Fields[i].getInt(null);
values[i]=getResources().getResourceEntryName(resArray[i]);
Log.v("resArray[i] " , getResources().getResourceEntryName(resArray[i]));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
iJustClickedAnItemInTheList((String) listView.getSelectedItem());
}
});
}
private void iJustClickedAnItemInTheList(String idname) {
setContentView(layoutIds.get(idname));
ArrayList<Button> allButtonsInLayout = getViewsFromViewGroup(findViewById(android.R.id.content), Button.class);
}
public static <T> ArrayList<T> getViewsFromViewGroup(View root, Class<T> clazz) {
ArrayList<T> result = new ArrayList<T>();
for (View view : getAllViewsFromRoots(root))
if (clazz.isInstance(view))
result.add(clazz.cast(view));
return result;
}
public static ArrayList<View> getAllViewsFromRoots(View...roots) {
ArrayList<View> result = new ArrayList<View>();
for (View root : roots)
getAllViews(result, root);
return result;
}
private static void getAllViews(ArrayList<View> allviews, View parent) {
allviews.add(parent);
if (parent instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup)parent;
for (int i = 0; i < viewGroup.getChildCount(); i++)
getAllViews(allviews, viewGroup.getChildAt(i));
}
}
}