无法将我的应用集成到素材标签视图

时间:2016-08-16 15:05:08

标签: android

我是android开发的新手我已经创建了一个Android应用程序,现在我想将应用程序迁移到材质标签视图,但我无法理解如何做到这一点。这是我目前的代码

清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.package">

<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/MyMaterialTheme">
    <activity android:name="com.package.MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="xxxxxxxxxxxx" />
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

</application>

</manifest>

主要活动

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
   private Toolbar toolbar;
   private TabLayout tabLayout;
   private ViewPager viewPager;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
  }


    private void setupViewPager(ViewPager viewPager) {
      ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new Message(), "Message");
    adapter.addFragment(new Maps(), "Maps");
    viewPager.setAdapter(adapter);
  }

   class ViewPagerAdapter extends FragmentPagerAdapter {
      private final List<Fragment> mFragmentList = new ArrayList<>();
      private final List<String> mFragmentTitleList = new ArrayList<>();

       public ViewPagerAdapter(FragmentManager manager) {
          super(manager);
      }

     @Override
     public Fragment getItem(int position) {
         return mFragmentList.get(position);
     }

     @Override
     public int getCount() {
         return mFragmentList.size();
      }

       public void addFragment(Fragment fragment, String title) {
         mFragmentList.add(fragment);
         mFragmentTitleList.add(title);
      }

      @Override
      public CharSequence getPageTitle(int position) {
         return mFragmentTitleList.get(position);
      }
    }
  }

Maps.java(标签中的片段)

  import android.Manifest;
  import android.content.pm.PackageManager;
  import android.support.v4.app.ActivityCompat;
  import android.support.v4.app.Fragment;
  import android.support.v7.app.AppCompatActivity;
  import android.app.Activity;
  import android.os.Bundle;

   import com.google.android.gms.maps.CameraUpdateFactory;
   import com.google.android.gms.maps.GoogleMap;
   import com.google.android.gms.maps.MapFragment;
   import com.google.android.gms.maps.OnMapReadyCallback;
   import com.google.android.gms.maps.model.BitmapDescriptorFactory;
   import com.google.android.gms.maps.model.CameraPosition;
   import com.google.android.gms.maps.model.LatLng;
   import com.google.android.gms.maps.model.MarkerOptions;

  public class Maps extends Fragment implements OnMapReadyCallback {

   private int contentView;

  @Override
   public void onMapReady(GoogleMap map) {
      map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

      CameraPosition googlePlex = CameraPosition.builder()
            .target(new LatLng(37.4219999, -122.0862462))
            .zoom(16)
            .bearing(0)
            .tilt(45)
            .build();

         map.moveCamera(CameraUpdateFactory.newCameraPosition(googlePlex));
         map.addMarker(new MarkerOptions()
            .position(new LatLng(17.440466, 78.496668))
            .title("SVIT")
         .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher)));

       if (checkSelfPermission( Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&checkSelfPermission( Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        return;
        }
         map.setMyLocationEnabled(true);


     }

     private int checkSelfPermission(String accessFineLocation) {
      return 0;
   }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
       setContentView(R.layout.fragment_maps);
        MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
       mapFragment.getMapAsync(this);
   }

   public void setContentView(int contentView) {
     this.contentView = contentView;
   }
}   

Message.java(第二个标签)

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.telephony.SmsManager;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    import com.package.R;


  public class Message extends Fragment {


   private int contentView;

   public Message() {

    }

  Button sendBtn;
  EditText txtphoneNo;
  EditText txtMessage;
  Button clearBtn;
  Button mapBtn;

   @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      sendBtn = (Button) findViewById(R.id.btnSendSMS);
      txtphoneNo = (EditText) findViewById(R.id.editText);
      txtMessage = (EditText) findViewById(R.id.editText2);
      clearBtn = (Button) findViewById(R.id.btnClearSMS);
      mapBtn = (Button) findViewById(R.id.btnMaps);

      sendBtn.setOnClickListener(new View.OnClickListener() {
          public void onClick(View view) {
             sendSMSMessage();
         } 
      });
      clearBtn.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v2) {

              txtMessage.setText("");
              txtphoneNo.setText("");


          }
         });
      }

     protected void sendSMSMessage() {
      Log.i("Send SMS", "");
      String phoneNo = txtphoneNo.getText().toString();
      String message = txtMessage.getText().toString();

      try {
          SmsManager smsManager = SmsManager.getDefault();
          smsManager.sendTextMessage(phoneNo, null, message, null, null);
          Toast.makeText(getApplicationContext(), "SMS sent.", Toast.LENGTH_LONG).show();
      }

      catch (Exception e) {
          Toast.makeText(getApplicationContext(), "SMS faild, please try again.", Toast.LENGTH_LONG).show();
          e.printStackTrace();
       }
    }

     @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
    }
   @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
      // Inflate the layout for this fragment
      return inflater.inflate(R.layout.fragment_message, container, false);
    }

     public void setContentView(int contentView) {
      this.contentView = contentView;
     }
    }

