我在实现片段(imageButton)时遇到了麻烦,并使其与mainActivity一起使用

时间:2017-06-26 01:19:41

标签: android android-fragments

我正在使用Android Studio,为现有应用创建广告或横幅广告。我不能使用AdMob或类似的东西。因此,我创建了一个带有ImageButton的片段,一旦我点击它就会把我带到一个网站。我在尝试实施ImageButton片段时遇到问题。

mainActivy.java

package com.android.nancysarmiento.assignmenttwo;
import android.os.ParcelFileDescriptor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity  {
    ImageView pic;
    Button toggleBtn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pic =  (ImageView) findViewById(R.id.imgDisplay);
        toggleBtn = (Button)(findViewById(R.id.toggleBtn));

    }
    public void toggleImage(View view){
        if(toggleBtn.getText().toString().equals("show me a nole")){
            pic.setImageResource(R.mipmap.nole);
            toggleBtn.setText("show me a gator");
            toggleBtn = (Button)(findViewById(R.id.toggleBtn));

       } else {
            pic.setImageResource(R.mipmap.gator);
            toggleBtn.setText("show me a nole");

        }
    }

}

banner.java

public class BannerAd extends Fragment {
    private static ImageButton bannerad;

    bannerSection activityCommander;

    public interface bannerSection {


    }
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable 
    ViewGroup container, @Nullable Bundle savedInstanceState) {
       View view = inflater.inflate(R.layout.banner, container, false);

       bannerad = (ImageButton) view.findViewById(R.id.cs_ad);

       bannerad.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View v) {
                       Uri uri = Uri.parse("http://www.cs.fsu.edu/");
                       Intent intent = new Intent(Intent.ACTION_VIEW, 
                       uri);
                       startActivity(intent);
                   }
               }
       );

       return view;
   }
}

1 个答案:

答案 0 :(得分:0)

您的片段未启动。将此方法添加到Fragment NEW

public void startFragment(Fragment fragment) {
        FragmentManager fm = getFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.replace(R.id.fragment, fragment);
        transaction.commit();
    }