在listview片段中嵌入adView的android逻辑错误 - 最新的admob sdk - 使用XML和Java进行修订

时间:2014-03-20 03:26:55

标签: java android listview android-listview admob

我终于让我的广告在我的ListView片段中工作,但现在我收到一个奇怪的逻辑错误。问题似乎是跟踪广告的位置(位置0)和列表中的其他项目。第一个项目由添加替换,单击列表上的任何项目以进行更新,然后返回到项目列表。列表名称似乎没有问题。

以下是我使用adMob XML代码进行的修订,在我的ListFragment类中使用了几行java,

我的XML代码如下:

  <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      >
    <LinearLayout 
      android:id="@+id/adsContainer"
      android:orientation="vertical"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"/>
    <com.google.android.gms.ads.AdView
      xmlns:ads="http://schemas.android.com/apk/res-auto"
      android:id="@+id/adView"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      ads:adUnitId="ca-app-pub-9999999999999999999999999"
      ads:adSize="BANNER"/>
    <ListView
      android:id="@android:id/list"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      >
     </ListView>
     <ListView
       android:id="@android:id/empty"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:paddingLeft="4dp"
       android:paddingRight="4dp"
       android:text="@string/new_empty_desc" 
      >
      </ListView>
</

在我的类中,公共类BxListFragment扩展了SherlockListFragment:

import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdRequest.Builder; import com.google.android.gms.ads.AdSize; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.doubleclick.PublisherAdRequest; import com.google.android.gms.ads.doubleclick.PublisherAdView; import com.google.android.gms.drive.query.internal.InFilter; import com.robertrichardson.bxxxyxxxxzxxxLite.R.string;

/* * BxiedListFragment Class: Sets up and displays all Bxied Activity on the list. */

public class BxiedListFragment extends SherlockListFragment {

  private ArrayList<Bxied> mBxied;
  private boolean mSubtitleVisible;
  private LayoutInflater inflater;
  private PostData[] datas;

  private Activity mainActivity;

  private static final String AD_UNIT_ID = "ca-app-pub-4409647944042499/8301167762";

  public static final String TAG = "BxiedListFragment";
  private AdView adView;

  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      setHasOptionsMenu(true);
      getSherlockActivity().setTitle(R.string.app_name);
      mBxied = BxiedLab.get(getSherlockActivity()).getBxied();
      BxiedAdapter adapter = new BxiedAdapter(mBxied);
      setListAdapter(adapter);
      setRetainInstance(true);
      mSubtitleVisible = false;

      }

  @Override
  public void onViewCreated(View view, Bundle savedInstanceState) {
      super.onViewCreated(view,  savedInstanceState);

      setEmptyText(getResources().getString(string.new_bxied_attack_empty_desc));

      registerForContextMenu(getListView());
      setHasOptionsMenu(true);
  } 

  @TargetApi(11)
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup parent,
          Bundle savedInstanceState) {

        View v = super.onCreateView(inflater,  parent,  savedInstanceState);

      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
          if (mSubtitleVisible) {
              getSherlockActivity().getSupportActionBar().setSubtitle(R.string.subtitle);
          }
      }

      ListView listView = (ListView)v.findViewById(android.R.id.list);

      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {

          // Use floating point context menus on Froyer and Gingerbread
          registerForContextMenu(listView);

      } else {

          // Use contextual action bar on Honeycomb and higher
          listView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
          listView.setMultiChoiceModeListener(new MultiChoiceModeListener()  {

              public boolean onActionItemClicked(
                      android.view.ActionMode arg0, android.view.MenuItem arg1) {
                  // TODO Auto-generated method stub
                  return false;
              }


              public boolean onCreateActionMode(android.view.ActionMode mode,
                      android.view.Menu menu) {
                  // TODO Auto-generated method stub
                  return false;
              }

              public void onDestroyActionMode(android.view.ActionMode mode) {
                  // TODO Auto-generated method stub

              }
              public boolean onPrepareActionMode(
                      android.view.ActionMode mode, android.view.Menu menu) {
                  // TODO Auto-generated method stub
                  return false;
              }

              public void onItemCheckedStateChanged(
                      android.view.ActionMode mode, int position, long id,
                      boolean checked) {
                  // TODO Auto-generated method stub
              }

          // ActionMode.Callback methods
      }); 
  }
         return v;

}

  @Override
  public void onListItemClick(ListView l, View v, int position, long id) {
      Bxied c = ((BxiedAdapter)getListAdapter()).getItem(position);
      // Start Bxied Activity
      Intent i = new Intent(getSherlockActivity(), BxiedPagerActivity.class);
      i.putExtra(BxiedFragment.EXTRA_BULLIED_ID, c.getId());
      startActivityForResult(i, 0);
  }

  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
      ((BxiedAdapter)getListAdapter()).notifyDataSetChanged();
  }

  @Override
  public void onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu, MenuInflater inflater) {
      super.onCreateOptionsMenu(menu, inflater);
      inflater.inflate(R.menu.fragment_bxied_list, menu);
   }

