我正在创建一个音乐应用,其中UI被分割成片段。 它建立在TabbedActivty项目之上。 所以我的问题是: 在MainActivity中,我将音乐文件从存储加载到数组中。(这很好。) 该Array被传递给一个帮助器类。 Fragment然后加载该数组(也可以。) 我可以设置适配器,但即使数组有值,列表视图也保持为空。 我尝试了很多代码但到目前为止没有任何工作。 但是我没有收到任何错误消息。
我的主要活动:
package needforbleed.com.music;
public class MainActivity extends AppCompatActivity {
//vars
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private ArrayList<Song> songList;
private ListView songView;
private SongAdapter songAdt;
Context c;
//methods
@Override
public void onAttachFragment(android.app.Fragment fragment) {
super.onAttachFragment(fragment);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
songList=new ArrayList<Song>();
getSongList();
c=this;
Collections.sort(songList, new Comparator<Song>() {
public int compare(Song a, Song b) {
return a.getName().compareTo(b.getName());
}
});
Helper.setSongs(songList);
/* for(int x=0;x<songList.size();x++)
{
}*/
/* for(int x=0;x<songList.size();x++) {
Toast toast = Toast.makeText(this,songList.get(x).getName(),Toast.LENGTH_SHORT);
toast.show();
}*///I used that loop to check songList for Content. It has content so that's not the error.
}
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
return view;
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position)
{
case 0:return Player.newInstance(0,"Player");
case 1:return Artists.newInstance(1,"Artists");
case 2:return Albums.newInstance(2,"Albums");
case 3:return Titles.newInstance(3,"Titles");
}
return null;
}
@Override
public int getCount() {
// Show 3 total pages.
return 4;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Player";
case 1:
return "Artists";
case 2:
return "Albums";
case 3:
return "Titles";
}
return null;
}
}
@Override
protected void onStart() {
super.onStart();
}
@Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
/*songView=Helper.getLv();
songAdt=new SongAdapter(this,songView.getId(),songList);
songView.setAdapter(songAdt);
*/
}
public void getSongList() {
ContentResolver musicResolver = getContentResolver();
Uri musicUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
if(musicCursor!=null && musicCursor.moveToFirst()){
//get columns
int titleColumn = musicCursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST);
int albumColumn=musicCursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
String thisAlbum = musicCursor.getString(albumColumn);
Song s=new Song();
s.setID(thisId);
s.setName(thisTitle);
s.setArtist(thisArtist);
s.setAlbum(thisAlbum);
songList.add(s);
}
while (musicCursor.moveToNext());
}
}
}
MainActivity XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="needforbleed.com.music.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/appbar_padding_top"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="@color/tab_color"
app:tabTextColor="@color/tab_color"
app:tabSelectedTextColor="@color/colorPrimaryDark"
/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
片段代码:
package needforbleed.com.music;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link Titles.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link Titles#newInstance} factory method to
* create an instance of this fragment.
*/
public class Titles extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "Number";
private static final String ARG_PARAM2 = "Name";
private ListView lv;
private SongAdapter sa;
// TODO: Rename and change types of parameters
private int Number;
private String Name;
private OnFragmentInteractionListener mListener;
public Titles() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Titles.
*/
// TODO: Rename and change types and number of parameters
public static Titles newInstance(int param1, String param2) {
Titles fragment = new Titles();
Bundle args = new Bundle();
args.putInt(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
Number = getArguments().getInt(ARG_PARAM1);
Name = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_titles, container, false);
lv=(ListView)view.findViewById(R.id.lv_t);
sa=new SongAdapter(this.getContext(),lv.getId(),Helper.getSongs());
lv.setAdapter(sa);
return inflater.inflate(R.layout.fragment_titles, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
片段XML
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="needforbleed.com.music.Titles">
<!-- TODO: Update blank fragment layout -->
<ListView
android:layout_width="wrap_content"
android:layout_height="523dp"
android:id="@+id/lv_t"
android:layout_gravity="left|top"
android:smoothScrollbar="true" />
</FrameLayout>
助手类
package needforbleed.com.music;
public class Helper {
private static SongAdapter s;
private static ArrayList<Song> songs;
private static ListView lv;
public static ListView getLv() {
return lv;
}
public static void setLv(ListView lv) {
lv = lv;
}
public static ArrayList<Song> getSongs() {
return songs;
}
public static void setSongs(ArrayList<Song> songs) {
Helper.songs = songs;
}
public static SongAdapter getS() {
return s;
}
public static void setS(SongAdapter s) {
Helper.s = s;
}
}
自定义适配器类
package needforbleed.com.music;
public class SongAdapter extends ArrayAdapter<Song> {
public SongAdapter(Context context, int listviewid) {
super(context, listviewid);
}
public SongAdapter(Context context, int resource, ArrayList<Song> tracks) {
super(context, resource, tracks);
}
@Override
public Song getItem(int position) {
return super.getItem(position);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.title_list,parent,false);
}
Song p = getItem(position);
if (p != null) {
TextView tt1 = (TextView) v.findViewById(R.id.song_title);
TextView tt2 = (TextView) v.findViewById(R.id.song_artist);
TextView tt3 = (TextView) v.findViewById(R.id.song_album);
if (tt1 != null) {
tt1.setText(p.getName());
}
if (tt2 != null) {
tt2.setText(p.getArtist());
}
if (tt3 != null) {
tt3.setText(p.getAlbum());
}
}
return v;
}
}
title_list xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="songPicked"
android:orientation="vertical"
android:padding="5dp" >
<TextView
android:id="@+id/song_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="@color/colorAccent"
android:textSize="22sp"
android:textStyle="bold" />
<TextView
android:id="@+id/song_artist"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="@color/colorPrimaryDark"
android:textSize="20sp" />
<TextView
android:id="@+id/song_album"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="18sp" />
</LinearLayout>
Color XML
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#f08320</color>
<color name="colorPrimaryDark">#d76e0e</color>
<color name="colorAccent">#f08320</color>
<color name="tab_color">#ffffff</color>
<color name="nav_bar">#f08320</color>
</resources>
答案 0 :(得分:1)
在片段中的创建视图中返回view
而不是
inflater.inflate(R.layout.fragment_titles, container, false);
答案 1 :(得分:1)
在onCreateView
方法中,您将返回新的膨胀视图。
应该是这样的:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_titles, container, false);
lv=(ListView)view.findViewById(R.id.lv_t);
sa=new SongAdapter(this.getContext(),lv.getId(),Helper.getSongs());
lv.setAdapter(sa);
return view;
}