Android开发:ListView未被ArrayAdapter填充,仅显示主布局
Hey there! I see exactly what's going on here—your PlaceholderFragment (which contains the ListView) isn't actually being added to your MainActivity's layout! That's why you only see the empty FrameLayout and no ListView.
核心问题
You've defined the fragment class and its layout, but you never told your MainActivity to attach this fragment to the FrameLayout with id container. Fragments don't automatically appear in your Activity; you need to explicitly add them via a Fragment Transaction.
修改步骤
Update your MainActivity's onCreate method to add the fragment to the container:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Add this block to attach the fragment to the container if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceHolderFragment()) .commit(); } } public static class PlaceHolderFragment extends Fragment { private ArrayAdapter<String> mForecastAdapter; public PlaceHolderFragment(){} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootview= inflater.inflate(R.layout.fragment_main, container, false); String[] forecastArray={ "Today","Tomorrow","Wed","Thursday","Friday","Saturday","Sunday" }; List<String> fore=new ArrayList<String>(Arrays.asList(forecastArray)); mForecastAdapter=new ArrayAdapter<String>(getActivity(),R.layout.list_item_forecast,R.id.list_item_forecast_textview,fore); ListView listview= (ListView)rootview.findViewById(R.id.listview_forecast); listview.setAdapter(mForecastAdapter); return rootview; } } }
为什么这样修改有效
- The
savedInstanceState == nullcheck ensures we only add the fragment once (not on screen rotation or other configuration changes, which would recreate the Activity). getSupportFragmentManager().beginTransaction()starts a fragment transaction,add(R.id.container, new PlaceHolderFragment())attaches your fragment to the FrameLayout container, andcommit()applies the change.
其他检查(你的代码这里没问题,但值得确认)
- Your
ArrayAdaptersetup is correct: you're using the right context (getActivity()), the correct list item layout, the TextView ID within that layout, and passing the fake data list. - All layout IDs match between your Java code and XML files (you already checked this, which is great!).
Once you make this change, run your app again—your ListView with the fake forecast data should show up perfectly!
内容的提问来源于stack exchange,提问作者Jeetesh Saxena