@TargetApi(11) @Override public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) { switch (item.getItemId()) { case R.id.settings: Intent i=new Intent(getSherlockActivity(), Preferences.class); startActivity(i); return(true); case R.id.about: i=new Intent(getSherlockActivity(),BxiedContentActivity.class); i.putExtra(BxiedContentActivity.EXTRA_FILE, "file:///android_asset/misc/about.html"); startActivity(i); return(true); case R.id.help: i=new Intent(getSherlockActivity(),BxiedContentActivity.class); i.putExtra(BxiedContentActivity.EXTRA_FILE, "file:///android_asset/misc/help.html"); startActivity(i); return(true); case R.id.disclaimer: i=new Intent(getSherlockActivity(),BxiedContentActivity.class); i.putExtra(BxiedContentActivity.EXTRA_FILE, "file:///android_asset/misc/disclaimer.html"); startActivity(i); return(true); case R.id.menu_item_new_bxied: Bxied bxied = new Bxied(); BxiedLab.get(getSherlockActivity()).addBxied(bxied); i = new Intent(getSherlockActivity(), BxiedPagerActivity.class); i.putExtra(BxiedFragment.EXTRA_BULLIED_ID, bxied.getId()); startActivityForResult(i,0); return true; default: return super.onOptionsItemSelected(item); } }

  @Override
  public void onCreateContextMenu(ContextMenu menu,View v, ContextMenuInfo menuInfo) {
      getActivity().getMenuInflater().inflate(R.menu.bxied_list_item_context, menu);
  }

  @Override
  public boolean onContextItemSelected(android.view.MenuItem item) {
      AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
      int position = info.position;
      BxiedAdapter adapter = (BxiedAdapter)getListAdapter();
      Bxied bxied = adapter.getItem(position);

      switch (item.getItemId()) {
         case R.id.menu_item_delete_bxied:
             BxiedLab.get(getActivity()).deleteBxied(bxied);
             adapter.notifyDataSetChanged();
             return true;
      }
      return super.onContextItemSelected(item);
  }

  private class BxiedAdapter extends ArrayAdapter<Bxied> {
      public BxiedAdapter(ArrayList<Bxied> bxied) {
          super(getSherlockActivity(), android.R.layout.simple_list_item_1, bxied);
      }    

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
       Log.i("1", "msg1");

      // If we weren't given a view, inflate one
      if (convertView == null) {
          convertView = getSherlockActivity().getLayoutInflater()
                  .inflate(R.layout.list_item_bxied, null);
      }  

      // Enter the view of this Bxied Attack
      Bxied c = getItem(position);

      TextView titleTextView =
              (TextView)convertView.findViewById(R.id.bxied_list_item_titleTextView);
      titleTextView.setText(c.getTitle());
      TextView dateTextView =
              (TextView)convertView.findViewById(R.id.bxied_list_item_dateTextView);
      dateTextView.setText(DateFormat.format("EEEE, MMM dd, yyyy  hh : mm a", c.getDate()).toString());

      CheckBox resolvedCheckBox =
              (CheckBox)convertView.findViewById(R.id.bxied_list_item_resolvedCheckBox);
      resolvedCheckBox.setChecked(c.isResolved());
      return convertView;
  }

}

   @Override
  public void onResume() {
      super.onResume();
      ((BxiedAdapter)getListAdapter()).notifyDataSetChanged();
      }
  }