Build.Gradle(app)

   apply plugin: 'com.android.application'

  android {
   compileSdkVersion 23
    buildToolsVersion '23.0.3'

    defaultConfig {
      applicationId "com.package"
      minSdkVersion 16
      targetSdkVersion 23
      versionCode 1
      versionName "3.0"
   }
    buildTypes {
       release {
          minifyEnabled false
          proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
       }
    }
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
//compile 'com.google.android.gms:play-services:9.2.1'
//compile 'com.google.android.gms:play-services:8.3.0'
compile 'com.android.support:appcompat-v7:22.2.1'
compile 'com.google.android.gms:play-services-appindexing:9.2.1'
compile 'com.google.android.gms:play-services-maps:9.4.0'
compile 'com.google.android.gms:play-services-location:9.2.1'
compile 'com.android.support:design:23.0.1'
compile 'com.android.support:support-v4:22.2.1'
 }

的build.gradle(项目)

   // Top-level build file where you can add configuration options common to    all sub-projects/modules.

  buildscript {
   repositories {
      jcenter()
   }
   dependencies {
      classpath 'com.android.tools.build:gradle:2.1.2'

      // NOTE: Do not place your application dependencies here; they belong
      // in the individual module build.gradle files
   }
 }

 allprojects {
     repositories {
       jcenter()
     }
  }    

  task clean(type: Delete) {
    delete rootProject.buildDir
}

我已经完成了许多在线教程,它在没有材料设计的情况下工作,但在尝试使用材料选项卡后,它无法正常工作。

这些是我所面临的错误

Error:(42, 33) error: cannot find symbol method findViewById(int)
Error:(69, 28) error: cannot find symbol method getApplicationContext()
Error:(43, 29) error: cannot find symbol method findViewById(int)
Error:(40, 28) error: cannot find symbol method findViewById(int)
Error:(41, 33) error: cannot find symbol method findViewById(int)
Error:(69, 20) error: onCreate(Bundle) in Maps cannot override onCreate(Bundle) in Fragment
attempting to assign weaker access privileges; was public
Error:(36, 20) error: onCreate(Bundle) in Message cannot override onCreate(Bundle) in Fragment
attempting to assign weaker access privileges; was public
Error:(72, 86) error: inconvertible types
required: MapFragment
found:    Fragment
Error:(81, 9) error: cannot find symbol method getMenuInflater()
Error:(73, 28) error: cannot find symbol method getApplicationContext()
Error:(78, 5) error: method does not override or implement a method from a supertype
:app:compileDebugJavaWithJavac FAILED
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.

> Compilation failed; see the compiler error output for details.

1 个答案:

答案 0 :(得分:0)

正如@ cricket_007指出的那样,FragmentActivity不同。我建议你仔细阅读development guide on fragments来了解差异。

作为一个起点,这个片段应该起作用:

public class MessageFragment extends Fragment {

    private static final String TAG = MessageFragment.class.getName();

    Button mSendButton;
    Button mClearButton;
    Button mMapButton;

    EditText mMessageEditText;
    EditText mPhoneNumberEditText;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_message, container, false);

        mSendButton = (Button) view.findViewById(R.id.btnSendSMS);
        mClearButton = (Button) view.findViewById(R.id.btnClearSMS);
        mMapButton = (Button) view.findViewById(R.id.btnMaps);

        mPhoneNumberEditText = (EditText) view.findViewById(R.id.editText);
        mMessageEditText = (EditText) view.findViewById(R.id.editText2);

        mSendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendSMSMessage();
            }
        });

        mClearButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mMessageEditText.setText("");
                mPhoneNumberEditText.setText("");
            }
        });

        return view;
    }

    protected void sendSMSMessage() {
        Log.i(TAG, "Send SMS");
        String phoneNo = mPhoneNumberEditText.getText().toString();
        String message = mMessageEditText.getText().toString();

        try {
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(phoneNo, null, message, null, null);
            Toast.makeText(getContext(), "SMS sent.", Toast.LENGTH_LONG).show();
        } catch (IllegalArgumentException exception) {
            Toast.makeText(getContext(), "SMS failed, please try again.", Toast.LENGTH_LONG).show();
            exception.printStackTrace();
        }
    }

}