private ArrayList<Bxied> mBxied; private boolean mSubtitleVisible; private LayoutInflater inflater; private PostData[] datas; private Activity mainActivity; private static final String AD_UNIT_ID = "ca-app-pub-4409647944042499/8301167762"; public static final String TAG = "BxiedListFragment"; private AdView adView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); getSherlockActivity().setTitle(R.string.app_name); mBxied = BxiedLab.get(getSherlockActivity()).getBxied(); BxiedAdapter adapter = new BxiedAdapter(mBxied); setListAdapter(adapter); setRetainInstance(true); mSubtitleVisible = false; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); setEmptyText(getResources().getString(string.new_bxied_attack_empty_desc)); registerForContextMenu(getListView()); setHasOptionsMenu(true); } @TargetApi(11) @Override public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { View v = super.onCreateView(inflater, parent, savedInstanceState); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { if (mSubtitleVisible) { getSherlockActivity().getSupportActionBar().setSubtitle(R.string.subtitle); } } ListView listView = (ListView)v.findViewById(android.R.id.list); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { // Use floating point context menus on Froyer and Gingerbread registerForContextMenu(listView); } else { // Use contextual action bar on Honeycomb and higher listView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE); listView.setMultiChoiceModeListener(new MultiChoiceModeListener() { public boolean onActionItemClicked( android.view.ActionMode arg0, android.view.MenuItem arg1) { // TODO Auto-generated method stub return false; } public boolean onCreateActionMode(android.view.ActionMode mode, android.view.Menu menu) { // TODO Auto-generated method stub return false; } public void onDestroyActionMode(android.view.ActionMode mode) { // TODO Auto-generated method stub } public boolean onPrepareActionMode( android.view.ActionMode mode, android.view.Menu menu) { // TODO Auto-generated method stub return false; } public void onItemCheckedStateChanged( android.view.ActionMode mode, int position, long id, boolean checked) { // TODO Auto-generated method stub } // ActionMode.Callback methods }); } return v;

我正在尝试在上面的ListFragment中添加这段代码。目前我得到一个语法错误findVuewById(int)undefined。我的问题是,我最好在我的listfragment中插入这段代码,将广告放在上面的XML中吗?   @Override public void onListItemClick(ListView l, View v, int position, long id) { Bxied c = ((BxiedAdapter)getListAdapter()).getItem(position); // Start Bxied Activity Intent i = new Intent(getSherlockActivity(), BxiedPagerActivity.class); i.putExtra(BxiedFragment.EXTRA_BULLIED_ID, c.getId()); startActivityForResult(i, 0); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { ((BxiedAdapter)getListAdapter()).notifyDataSetChanged(); } @Override public void onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.fragment_bxied_list, menu); }

@Override public void onCreateContextMenu(ContextMenu menu,View v, ContextMenuInfo menuInfo) { getActivity().getMenuInflater().inflate(R.menu.bxied_list_item_context, menu); } @Override public boolean onContextItemSelected(android.view.MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo(); int position = info.position; BxiedAdapter adapter = (BxiedAdapter)getListAdapter(); Bxied bxied = adapter.getItem(position); switch (item.getItemId()) { case R.id.menu_item_delete_bxied: BxiedLab.get(getActivity()).deleteBxied(bxied); adapter.notifyDataSetChanged(); return true; } return super.onContextItemSelected(item); } private class BxiedAdapter extends ArrayAdapter<Bxied> { public BxiedAdapter(ArrayList<Bxied> bxied) { super(getSherlockActivity(), android.R.layout.simple_list_item_1, bxied); } @Override public View getView(int position, View convertView, ViewGroup parent) { Log.i("1", "msg1"); // If we weren't given a view, inflate one if (convertView == null) { convertView = getSherlockActivity().getLayoutInflater() .inflate(R.layout.list_item_bxied, null); } // Enter the view of this Bxied Attack Bxied c = getItem(position); TextView titleTextView = (TextView)convertView.findViewById(R.id.bxied_list_item_titleTextView); titleTextView.setText(c.getTitle()); TextView dateTextView = (TextView)convertView.findViewById(R.id.bxied_list_item_dateTextView); dateTextView.setText(DateFormat.format("EEEE, MMM dd, yyyy hh : mm a", c.getDate()).toString()); CheckBox resolvedCheckBox = (CheckBox)convertView.findViewById(R.id.bxied_list_item_resolvedCheckBox); resolvedCheckBox.setChecked(c.isResolved()); return convertView; }
@Override public void onResume() { super.onResume(); ((BxiedAdapter)getListAdapter()).notifyDataSetChanged(); } }

3 个答案:

答案 0 :(得分:0)

问题可能与将0设为特殊情况有关,但拥有数据源的元素也为零。列表和适配器不再对齐。

将广告视图放在标题中可能会有效。看这里: https://developer.android.com/reference/android/widget/ListView.html#addHeaderView%28android.view.View,%20java.lang.Object,%20boolean%29

答案 1 :(得分:0)

我认为您在问“我应该在哪里放置加载广告的代码?”。

如果是,那么您要将以下代码添加到ListFragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  AdView adView = (AdView)this.findViewById(R.id.adView);

  AdRequest adRequest = new AdRequest.Builder()
      .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
      .addTestDevice("TEST_DEVICE_ID")
      .build();

  adView.loadAd(adRequest);

  ...
}

答案 2 :(得分:0)

仅供参考 - 我终于明白了。我最终在我的GetView中正确插入了所有广告逻辑,并在顶部发布了广告

以下是我的代码:

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
        if (position == 0)  {
            if (convertView instanceof AdView) {
       // Don’t instantiate new AdView, reuse old one
                return convertView;
        } else {
              Context mainActivity = getActivity();
          adView = new AdView(mainActivity);
          adView.setAdUnitId("ca-app-pub-9999998888888888");
          adView.setAdSize(AdSize.BANNER);                    
       // Convert the default layout parameters so that they play nice with
       // ListView.
          float density = mainActivity.getResources().getDisplayMetrics().density;
          int height = Math.round(AdSize.BANNER.getHeight() * density);
          AbsListView.LayoutParams params = new AbsListView.LayoutParams(
          AbsListView.LayoutParams.FILL_PARENT,
          height);
          adView.setLayoutParams(params);
          AdRequest adRequest = new AdRequest.Builder()
              .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
              .addTestDevice("TEST_DEVICE_ID")
              .build();
          adView.loadAd(adRequest);
          }
          convertView = adView;
         } else {
          convertView = getSherlockActivity().getLayoutInflater()
              .inflate(R.layout.list_item_bxied,null);
              // Enter the view of this Bxlied Attack
              // If we weren't given a view, inflate one
              // Enter the view of this Bxlied Attack

          Bxlied c = getItem(position);
          TextView titleTextView =
               (TextView)convertView.findViewById(R.id.bxied_list_item_titleTextView);
          titleTextView.setText(c.getTitle());
          TextView dateTextView =
               (TextView)convertView.findViewById(R.id.bxied_list_item_dateTextView);
          dateTextView.setText(DateFormat.format("EEEE, MMM dd, yyyy  hh : mm a", c.getDate()).toString());
          CheckBox resolvedCheckBox =
               (CheckBox)convertView.findViewById(R.id.bxied_list_item_resolvedCheckBox);
          resolvedCheckBox.setChecked(c.isResolved());
          }
          return convertView;
       }
    }

@Override public View getView(int position, View convertView, ViewGroup parent) { if (position == 0) { if (convertView instanceof AdView) { // Don’t instantiate new AdView, reuse old one return convertView; } else { Context mainActivity = getActivity(); adView = new AdView(mainActivity); adView.setAdUnitId("ca-app-pub-9999998888888888"); adView.setAdSize(AdSize.BANNER); // Convert the default layout parameters so that they play nice with // ListView. float density = mainActivity.getResources().getDisplayMetrics().density; int height = Math.round(AdSize.BANNER.getHeight() * density); AbsListView.LayoutParams params = new AbsListView.LayoutParams( AbsListView.LayoutParams.FILL_PARENT, height); adView.setLayoutParams(params); AdRequest adRequest = new AdRequest.Builder() .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) .addTestDevice("TEST_DEVICE_ID") .build(); adView.loadAd(adRequest); } convertView = adView; } else { convertView = getSherlockActivity().getLayoutInflater() .inflate(R.layout.list_item_bxied,null); // Enter the view of this Bxlied Attack // If we weren't given a view, inflate one // Enter the view of this Bxlied Attack Bxlied c = getItem(position); TextView titleTextView = (TextView)convertView.findViewById(R.id.bxied_list_item_titleTextView); titleTextView.setText(c.getTitle()); TextView dateTextView = (TextView)convertView.findViewById(R.id.bxied_list_item_dateTextView); dateTextView.setText(DateFormat.format("EEEE, MMM dd, yyyy hh : mm a", c.getDate()).toString()); CheckBox resolvedCheckBox = (CheckBox)convertView.findViewById(R.id.bxied_list_item_resolvedCheckBox); resolvedCheckBox.setChecked(c.isResolved()); } return convertView; } }